• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 
2 /*
3  * Local APIC virtualization
4  *
5  * Copyright (C) 2006 Qumranet, Inc.
6  * Copyright (C) 2007 Novell
7  * Copyright (C) 2007 Intel
8  * Copyright 2009 Red Hat, Inc. and/or its affiliates.
9  *
10  * Authors:
11  *   Dor Laor <dor.laor@qumranet.com>
12  *   Gregory Haskins <ghaskins@novell.com>
13  *   Yaozu (Eddie) Dong <eddie.dong@intel.com>
14  *
15  * Based on Xen 3.1 code, Copyright (c) 2004, Intel Corporation.
16  *
17  * This work is licensed under the terms of the GNU GPL, version 2.  See
18  * the COPYING file in the top-level directory.
19  */
20 
21 #include <linux/kvm_host.h>
22 #include <linux/kvm.h>
23 #include <linux/mm.h>
24 #include <linux/highmem.h>
25 #include <linux/smp.h>
26 #include <linux/hrtimer.h>
27 #include <linux/io.h>
28 #include <linux/export.h>
29 #include <linux/math64.h>
30 #include <linux/slab.h>
31 #include <asm/processor.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 "trace.h"
42 #include "x86.h"
43 #include "cpuid.h"
44 #include "hyperv.h"
45 
46 #ifndef CONFIG_X86_64
47 #define mod_64(x, y) ((x) - (y) * div64_u64(x, y))
48 #else
49 #define mod_64(x, y) ((x) % (y))
50 #endif
51 
52 #define PRId64 "d"
53 #define PRIx64 "llx"
54 #define PRIu64 "u"
55 #define PRIo64 "o"
56 
57 #define APIC_BUS_CYCLE_NS 1
58 
59 /* #define apic_debug(fmt,arg...) printk(KERN_WARNING fmt,##arg) */
60 #define apic_debug(fmt, arg...)
61 
62 /* 14 is the version for Xeon and Pentium 8.4.8*/
63 #define APIC_VERSION			(0x14UL | ((KVM_APIC_LVT_NUM - 1) << 16))
64 #define LAPIC_MMIO_LENGTH		(1 << 12)
65 /* followed define is not in apicdef.h */
66 #define APIC_SHORT_MASK			0xc0000
67 #define APIC_DEST_NOSHORT		0x0
68 #define APIC_DEST_MASK			0x800
69 #define MAX_APIC_VECTOR			256
70 #define APIC_VECTORS_PER_REG		32
71 
72 #define APIC_BROADCAST			0xFF
73 #define X2APIC_BROADCAST		0xFFFFFFFFul
74 
apic_test_vector(int vec,void * bitmap)75 static inline int apic_test_vector(int vec, void *bitmap)
76 {
77 	return test_bit(VEC_POS(vec), (bitmap) + REG_POS(vec));
78 }
79 
kvm_apic_pending_eoi(struct kvm_vcpu * vcpu,int vector)80 bool kvm_apic_pending_eoi(struct kvm_vcpu *vcpu, int vector)
81 {
82 	struct kvm_lapic *apic = vcpu->arch.apic;
83 
84 	return apic_test_vector(vector, apic->regs + APIC_ISR) ||
85 		apic_test_vector(vector, apic->regs + APIC_IRR);
86 }
87 
apic_clear_vector(int vec,void * bitmap)88 static inline void apic_clear_vector(int vec, void *bitmap)
89 {
90 	clear_bit(VEC_POS(vec), (bitmap) + REG_POS(vec));
91 }
92 
__apic_test_and_set_vector(int vec,void * bitmap)93 static inline int __apic_test_and_set_vector(int vec, void *bitmap)
94 {
95 	return __test_and_set_bit(VEC_POS(vec), (bitmap) + REG_POS(vec));
96 }
97 
__apic_test_and_clear_vector(int vec,void * bitmap)98 static inline int __apic_test_and_clear_vector(int vec, void *bitmap)
99 {
100 	return __test_and_clear_bit(VEC_POS(vec), (bitmap) + REG_POS(vec));
101 }
102 
103 struct static_key_deferred apic_hw_disabled __read_mostly;
104 struct static_key_deferred apic_sw_disabled __read_mostly;
105 
apic_enabled(struct kvm_lapic * apic)106 static inline int apic_enabled(struct kvm_lapic *apic)
107 {
108 	return kvm_apic_sw_enabled(apic) &&	kvm_apic_hw_enabled(apic);
109 }
110 
111 #define LVT_MASK	\
112 	(APIC_LVT_MASKED | APIC_SEND_PENDING | APIC_VECTOR_MASK)
113 
114 #define LINT_MASK	\
115 	(LVT_MASK | APIC_MODE_MASK | APIC_INPUT_POLARITY | \
116 	 APIC_LVT_REMOTE_IRR | APIC_LVT_LEVEL_TRIGGER)
117 
kvm_apic_map_get_logical_dest(struct kvm_apic_map * map,u32 dest_id,struct kvm_lapic *** cluster,u16 * mask)118 static inline bool kvm_apic_map_get_logical_dest(struct kvm_apic_map *map,
119 		u32 dest_id, struct kvm_lapic ***cluster, u16 *mask) {
120 	switch (map->mode) {
121 	case KVM_APIC_MODE_X2APIC: {
122 		u32 offset = (dest_id >> 16) * 16;
123 		u32 max_apic_id = map->max_apic_id;
124 
125 		if (offset <= max_apic_id) {
126 			u8 cluster_size = min(max_apic_id - offset + 1, 16U);
127 
128 			*cluster = &map->phys_map[offset];
129 			*mask = dest_id & (0xffff >> (16 - cluster_size));
130 		} else {
131 			*mask = 0;
132 		}
133 
134 		return true;
135 		}
136 	case KVM_APIC_MODE_XAPIC_FLAT:
137 		*cluster = map->xapic_flat_map;
138 		*mask = dest_id & 0xff;
139 		return true;
140 	case KVM_APIC_MODE_XAPIC_CLUSTER:
141 		*cluster = map->xapic_cluster_map[(dest_id >> 4) & 0xf];
142 		*mask = dest_id & 0xf;
143 		return true;
144 	default:
145 		/* Not optimized. */
146 		return false;
147 	}
148 }
149 
kvm_apic_map_free(struct rcu_head * rcu)150 static void kvm_apic_map_free(struct rcu_head *rcu)
151 {
152 	struct kvm_apic_map *map = container_of(rcu, struct kvm_apic_map, rcu);
153 
154 	kvfree(map);
155 }
156 
recalculate_apic_map(struct kvm * kvm)157 static void recalculate_apic_map(struct kvm *kvm)
158 {
159 	struct kvm_apic_map *new, *old = NULL;
160 	struct kvm_vcpu *vcpu;
161 	int i;
162 	u32 max_id = 255;
163 
164 	mutex_lock(&kvm->arch.apic_map_lock);
165 
166 	kvm_for_each_vcpu(i, vcpu, kvm)
167 		if (kvm_apic_present(vcpu))
168 			max_id = max(max_id, kvm_apic_id(vcpu->arch.apic));
169 
170 	new = kvm_kvzalloc(sizeof(struct kvm_apic_map) +
171 	                   sizeof(struct kvm_lapic *) * ((u64)max_id + 1));
172 
173 	if (!new)
174 		goto out;
175 
176 	new->max_apic_id = max_id;
177 
178 	kvm_for_each_vcpu(i, vcpu, kvm) {
179 		struct kvm_lapic *apic = vcpu->arch.apic;
180 		struct kvm_lapic **cluster;
181 		u16 mask;
182 		u32 ldr, aid;
183 
184 		if (!kvm_apic_present(vcpu))
185 			continue;
186 
187 		aid = kvm_apic_id(apic);
188 		ldr = kvm_lapic_get_reg(apic, APIC_LDR);
189 
190 		if (aid <= new->max_apic_id)
191 			new->phys_map[aid] = apic;
192 
193 		if (apic_x2apic_mode(apic)) {
194 			new->mode |= KVM_APIC_MODE_X2APIC;
195 		} else if (ldr) {
196 			ldr = GET_APIC_LOGICAL_ID(ldr);
197 			if (kvm_lapic_get_reg(apic, APIC_DFR) == APIC_DFR_FLAT)
198 				new->mode |= KVM_APIC_MODE_XAPIC_FLAT;
199 			else
200 				new->mode |= KVM_APIC_MODE_XAPIC_CLUSTER;
201 		}
202 
203 		if (!kvm_apic_map_get_logical_dest(new, ldr, &cluster, &mask))
204 			continue;
205 
206 		if (mask)
207 			cluster[ffs(mask) - 1] = apic;
208 	}
209 out:
210 	old = rcu_dereference_protected(kvm->arch.apic_map,
211 			lockdep_is_held(&kvm->arch.apic_map_lock));
212 	rcu_assign_pointer(kvm->arch.apic_map, new);
213 	mutex_unlock(&kvm->arch.apic_map_lock);
214 
215 	if (old)
216 		call_rcu(&old->rcu, kvm_apic_map_free);
217 
218 	kvm_make_scan_ioapic_request(kvm);
219 }
220 
apic_set_spiv(struct kvm_lapic * apic,u32 val)221 static inline void apic_set_spiv(struct kvm_lapic *apic, u32 val)
222 {
223 	bool enabled = val & APIC_SPIV_APIC_ENABLED;
224 
225 	kvm_lapic_set_reg(apic, APIC_SPIV, val);
226 
227 	if (enabled != apic->sw_enabled) {
228 		apic->sw_enabled = enabled;
229 		if (enabled) {
230 			static_key_slow_dec_deferred(&apic_sw_disabled);
231 			recalculate_apic_map(apic->vcpu->kvm);
232 		} else
233 			static_key_slow_inc(&apic_sw_disabled.key);
234 	}
235 }
236 
kvm_apic_set_xapic_id(struct kvm_lapic * apic,u8 id)237 static inline void kvm_apic_set_xapic_id(struct kvm_lapic *apic, u8 id)
238 {
239 	kvm_lapic_set_reg(apic, APIC_ID, id << 24);
240 	recalculate_apic_map(apic->vcpu->kvm);
241 }
242 
kvm_apic_set_ldr(struct kvm_lapic * apic,u32 id)243 static inline void kvm_apic_set_ldr(struct kvm_lapic *apic, u32 id)
244 {
245 	kvm_lapic_set_reg(apic, APIC_LDR, id);
246 	recalculate_apic_map(apic->vcpu->kvm);
247 }
248 
kvm_apic_calc_x2apic_ldr(u32 id)249 static inline u32 kvm_apic_calc_x2apic_ldr(u32 id)
250 {
251 	return ((id >> 4) << 16) | (1 << (id & 0xf));
252 }
253 
kvm_apic_set_x2apic_id(struct kvm_lapic * apic,u32 id)254 static inline void kvm_apic_set_x2apic_id(struct kvm_lapic *apic, u32 id)
255 {
256 	u32 ldr = kvm_apic_calc_x2apic_ldr(id);
257 
258 	kvm_lapic_set_reg(apic, APIC_ID, id);
259 	kvm_lapic_set_reg(apic, APIC_LDR, ldr);
260 	recalculate_apic_map(apic->vcpu->kvm);
261 }
262 
apic_lvt_enabled(struct kvm_lapic * apic,int lvt_type)263 static inline int apic_lvt_enabled(struct kvm_lapic *apic, int lvt_type)
264 {
265 	return !(kvm_lapic_get_reg(apic, lvt_type) & APIC_LVT_MASKED);
266 }
267 
apic_lvt_vector(struct kvm_lapic * apic,int lvt_type)268 static inline int apic_lvt_vector(struct kvm_lapic *apic, int lvt_type)
269 {
270 	return kvm_lapic_get_reg(apic, lvt_type) & APIC_VECTOR_MASK;
271 }
272 
apic_lvtt_oneshot(struct kvm_lapic * apic)273 static inline int apic_lvtt_oneshot(struct kvm_lapic *apic)
274 {
275 	return apic->lapic_timer.timer_mode == APIC_LVT_TIMER_ONESHOT;
276 }
277 
apic_lvtt_period(struct kvm_lapic * apic)278 static inline int apic_lvtt_period(struct kvm_lapic *apic)
279 {
280 	return apic->lapic_timer.timer_mode == APIC_LVT_TIMER_PERIODIC;
281 }
282 
apic_lvtt_tscdeadline(struct kvm_lapic * apic)283 static inline int apic_lvtt_tscdeadline(struct kvm_lapic *apic)
284 {
285 	return apic->lapic_timer.timer_mode == APIC_LVT_TIMER_TSCDEADLINE;
286 }
287 
apic_lvt_nmi_mode(u32 lvt_val)288 static inline int apic_lvt_nmi_mode(u32 lvt_val)
289 {
290 	return (lvt_val & (APIC_MODE_MASK | APIC_LVT_MASKED)) == APIC_DM_NMI;
291 }
292 
kvm_apic_set_version(struct kvm_vcpu * vcpu)293 void kvm_apic_set_version(struct kvm_vcpu *vcpu)
294 {
295 	struct kvm_lapic *apic = vcpu->arch.apic;
296 	struct kvm_cpuid_entry2 *feat;
297 	u32 v = APIC_VERSION;
298 
299 	if (!lapic_in_kernel(vcpu))
300 		return;
301 
302 	feat = kvm_find_cpuid_entry(apic->vcpu, 0x1, 0);
303 	if (feat && (feat->ecx & (1 << (X86_FEATURE_X2APIC & 31))))
304 		v |= APIC_LVR_DIRECTED_EOI;
305 	kvm_lapic_set_reg(apic, APIC_LVR, v);
306 }
307 
308 static const unsigned int apic_lvt_mask[KVM_APIC_LVT_NUM] = {
309 	LVT_MASK ,      /* part LVTT mask, timer mode mask added at runtime */
310 	LVT_MASK | APIC_MODE_MASK,	/* LVTTHMR */
311 	LVT_MASK | APIC_MODE_MASK,	/* LVTPC */
312 	LINT_MASK, LINT_MASK,	/* LVT0-1 */
313 	LVT_MASK		/* LVTERR */
314 };
315 
find_highest_vector(void * bitmap)316 static int find_highest_vector(void *bitmap)
317 {
318 	int vec;
319 	u32 *reg;
320 
321 	for (vec = MAX_APIC_VECTOR - APIC_VECTORS_PER_REG;
322 	     vec >= 0; vec -= APIC_VECTORS_PER_REG) {
323 		reg = bitmap + REG_POS(vec);
324 		if (*reg)
325 			return fls(*reg) - 1 + vec;
326 	}
327 
328 	return -1;
329 }
330 
count_vectors(void * bitmap)331 static u8 count_vectors(void *bitmap)
332 {
333 	int vec;
334 	u32 *reg;
335 	u8 count = 0;
336 
337 	for (vec = 0; vec < MAX_APIC_VECTOR; vec += APIC_VECTORS_PER_REG) {
338 		reg = bitmap + REG_POS(vec);
339 		count += hweight32(*reg);
340 	}
341 
342 	return count;
343 }
344 
__kvm_apic_update_irr(u32 * pir,void * regs)345 void __kvm_apic_update_irr(u32 *pir, void *regs)
346 {
347 	u32 i, pir_val;
348 
349 	for (i = 0; i <= 7; i++) {
350 		pir_val = xchg(&pir[i], 0);
351 		if (pir_val)
352 			*((u32 *)(regs + APIC_IRR + i * 0x10)) |= pir_val;
353 	}
354 }
355 EXPORT_SYMBOL_GPL(__kvm_apic_update_irr);
356 
kvm_apic_update_irr(struct kvm_vcpu * vcpu,u32 * pir)357 void kvm_apic_update_irr(struct kvm_vcpu *vcpu, u32 *pir)
358 {
359 	struct kvm_lapic *apic = vcpu->arch.apic;
360 
361 	__kvm_apic_update_irr(pir, apic->regs);
362 
363 	kvm_make_request(KVM_REQ_EVENT, vcpu);
364 }
365 EXPORT_SYMBOL_GPL(kvm_apic_update_irr);
366 
apic_search_irr(struct kvm_lapic * apic)367 static inline int apic_search_irr(struct kvm_lapic *apic)
368 {
369 	return find_highest_vector(apic->regs + APIC_IRR);
370 }
371 
apic_find_highest_irr(struct kvm_lapic * apic)372 static inline int apic_find_highest_irr(struct kvm_lapic *apic)
373 {
374 	int result;
375 
376 	/*
377 	 * Note that irr_pending is just a hint. It will be always
378 	 * true with virtual interrupt delivery enabled.
379 	 */
380 	if (!apic->irr_pending)
381 		return -1;
382 
383 	if (apic->vcpu->arch.apicv_active)
384 		kvm_x86_ops->sync_pir_to_irr(apic->vcpu);
385 	result = apic_search_irr(apic);
386 	ASSERT(result == -1 || result >= 16);
387 
388 	return result;
389 }
390 
apic_clear_irr(int vec,struct kvm_lapic * apic)391 static inline void apic_clear_irr(int vec, struct kvm_lapic *apic)
392 {
393 	struct kvm_vcpu *vcpu;
394 
395 	vcpu = apic->vcpu;
396 
397 	if (unlikely(vcpu->arch.apicv_active)) {
398 		/* try to update RVI */
399 		apic_clear_vector(vec, apic->regs + APIC_IRR);
400 		kvm_make_request(KVM_REQ_EVENT, vcpu);
401 	} else {
402 		apic->irr_pending = false;
403 		apic_clear_vector(vec, apic->regs + APIC_IRR);
404 		if (apic_search_irr(apic) != -1)
405 			apic->irr_pending = true;
406 	}
407 }
408 
apic_set_isr(int vec,struct kvm_lapic * apic)409 static inline void apic_set_isr(int vec, struct kvm_lapic *apic)
410 {
411 	struct kvm_vcpu *vcpu;
412 
413 	if (__apic_test_and_set_vector(vec, apic->regs + APIC_ISR))
414 		return;
415 
416 	vcpu = apic->vcpu;
417 
418 	/*
419 	 * With APIC virtualization enabled, all caching is disabled
420 	 * because the processor can modify ISR under the hood.  Instead
421 	 * just set SVI.
422 	 */
423 	if (unlikely(vcpu->arch.apicv_active))
424 		kvm_x86_ops->hwapic_isr_update(vcpu, vec);
425 	else {
426 		++apic->isr_count;
427 		BUG_ON(apic->isr_count > MAX_APIC_VECTOR);
428 		/*
429 		 * ISR (in service register) bit is set when injecting an interrupt.
430 		 * The highest vector is injected. Thus the latest bit set matches
431 		 * the highest bit in ISR.
432 		 */
433 		apic->highest_isr_cache = vec;
434 	}
435 }
436 
apic_find_highest_isr(struct kvm_lapic * apic)437 static inline int apic_find_highest_isr(struct kvm_lapic *apic)
438 {
439 	int result;
440 
441 	/*
442 	 * Note that isr_count is always 1, and highest_isr_cache
443 	 * is always -1, with APIC virtualization enabled.
444 	 */
445 	if (!apic->isr_count)
446 		return -1;
447 	if (likely(apic->highest_isr_cache != -1))
448 		return apic->highest_isr_cache;
449 
450 	result = find_highest_vector(apic->regs + APIC_ISR);
451 	ASSERT(result == -1 || result >= 16);
452 
453 	return result;
454 }
455 
apic_clear_isr(int vec,struct kvm_lapic * apic)456 static inline void apic_clear_isr(int vec, struct kvm_lapic *apic)
457 {
458 	struct kvm_vcpu *vcpu;
459 	if (!__apic_test_and_clear_vector(vec, apic->regs + APIC_ISR))
460 		return;
461 
462 	vcpu = apic->vcpu;
463 
464 	/*
465 	 * We do get here for APIC virtualization enabled if the guest
466 	 * uses the Hyper-V APIC enlightenment.  In this case we may need
467 	 * to trigger a new interrupt delivery by writing the SVI field;
468 	 * on the other hand isr_count and highest_isr_cache are unused
469 	 * and must be left alone.
470 	 */
471 	if (unlikely(vcpu->arch.apicv_active))
472 		kvm_x86_ops->hwapic_isr_update(vcpu,
473 					       apic_find_highest_isr(apic));
474 	else {
475 		--apic->isr_count;
476 		BUG_ON(apic->isr_count < 0);
477 		apic->highest_isr_cache = -1;
478 	}
479 }
480 
kvm_lapic_find_highest_irr(struct kvm_vcpu * vcpu)481 int kvm_lapic_find_highest_irr(struct kvm_vcpu *vcpu)
482 {
483 	/* This may race with setting of irr in __apic_accept_irq() and
484 	 * value returned may be wrong, but kvm_vcpu_kick() in __apic_accept_irq
485 	 * will cause vmexit immediately and the value will be recalculated
486 	 * on the next vmentry.
487 	 */
488 	return apic_find_highest_irr(vcpu->arch.apic);
489 }
490 
491 static int __apic_accept_irq(struct kvm_lapic *apic, int delivery_mode,
492 			     int vector, int level, int trig_mode,
493 			     struct dest_map *dest_map);
494 
kvm_apic_set_irq(struct kvm_vcpu * vcpu,struct kvm_lapic_irq * irq,struct dest_map * dest_map)495 int kvm_apic_set_irq(struct kvm_vcpu *vcpu, struct kvm_lapic_irq *irq,
496 		     struct dest_map *dest_map)
497 {
498 	struct kvm_lapic *apic = vcpu->arch.apic;
499 
500 	return __apic_accept_irq(apic, irq->delivery_mode, irq->vector,
501 			irq->level, irq->trig_mode, dest_map);
502 }
503 
pv_eoi_put_user(struct kvm_vcpu * vcpu,u8 val)504 static int pv_eoi_put_user(struct kvm_vcpu *vcpu, u8 val)
505 {
506 
507 	return kvm_write_guest_cached(vcpu->kvm, &vcpu->arch.pv_eoi.data, &val,
508 				      sizeof(val));
509 }
510 
pv_eoi_get_user(struct kvm_vcpu * vcpu,u8 * val)511 static int pv_eoi_get_user(struct kvm_vcpu *vcpu, u8 *val)
512 {
513 
514 	return kvm_read_guest_cached(vcpu->kvm, &vcpu->arch.pv_eoi.data, val,
515 				      sizeof(*val));
516 }
517 
pv_eoi_enabled(struct kvm_vcpu * vcpu)518 static inline bool pv_eoi_enabled(struct kvm_vcpu *vcpu)
519 {
520 	return vcpu->arch.pv_eoi.msr_val & KVM_MSR_ENABLED;
521 }
522 
pv_eoi_get_pending(struct kvm_vcpu * vcpu)523 static bool pv_eoi_get_pending(struct kvm_vcpu *vcpu)
524 {
525 	u8 val;
526 	if (pv_eoi_get_user(vcpu, &val) < 0)
527 		apic_debug("Can't read EOI MSR value: 0x%llx\n",
528 			   (unsigned long long)vcpu->arch.pv_eoi.msr_val);
529 	return val & 0x1;
530 }
531 
pv_eoi_set_pending(struct kvm_vcpu * vcpu)532 static void pv_eoi_set_pending(struct kvm_vcpu *vcpu)
533 {
534 	if (pv_eoi_put_user(vcpu, KVM_PV_EOI_ENABLED) < 0) {
535 		apic_debug("Can't set EOI MSR value: 0x%llx\n",
536 			   (unsigned long long)vcpu->arch.pv_eoi.msr_val);
537 		return;
538 	}
539 	__set_bit(KVM_APIC_PV_EOI_PENDING, &vcpu->arch.apic_attention);
540 }
541 
pv_eoi_clr_pending(struct kvm_vcpu * vcpu)542 static void pv_eoi_clr_pending(struct kvm_vcpu *vcpu)
543 {
544 	if (pv_eoi_put_user(vcpu, KVM_PV_EOI_DISABLED) < 0) {
545 		apic_debug("Can't clear EOI MSR value: 0x%llx\n",
546 			   (unsigned long long)vcpu->arch.pv_eoi.msr_val);
547 		return;
548 	}
549 	__clear_bit(KVM_APIC_PV_EOI_PENDING, &vcpu->arch.apic_attention);
550 }
551 
apic_update_ppr(struct kvm_lapic * apic)552 static void apic_update_ppr(struct kvm_lapic *apic)
553 {
554 	u32 tpr, isrv, ppr, old_ppr;
555 	int isr;
556 
557 	old_ppr = kvm_lapic_get_reg(apic, APIC_PROCPRI);
558 	tpr = kvm_lapic_get_reg(apic, APIC_TASKPRI);
559 	isr = apic_find_highest_isr(apic);
560 	isrv = (isr != -1) ? isr : 0;
561 
562 	if ((tpr & 0xf0) >= (isrv & 0xf0))
563 		ppr = tpr & 0xff;
564 	else
565 		ppr = isrv & 0xf0;
566 
567 	apic_debug("vlapic %p, ppr 0x%x, isr 0x%x, isrv 0x%x",
568 		   apic, ppr, isr, isrv);
569 
570 	if (old_ppr != ppr) {
571 		kvm_lapic_set_reg(apic, APIC_PROCPRI, ppr);
572 		if (ppr < old_ppr)
573 			kvm_make_request(KVM_REQ_EVENT, apic->vcpu);
574 	}
575 }
576 
apic_set_tpr(struct kvm_lapic * apic,u32 tpr)577 static void apic_set_tpr(struct kvm_lapic *apic, u32 tpr)
578 {
579 	kvm_lapic_set_reg(apic, APIC_TASKPRI, tpr);
580 	apic_update_ppr(apic);
581 }
582 
kvm_apic_broadcast(struct kvm_lapic * apic,u32 mda)583 static bool kvm_apic_broadcast(struct kvm_lapic *apic, u32 mda)
584 {
585 	if (apic_x2apic_mode(apic))
586 		return mda == X2APIC_BROADCAST;
587 
588 	return GET_APIC_DEST_FIELD(mda) == APIC_BROADCAST;
589 }
590 
kvm_apic_match_physical_addr(struct kvm_lapic * apic,u32 mda)591 static bool kvm_apic_match_physical_addr(struct kvm_lapic *apic, u32 mda)
592 {
593 	if (kvm_apic_broadcast(apic, mda))
594 		return true;
595 
596 	if (apic_x2apic_mode(apic))
597 		return mda == kvm_apic_id(apic);
598 
599 	return mda == SET_APIC_DEST_FIELD(kvm_apic_id(apic));
600 }
601 
kvm_apic_match_logical_addr(struct kvm_lapic * apic,u32 mda)602 static bool kvm_apic_match_logical_addr(struct kvm_lapic *apic, u32 mda)
603 {
604 	u32 logical_id;
605 
606 	if (kvm_apic_broadcast(apic, mda))
607 		return true;
608 
609 	logical_id = kvm_lapic_get_reg(apic, APIC_LDR);
610 
611 	if (apic_x2apic_mode(apic))
612 		return ((logical_id >> 16) == (mda >> 16))
613 		       && (logical_id & mda & 0xffff) != 0;
614 
615 	logical_id = GET_APIC_LOGICAL_ID(logical_id);
616 	mda = GET_APIC_DEST_FIELD(mda);
617 
618 	switch (kvm_lapic_get_reg(apic, APIC_DFR)) {
619 	case APIC_DFR_FLAT:
620 		return (logical_id & mda) != 0;
621 	case APIC_DFR_CLUSTER:
622 		return ((logical_id >> 4) == (mda >> 4))
623 		       && (logical_id & mda & 0xf) != 0;
624 	default:
625 		apic_debug("Bad DFR vcpu %d: %08x\n",
626 			   apic->vcpu->vcpu_id, kvm_lapic_get_reg(apic, APIC_DFR));
627 		return false;
628 	}
629 }
630 
631 /* The KVM local APIC implementation has two quirks:
632  *
633  *  - the xAPIC MDA stores the destination at bits 24-31, while this
634  *    is not true of struct kvm_lapic_irq's dest_id field.  This is
635  *    just a quirk in the API and is not problematic.
636  *
637  *  - in-kernel IOAPIC messages have to be delivered directly to
638  *    x2APIC, because the kernel does not support interrupt remapping.
639  *    In order to support broadcast without interrupt remapping, x2APIC
640  *    rewrites the destination of non-IPI messages from APIC_BROADCAST
641  *    to X2APIC_BROADCAST.
642  *
643  * The broadcast quirk can be disabled with KVM_CAP_X2APIC_API.  This is
644  * important when userspace wants to use x2APIC-format MSIs, because
645  * APIC_BROADCAST (0xff) is a legal route for "cluster 0, CPUs 0-7".
646  */
kvm_apic_mda(struct kvm_vcpu * vcpu,unsigned int dest_id,struct kvm_lapic * source,struct kvm_lapic * target)647 static u32 kvm_apic_mda(struct kvm_vcpu *vcpu, unsigned int dest_id,
648 		struct kvm_lapic *source, struct kvm_lapic *target)
649 {
650 	bool ipi = source != NULL;
651 	bool x2apic_mda = apic_x2apic_mode(ipi ? source : target);
652 
653 	if (!vcpu->kvm->arch.x2apic_broadcast_quirk_disabled &&
654 	    !ipi && dest_id == APIC_BROADCAST && x2apic_mda)
655 		return X2APIC_BROADCAST;
656 
657 	return x2apic_mda ? dest_id : SET_APIC_DEST_FIELD(dest_id);
658 }
659 
kvm_apic_match_dest(struct kvm_vcpu * vcpu,struct kvm_lapic * source,int short_hand,unsigned int dest,int dest_mode)660 bool kvm_apic_match_dest(struct kvm_vcpu *vcpu, struct kvm_lapic *source,
661 			   int short_hand, unsigned int dest, int dest_mode)
662 {
663 	struct kvm_lapic *target = vcpu->arch.apic;
664 	u32 mda = kvm_apic_mda(vcpu, dest, source, target);
665 
666 	apic_debug("target %p, source %p, dest 0x%x, "
667 		   "dest_mode 0x%x, short_hand 0x%x\n",
668 		   target, source, dest, dest_mode, short_hand);
669 
670 	ASSERT(target);
671 	switch (short_hand) {
672 	case APIC_DEST_NOSHORT:
673 		if (dest_mode == APIC_DEST_PHYSICAL)
674 			return kvm_apic_match_physical_addr(target, mda);
675 		else
676 			return kvm_apic_match_logical_addr(target, mda);
677 	case APIC_DEST_SELF:
678 		return target == source;
679 	case APIC_DEST_ALLINC:
680 		return true;
681 	case APIC_DEST_ALLBUT:
682 		return target != source;
683 	default:
684 		apic_debug("kvm: apic: Bad dest shorthand value %x\n",
685 			   short_hand);
686 		return false;
687 	}
688 }
689 EXPORT_SYMBOL_GPL(kvm_apic_match_dest);
690 
kvm_vector_to_index(u32 vector,u32 dest_vcpus,const unsigned long * bitmap,u32 bitmap_size)691 int kvm_vector_to_index(u32 vector, u32 dest_vcpus,
692 		       const unsigned long *bitmap, u32 bitmap_size)
693 {
694 	u32 mod;
695 	int i, idx = -1;
696 
697 	mod = vector % dest_vcpus;
698 
699 	for (i = 0; i <= mod; i++) {
700 		idx = find_next_bit(bitmap, bitmap_size, idx + 1);
701 		BUG_ON(idx == bitmap_size);
702 	}
703 
704 	return idx;
705 }
706 
kvm_apic_disabled_lapic_found(struct kvm * kvm)707 static void kvm_apic_disabled_lapic_found(struct kvm *kvm)
708 {
709 	if (!kvm->arch.disabled_lapic_found) {
710 		kvm->arch.disabled_lapic_found = true;
711 		printk(KERN_INFO
712 		       "Disabled LAPIC found during irq injection\n");
713 	}
714 }
715 
kvm_apic_is_broadcast_dest(struct kvm * kvm,struct kvm_lapic ** src,struct kvm_lapic_irq * irq,struct kvm_apic_map * map)716 static bool kvm_apic_is_broadcast_dest(struct kvm *kvm, struct kvm_lapic **src,
717 		struct kvm_lapic_irq *irq, struct kvm_apic_map *map)
718 {
719 	if (kvm->arch.x2apic_broadcast_quirk_disabled) {
720 		if ((irq->dest_id == APIC_BROADCAST &&
721 				map->mode != KVM_APIC_MODE_X2APIC))
722 			return true;
723 		if (irq->dest_id == X2APIC_BROADCAST)
724 			return true;
725 	} else {
726 		bool x2apic_ipi = src && *src && apic_x2apic_mode(*src);
727 		if (irq->dest_id == (x2apic_ipi ?
728 		                     X2APIC_BROADCAST : APIC_BROADCAST))
729 			return true;
730 	}
731 
732 	return false;
733 }
734 
735 /* Return true if the interrupt can be handled by using *bitmap as index mask
736  * for valid destinations in *dst array.
737  * Return false if kvm_apic_map_get_dest_lapic did nothing useful.
738  * Note: we may have zero kvm_lapic destinations when we return true, which
739  * means that the interrupt should be dropped.  In this case, *bitmap would be
740  * zero and *dst undefined.
741  */
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)742 static inline bool kvm_apic_map_get_dest_lapic(struct kvm *kvm,
743 		struct kvm_lapic **src, struct kvm_lapic_irq *irq,
744 		struct kvm_apic_map *map, struct kvm_lapic ***dst,
745 		unsigned long *bitmap)
746 {
747 	int i, lowest;
748 
749 	if (irq->shorthand == APIC_DEST_SELF && src) {
750 		*dst = src;
751 		*bitmap = 1;
752 		return true;
753 	} else if (irq->shorthand)
754 		return false;
755 
756 	if (!map || kvm_apic_is_broadcast_dest(kvm, src, irq, map))
757 		return false;
758 
759 	if (irq->dest_mode == APIC_DEST_PHYSICAL) {
760 		if (irq->dest_id > map->max_apic_id) {
761 			*bitmap = 0;
762 		} else {
763 			*dst = &map->phys_map[irq->dest_id];
764 			*bitmap = 1;
765 		}
766 		return true;
767 	}
768 
769 	*bitmap = 0;
770 	if (!kvm_apic_map_get_logical_dest(map, irq->dest_id, dst,
771 				(u16 *)bitmap))
772 		return false;
773 
774 	if (!kvm_lowest_prio_delivery(irq))
775 		return true;
776 
777 	if (!kvm_vector_hashing_enabled()) {
778 		lowest = -1;
779 		for_each_set_bit(i, bitmap, 16) {
780 			if (!(*dst)[i])
781 				continue;
782 			if (lowest < 0)
783 				lowest = i;
784 			else if (kvm_apic_compare_prio((*dst)[i]->vcpu,
785 						(*dst)[lowest]->vcpu) < 0)
786 				lowest = i;
787 		}
788 	} else {
789 		if (!*bitmap)
790 			return true;
791 
792 		lowest = kvm_vector_to_index(irq->vector, hweight16(*bitmap),
793 				bitmap, 16);
794 
795 		if (!(*dst)[lowest]) {
796 			kvm_apic_disabled_lapic_found(kvm);
797 			*bitmap = 0;
798 			return true;
799 		}
800 	}
801 
802 	*bitmap = (lowest >= 0) ? 1 << lowest : 0;
803 
804 	return true;
805 }
806 
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)807 bool kvm_irq_delivery_to_apic_fast(struct kvm *kvm, struct kvm_lapic *src,
808 		struct kvm_lapic_irq *irq, int *r, struct dest_map *dest_map)
809 {
810 	struct kvm_apic_map *map;
811 	unsigned long bitmap;
812 	struct kvm_lapic **dst = NULL;
813 	int i;
814 	bool ret;
815 
816 	*r = -1;
817 
818 	if (irq->shorthand == APIC_DEST_SELF) {
819 		*r = kvm_apic_set_irq(src->vcpu, irq, dest_map);
820 		return true;
821 	}
822 
823 	rcu_read_lock();
824 	map = rcu_dereference(kvm->arch.apic_map);
825 
826 	ret = kvm_apic_map_get_dest_lapic(kvm, &src, irq, map, &dst, &bitmap);
827 	if (ret)
828 		for_each_set_bit(i, &bitmap, 16) {
829 			if (!dst[i])
830 				continue;
831 			if (*r < 0)
832 				*r = 0;
833 			*r += kvm_apic_set_irq(dst[i]->vcpu, irq, dest_map);
834 		}
835 
836 	rcu_read_unlock();
837 	return ret;
838 }
839 
840 /*
841  * This routine tries to handler interrupts in posted mode, here is how
842  * it deals with different cases:
843  * - For single-destination interrupts, handle it in posted mode
844  * - Else if vector hashing is enabled and it is a lowest-priority
845  *   interrupt, handle it in posted mode and use the following mechanism
846  *   to find the destinaiton vCPU.
847  *	1. For lowest-priority interrupts, store all the possible
848  *	   destination vCPUs in an array.
849  *	2. Use "guest vector % max number of destination vCPUs" to find
850  *	   the right destination vCPU in the array for the lowest-priority
851  *	   interrupt.
852  * - Otherwise, use remapped mode to inject the interrupt.
853  */
kvm_intr_is_single_vcpu_fast(struct kvm * kvm,struct kvm_lapic_irq * irq,struct kvm_vcpu ** dest_vcpu)854 bool kvm_intr_is_single_vcpu_fast(struct kvm *kvm, struct kvm_lapic_irq *irq,
855 			struct kvm_vcpu **dest_vcpu)
856 {
857 	struct kvm_apic_map *map;
858 	unsigned long bitmap;
859 	struct kvm_lapic **dst = NULL;
860 	bool ret = false;
861 
862 	if (irq->shorthand)
863 		return false;
864 
865 	rcu_read_lock();
866 	map = rcu_dereference(kvm->arch.apic_map);
867 
868 	if (kvm_apic_map_get_dest_lapic(kvm, NULL, irq, map, &dst, &bitmap) &&
869 			hweight16(bitmap) == 1) {
870 		unsigned long i = find_first_bit(&bitmap, 16);
871 
872 		if (dst[i]) {
873 			*dest_vcpu = dst[i]->vcpu;
874 			ret = true;
875 		}
876 	}
877 
878 	rcu_read_unlock();
879 	return ret;
880 }
881 
882 /*
883  * Add a pending IRQ into lapic.
884  * Return 1 if successfully added and 0 if discarded.
885  */
__apic_accept_irq(struct kvm_lapic * apic,int delivery_mode,int vector,int level,int trig_mode,struct dest_map * dest_map)886 static int __apic_accept_irq(struct kvm_lapic *apic, int delivery_mode,
887 			     int vector, int level, int trig_mode,
888 			     struct dest_map *dest_map)
889 {
890 	int result = 0;
891 	struct kvm_vcpu *vcpu = apic->vcpu;
892 
893 	trace_kvm_apic_accept_irq(vcpu->vcpu_id, delivery_mode,
894 				  trig_mode, vector);
895 	switch (delivery_mode) {
896 	case APIC_DM_LOWEST:
897 		vcpu->arch.apic_arb_prio++;
898 	case APIC_DM_FIXED:
899 		if (unlikely(trig_mode && !level))
900 			break;
901 
902 		/* FIXME add logic for vcpu on reset */
903 		if (unlikely(!apic_enabled(apic)))
904 			break;
905 
906 		result = 1;
907 
908 		if (dest_map) {
909 			__set_bit(vcpu->vcpu_id, dest_map->map);
910 			dest_map->vectors[vcpu->vcpu_id] = vector;
911 		}
912 
913 		if (apic_test_vector(vector, apic->regs + APIC_TMR) != !!trig_mode) {
914 			if (trig_mode)
915 				kvm_lapic_set_vector(vector, apic->regs + APIC_TMR);
916 			else
917 				apic_clear_vector(vector, apic->regs + APIC_TMR);
918 		}
919 
920 		if (vcpu->arch.apicv_active)
921 			kvm_x86_ops->deliver_posted_interrupt(vcpu, vector);
922 		else {
923 			kvm_lapic_set_irr(vector, apic);
924 
925 			kvm_make_request(KVM_REQ_EVENT, vcpu);
926 			kvm_vcpu_kick(vcpu);
927 		}
928 		break;
929 
930 	case APIC_DM_REMRD:
931 		result = 1;
932 		vcpu->arch.pv.pv_unhalted = 1;
933 		kvm_make_request(KVM_REQ_EVENT, vcpu);
934 		kvm_vcpu_kick(vcpu);
935 		break;
936 
937 	case APIC_DM_SMI:
938 		result = 1;
939 		kvm_make_request(KVM_REQ_SMI, vcpu);
940 		kvm_vcpu_kick(vcpu);
941 		break;
942 
943 	case APIC_DM_NMI:
944 		result = 1;
945 		kvm_inject_nmi(vcpu);
946 		kvm_vcpu_kick(vcpu);
947 		break;
948 
949 	case APIC_DM_INIT:
950 		if (!trig_mode || level) {
951 			result = 1;
952 			/* assumes that there are only KVM_APIC_INIT/SIPI */
953 			apic->pending_events = (1UL << KVM_APIC_INIT);
954 			/* make sure pending_events is visible before sending
955 			 * the request */
956 			smp_wmb();
957 			kvm_make_request(KVM_REQ_EVENT, vcpu);
958 			kvm_vcpu_kick(vcpu);
959 		} else {
960 			apic_debug("Ignoring de-assert INIT to vcpu %d\n",
961 				   vcpu->vcpu_id);
962 		}
963 		break;
964 
965 	case APIC_DM_STARTUP:
966 		apic_debug("SIPI to vcpu %d vector 0x%02x\n",
967 			   vcpu->vcpu_id, vector);
968 		result = 1;
969 		apic->sipi_vector = vector;
970 		/* make sure sipi_vector is visible for the receiver */
971 		smp_wmb();
972 		set_bit(KVM_APIC_SIPI, &apic->pending_events);
973 		kvm_make_request(KVM_REQ_EVENT, vcpu);
974 		kvm_vcpu_kick(vcpu);
975 		break;
976 
977 	case APIC_DM_EXTINT:
978 		/*
979 		 * Should only be called by kvm_apic_local_deliver() with LVT0,
980 		 * before NMI watchdog was enabled. Already handled by
981 		 * kvm_apic_accept_pic_intr().
982 		 */
983 		break;
984 
985 	default:
986 		printk(KERN_ERR "TODO: unsupported delivery mode %x\n",
987 		       delivery_mode);
988 		break;
989 	}
990 	return result;
991 }
992 
kvm_apic_compare_prio(struct kvm_vcpu * vcpu1,struct kvm_vcpu * vcpu2)993 int kvm_apic_compare_prio(struct kvm_vcpu *vcpu1, struct kvm_vcpu *vcpu2)
994 {
995 	return vcpu1->arch.apic_arb_prio - vcpu2->arch.apic_arb_prio;
996 }
997 
kvm_ioapic_handles_vector(struct kvm_lapic * apic,int vector)998 static bool kvm_ioapic_handles_vector(struct kvm_lapic *apic, int vector)
999 {
1000 	return test_bit(vector, apic->vcpu->arch.ioapic_handled_vectors);
1001 }
1002 
kvm_ioapic_send_eoi(struct kvm_lapic * apic,int vector)1003 static void kvm_ioapic_send_eoi(struct kvm_lapic *apic, int vector)
1004 {
1005 	int trigger_mode;
1006 
1007 	/* Eoi the ioapic only if the ioapic doesn't own the vector. */
1008 	if (!kvm_ioapic_handles_vector(apic, vector))
1009 		return;
1010 
1011 	/* Request a KVM exit to inform the userspace IOAPIC. */
1012 	if (irqchip_split(apic->vcpu->kvm)) {
1013 		apic->vcpu->arch.pending_ioapic_eoi = vector;
1014 		kvm_make_request(KVM_REQ_IOAPIC_EOI_EXIT, apic->vcpu);
1015 		return;
1016 	}
1017 
1018 	if (apic_test_vector(vector, apic->regs + APIC_TMR))
1019 		trigger_mode = IOAPIC_LEVEL_TRIG;
1020 	else
1021 		trigger_mode = IOAPIC_EDGE_TRIG;
1022 
1023 	kvm_ioapic_update_eoi(apic->vcpu, vector, trigger_mode);
1024 }
1025 
apic_set_eoi(struct kvm_lapic * apic)1026 static int apic_set_eoi(struct kvm_lapic *apic)
1027 {
1028 	int vector = apic_find_highest_isr(apic);
1029 
1030 	trace_kvm_eoi(apic, vector);
1031 
1032 	/*
1033 	 * Not every write EOI will has corresponding ISR,
1034 	 * one example is when Kernel check timer on setup_IO_APIC
1035 	 */
1036 	if (vector == -1)
1037 		return vector;
1038 
1039 	apic_clear_isr(vector, apic);
1040 	apic_update_ppr(apic);
1041 
1042 	if (test_bit(vector, vcpu_to_synic(apic->vcpu)->vec_bitmap))
1043 		kvm_hv_synic_send_eoi(apic->vcpu, vector);
1044 
1045 	kvm_ioapic_send_eoi(apic, vector);
1046 	kvm_make_request(KVM_REQ_EVENT, apic->vcpu);
1047 	return vector;
1048 }
1049 
1050 /*
1051  * this interface assumes a trap-like exit, which has already finished
1052  * desired side effect including vISR and vPPR update.
1053  */
kvm_apic_set_eoi_accelerated(struct kvm_vcpu * vcpu,int vector)1054 void kvm_apic_set_eoi_accelerated(struct kvm_vcpu *vcpu, int vector)
1055 {
1056 	struct kvm_lapic *apic = vcpu->arch.apic;
1057 
1058 	trace_kvm_eoi(apic, vector);
1059 
1060 	kvm_ioapic_send_eoi(apic, vector);
1061 	kvm_make_request(KVM_REQ_EVENT, apic->vcpu);
1062 }
1063 EXPORT_SYMBOL_GPL(kvm_apic_set_eoi_accelerated);
1064 
apic_send_ipi(struct kvm_lapic * apic)1065 static void apic_send_ipi(struct kvm_lapic *apic)
1066 {
1067 	u32 icr_low = kvm_lapic_get_reg(apic, APIC_ICR);
1068 	u32 icr_high = kvm_lapic_get_reg(apic, APIC_ICR2);
1069 	struct kvm_lapic_irq irq;
1070 
1071 	irq.vector = icr_low & APIC_VECTOR_MASK;
1072 	irq.delivery_mode = icr_low & APIC_MODE_MASK;
1073 	irq.dest_mode = icr_low & APIC_DEST_MASK;
1074 	irq.level = (icr_low & APIC_INT_ASSERT) != 0;
1075 	irq.trig_mode = icr_low & APIC_INT_LEVELTRIG;
1076 	irq.shorthand = icr_low & APIC_SHORT_MASK;
1077 	irq.msi_redir_hint = false;
1078 	if (apic_x2apic_mode(apic))
1079 		irq.dest_id = icr_high;
1080 	else
1081 		irq.dest_id = GET_APIC_DEST_FIELD(icr_high);
1082 
1083 	trace_kvm_apic_ipi(icr_low, irq.dest_id);
1084 
1085 	apic_debug("icr_high 0x%x, icr_low 0x%x, "
1086 		   "short_hand 0x%x, dest 0x%x, trig_mode 0x%x, level 0x%x, "
1087 		   "dest_mode 0x%x, delivery_mode 0x%x, vector 0x%x, "
1088 		   "msi_redir_hint 0x%x\n",
1089 		   icr_high, icr_low, irq.shorthand, irq.dest_id,
1090 		   irq.trig_mode, irq.level, irq.dest_mode, irq.delivery_mode,
1091 		   irq.vector, irq.msi_redir_hint);
1092 
1093 	kvm_irq_delivery_to_apic(apic->vcpu->kvm, apic, &irq, NULL);
1094 }
1095 
apic_get_tmcct(struct kvm_lapic * apic)1096 static u32 apic_get_tmcct(struct kvm_lapic *apic)
1097 {
1098 	ktime_t remaining;
1099 	s64 ns;
1100 	u32 tmcct;
1101 
1102 	ASSERT(apic != NULL);
1103 
1104 	/* if initial count is 0, current count should also be 0 */
1105 	if (kvm_lapic_get_reg(apic, APIC_TMICT) == 0 ||
1106 		apic->lapic_timer.period == 0)
1107 		return 0;
1108 
1109 	remaining = hrtimer_get_remaining(&apic->lapic_timer.timer);
1110 	if (ktime_to_ns(remaining) < 0)
1111 		remaining = ktime_set(0, 0);
1112 
1113 	ns = mod_64(ktime_to_ns(remaining), apic->lapic_timer.period);
1114 	tmcct = div64_u64(ns,
1115 			 (APIC_BUS_CYCLE_NS * apic->divide_count));
1116 
1117 	return tmcct;
1118 }
1119 
__report_tpr_access(struct kvm_lapic * apic,bool write)1120 static void __report_tpr_access(struct kvm_lapic *apic, bool write)
1121 {
1122 	struct kvm_vcpu *vcpu = apic->vcpu;
1123 	struct kvm_run *run = vcpu->run;
1124 
1125 	kvm_make_request(KVM_REQ_REPORT_TPR_ACCESS, vcpu);
1126 	run->tpr_access.rip = kvm_rip_read(vcpu);
1127 	run->tpr_access.is_write = write;
1128 }
1129 
report_tpr_access(struct kvm_lapic * apic,bool write)1130 static inline void report_tpr_access(struct kvm_lapic *apic, bool write)
1131 {
1132 	if (apic->vcpu->arch.tpr_access_reporting)
1133 		__report_tpr_access(apic, write);
1134 }
1135 
__apic_read(struct kvm_lapic * apic,unsigned int offset)1136 static u32 __apic_read(struct kvm_lapic *apic, unsigned int offset)
1137 {
1138 	u32 val = 0;
1139 
1140 	if (offset >= LAPIC_MMIO_LENGTH)
1141 		return 0;
1142 
1143 	switch (offset) {
1144 	case APIC_ARBPRI:
1145 		apic_debug("Access APIC ARBPRI register which is for P6\n");
1146 		break;
1147 
1148 	case APIC_TMCCT:	/* Timer CCR */
1149 		if (apic_lvtt_tscdeadline(apic))
1150 			return 0;
1151 
1152 		val = apic_get_tmcct(apic);
1153 		break;
1154 	case APIC_PROCPRI:
1155 		apic_update_ppr(apic);
1156 		val = kvm_lapic_get_reg(apic, offset);
1157 		break;
1158 	case APIC_TASKPRI:
1159 		report_tpr_access(apic, false);
1160 		/* fall thru */
1161 	default:
1162 		val = kvm_lapic_get_reg(apic, offset);
1163 		break;
1164 	}
1165 
1166 	return val;
1167 }
1168 
to_lapic(struct kvm_io_device * dev)1169 static inline struct kvm_lapic *to_lapic(struct kvm_io_device *dev)
1170 {
1171 	return container_of(dev, struct kvm_lapic, dev);
1172 }
1173 
kvm_lapic_reg_read(struct kvm_lapic * apic,u32 offset,int len,void * data)1174 int kvm_lapic_reg_read(struct kvm_lapic *apic, u32 offset, int len,
1175 		void *data)
1176 {
1177 	unsigned char alignment = offset & 0xf;
1178 	u32 result;
1179 	/* this bitmask has a bit cleared for each reserved register */
1180 	static const u64 rmask = 0x43ff01ffffffe70cULL;
1181 
1182 	if ((alignment + len) > 4) {
1183 		apic_debug("KVM_APIC_READ: alignment error %x %d\n",
1184 			   offset, len);
1185 		return 1;
1186 	}
1187 
1188 	if (offset > 0x3f0 || !(rmask & (1ULL << (offset >> 4)))) {
1189 		apic_debug("KVM_APIC_READ: read reserved register %x\n",
1190 			   offset);
1191 		return 1;
1192 	}
1193 
1194 	result = __apic_read(apic, offset & ~0xf);
1195 
1196 	trace_kvm_apic_read(offset, result);
1197 
1198 	switch (len) {
1199 	case 1:
1200 	case 2:
1201 	case 4:
1202 		memcpy(data, (char *)&result + alignment, len);
1203 		break;
1204 	default:
1205 		printk(KERN_ERR "Local APIC read with len = %x, "
1206 		       "should be 1,2, or 4 instead\n", len);
1207 		break;
1208 	}
1209 	return 0;
1210 }
1211 EXPORT_SYMBOL_GPL(kvm_lapic_reg_read);
1212 
apic_mmio_in_range(struct kvm_lapic * apic,gpa_t addr)1213 static int apic_mmio_in_range(struct kvm_lapic *apic, gpa_t addr)
1214 {
1215 	return kvm_apic_hw_enabled(apic) &&
1216 	    addr >= apic->base_address &&
1217 	    addr < apic->base_address + LAPIC_MMIO_LENGTH;
1218 }
1219 
apic_mmio_read(struct kvm_vcpu * vcpu,struct kvm_io_device * this,gpa_t address,int len,void * data)1220 static int apic_mmio_read(struct kvm_vcpu *vcpu, struct kvm_io_device *this,
1221 			   gpa_t address, int len, void *data)
1222 {
1223 	struct kvm_lapic *apic = to_lapic(this);
1224 	u32 offset = address - apic->base_address;
1225 
1226 	if (!apic_mmio_in_range(apic, address))
1227 		return -EOPNOTSUPP;
1228 
1229 	kvm_lapic_reg_read(apic, offset, len, data);
1230 
1231 	return 0;
1232 }
1233 
update_divide_count(struct kvm_lapic * apic)1234 static void update_divide_count(struct kvm_lapic *apic)
1235 {
1236 	u32 tmp1, tmp2, tdcr;
1237 
1238 	tdcr = kvm_lapic_get_reg(apic, APIC_TDCR);
1239 	tmp1 = tdcr & 0xf;
1240 	tmp2 = ((tmp1 & 0x3) | ((tmp1 & 0x8) >> 1)) + 1;
1241 	apic->divide_count = 0x1 << (tmp2 & 0x7);
1242 
1243 	apic_debug("timer divide count is 0x%x\n",
1244 				   apic->divide_count);
1245 }
1246 
apic_update_lvtt(struct kvm_lapic * apic)1247 static void apic_update_lvtt(struct kvm_lapic *apic)
1248 {
1249 	u32 timer_mode = kvm_lapic_get_reg(apic, APIC_LVTT) &
1250 			apic->lapic_timer.timer_mode_mask;
1251 
1252 	if (apic->lapic_timer.timer_mode != timer_mode) {
1253 		apic->lapic_timer.timer_mode = timer_mode;
1254 		hrtimer_cancel(&apic->lapic_timer.timer);
1255 	}
1256 }
1257 
apic_timer_expired(struct kvm_lapic * apic)1258 static void apic_timer_expired(struct kvm_lapic *apic)
1259 {
1260 	struct kvm_vcpu *vcpu = apic->vcpu;
1261 	struct swait_queue_head *q = &vcpu->wq;
1262 	struct kvm_timer *ktimer = &apic->lapic_timer;
1263 
1264 	if (atomic_read(&apic->lapic_timer.pending))
1265 		return;
1266 
1267 	atomic_inc(&apic->lapic_timer.pending);
1268 	kvm_set_pending_timer(vcpu);
1269 
1270 	if (swait_active(q))
1271 		swake_up(q);
1272 
1273 	if (apic_lvtt_tscdeadline(apic))
1274 		ktimer->expired_tscdeadline = ktimer->tscdeadline;
1275 }
1276 
1277 /*
1278  * On APICv, this test will cause a busy wait
1279  * during a higher-priority task.
1280  */
1281 
lapic_timer_int_injected(struct kvm_vcpu * vcpu)1282 static bool lapic_timer_int_injected(struct kvm_vcpu *vcpu)
1283 {
1284 	struct kvm_lapic *apic = vcpu->arch.apic;
1285 	u32 reg = kvm_lapic_get_reg(apic, APIC_LVTT);
1286 
1287 	if (kvm_apic_hw_enabled(apic)) {
1288 		int vec = reg & APIC_VECTOR_MASK;
1289 		void *bitmap = apic->regs + APIC_ISR;
1290 
1291 		if (vcpu->arch.apicv_active)
1292 			bitmap = apic->regs + APIC_IRR;
1293 
1294 		if (apic_test_vector(vec, bitmap))
1295 			return true;
1296 	}
1297 	return false;
1298 }
1299 
wait_lapic_expire(struct kvm_vcpu * vcpu)1300 void wait_lapic_expire(struct kvm_vcpu *vcpu)
1301 {
1302 	struct kvm_lapic *apic = vcpu->arch.apic;
1303 	u64 guest_tsc, tsc_deadline;
1304 
1305 	if (!lapic_in_kernel(vcpu))
1306 		return;
1307 
1308 	if (apic->lapic_timer.expired_tscdeadline == 0)
1309 		return;
1310 
1311 	if (!lapic_timer_int_injected(vcpu))
1312 		return;
1313 
1314 	tsc_deadline = apic->lapic_timer.expired_tscdeadline;
1315 	apic->lapic_timer.expired_tscdeadline = 0;
1316 	guest_tsc = kvm_read_l1_tsc(vcpu, rdtsc());
1317 	trace_kvm_wait_lapic_expire(vcpu->vcpu_id, guest_tsc - tsc_deadline);
1318 
1319 	/* __delay is delay_tsc whenever the hardware has TSC, thus always.  */
1320 	if (guest_tsc < tsc_deadline)
1321 		__delay(min(tsc_deadline - guest_tsc,
1322 			nsec_to_cycles(vcpu, lapic_timer_advance_ns)));
1323 }
1324 
start_sw_tscdeadline(struct kvm_lapic * apic)1325 static void start_sw_tscdeadline(struct kvm_lapic *apic)
1326 {
1327 	u64 guest_tsc, tscdeadline = apic->lapic_timer.tscdeadline;
1328 	u64 ns = 0;
1329 	ktime_t expire;
1330 	struct kvm_vcpu *vcpu = apic->vcpu;
1331 	unsigned long this_tsc_khz = vcpu->arch.virtual_tsc_khz;
1332 	unsigned long flags;
1333 	ktime_t now;
1334 
1335 	if (unlikely(!tscdeadline || !this_tsc_khz))
1336 		return;
1337 
1338 	local_irq_save(flags);
1339 
1340 	now = apic->lapic_timer.timer.base->get_time();
1341 	guest_tsc = kvm_read_l1_tsc(vcpu, rdtsc());
1342 	if (likely(tscdeadline > guest_tsc)) {
1343 		ns = (tscdeadline - guest_tsc) * 1000000ULL;
1344 		do_div(ns, this_tsc_khz);
1345 		expire = ktime_add_ns(now, ns);
1346 		expire = ktime_sub_ns(expire, lapic_timer_advance_ns);
1347 		hrtimer_start(&apic->lapic_timer.timer,
1348 				expire, HRTIMER_MODE_ABS_PINNED);
1349 	} else
1350 		apic_timer_expired(apic);
1351 
1352 	local_irq_restore(flags);
1353 }
1354 
kvm_lapic_hv_timer_in_use(struct kvm_vcpu * vcpu)1355 bool kvm_lapic_hv_timer_in_use(struct kvm_vcpu *vcpu)
1356 {
1357 	if (!lapic_in_kernel(vcpu))
1358 		return false;
1359 
1360 	return vcpu->arch.apic->lapic_timer.hv_timer_in_use;
1361 }
1362 EXPORT_SYMBOL_GPL(kvm_lapic_hv_timer_in_use);
1363 
cancel_hv_tscdeadline(struct kvm_lapic * apic)1364 static void cancel_hv_tscdeadline(struct kvm_lapic *apic)
1365 {
1366 	preempt_disable();
1367 	kvm_x86_ops->cancel_hv_timer(apic->vcpu);
1368 	apic->lapic_timer.hv_timer_in_use = false;
1369 	preempt_enable();
1370 }
1371 
kvm_lapic_expired_hv_timer(struct kvm_vcpu * vcpu)1372 void kvm_lapic_expired_hv_timer(struct kvm_vcpu *vcpu)
1373 {
1374 	struct kvm_lapic *apic = vcpu->arch.apic;
1375 
1376 	WARN_ON(!apic->lapic_timer.hv_timer_in_use);
1377 	WARN_ON(swait_active(&vcpu->wq));
1378 	cancel_hv_tscdeadline(apic);
1379 	apic_timer_expired(apic);
1380 }
1381 EXPORT_SYMBOL_GPL(kvm_lapic_expired_hv_timer);
1382 
start_hv_tscdeadline(struct kvm_lapic * apic)1383 static bool start_hv_tscdeadline(struct kvm_lapic *apic)
1384 {
1385 	u64 tscdeadline = apic->lapic_timer.tscdeadline;
1386 
1387 	if (atomic_read(&apic->lapic_timer.pending) ||
1388 		kvm_x86_ops->set_hv_timer(apic->vcpu, tscdeadline)) {
1389 		if (apic->lapic_timer.hv_timer_in_use)
1390 			cancel_hv_tscdeadline(apic);
1391 	} else {
1392 		apic->lapic_timer.hv_timer_in_use = true;
1393 		hrtimer_cancel(&apic->lapic_timer.timer);
1394 
1395 		/* In case the sw timer triggered in the window */
1396 		if (atomic_read(&apic->lapic_timer.pending))
1397 			cancel_hv_tscdeadline(apic);
1398 	}
1399 	trace_kvm_hv_timer_state(apic->vcpu->vcpu_id,
1400 			apic->lapic_timer.hv_timer_in_use);
1401 	return apic->lapic_timer.hv_timer_in_use;
1402 }
1403 
kvm_lapic_switch_to_hv_timer(struct kvm_vcpu * vcpu)1404 void kvm_lapic_switch_to_hv_timer(struct kvm_vcpu *vcpu)
1405 {
1406 	struct kvm_lapic *apic = vcpu->arch.apic;
1407 
1408 	WARN_ON(apic->lapic_timer.hv_timer_in_use);
1409 
1410 	if (apic_lvtt_tscdeadline(apic))
1411 		start_hv_tscdeadline(apic);
1412 }
1413 EXPORT_SYMBOL_GPL(kvm_lapic_switch_to_hv_timer);
1414 
kvm_lapic_switch_to_sw_timer(struct kvm_vcpu * vcpu)1415 void kvm_lapic_switch_to_sw_timer(struct kvm_vcpu *vcpu)
1416 {
1417 	struct kvm_lapic *apic = vcpu->arch.apic;
1418 
1419 	/* Possibly the TSC deadline timer is not enabled yet */
1420 	if (!apic->lapic_timer.hv_timer_in_use)
1421 		return;
1422 
1423 	cancel_hv_tscdeadline(apic);
1424 
1425 	if (atomic_read(&apic->lapic_timer.pending))
1426 		return;
1427 
1428 	start_sw_tscdeadline(apic);
1429 }
1430 EXPORT_SYMBOL_GPL(kvm_lapic_switch_to_sw_timer);
1431 
start_apic_timer(struct kvm_lapic * apic)1432 static void start_apic_timer(struct kvm_lapic *apic)
1433 {
1434 	ktime_t now;
1435 
1436 	atomic_set(&apic->lapic_timer.pending, 0);
1437 
1438 	if (apic_lvtt_period(apic) || apic_lvtt_oneshot(apic)) {
1439 		/* lapic timer in oneshot or periodic mode */
1440 		now = apic->lapic_timer.timer.base->get_time();
1441 		apic->lapic_timer.period = (u64)kvm_lapic_get_reg(apic, APIC_TMICT)
1442 			    * APIC_BUS_CYCLE_NS * apic->divide_count;
1443 
1444 		if (!apic->lapic_timer.period)
1445 			return;
1446 		/*
1447 		 * Do not allow the guest to program periodic timers with small
1448 		 * interval, since the hrtimers are not throttled by the host
1449 		 * scheduler.
1450 		 */
1451 		if (apic_lvtt_period(apic)) {
1452 			s64 min_period = min_timer_period_us * 1000LL;
1453 
1454 			if (apic->lapic_timer.period < min_period) {
1455 				pr_info_ratelimited(
1456 				    "kvm: vcpu %i: requested %lld ns "
1457 				    "lapic timer period limited to %lld ns\n",
1458 				    apic->vcpu->vcpu_id,
1459 				    apic->lapic_timer.period, min_period);
1460 				apic->lapic_timer.period = min_period;
1461 			}
1462 		}
1463 
1464 		hrtimer_start(&apic->lapic_timer.timer,
1465 			      ktime_add_ns(now, apic->lapic_timer.period),
1466 			      HRTIMER_MODE_ABS_PINNED);
1467 
1468 		apic_debug("%s: bus cycle is %" PRId64 "ns, now 0x%016"
1469 			   PRIx64 ", "
1470 			   "timer initial count 0x%x, period %lldns, "
1471 			   "expire @ 0x%016" PRIx64 ".\n", __func__,
1472 			   APIC_BUS_CYCLE_NS, ktime_to_ns(now),
1473 			   kvm_lapic_get_reg(apic, APIC_TMICT),
1474 			   apic->lapic_timer.period,
1475 			   ktime_to_ns(ktime_add_ns(now,
1476 					apic->lapic_timer.period)));
1477 	} else if (apic_lvtt_tscdeadline(apic)) {
1478 		if (!(kvm_x86_ops->set_hv_timer && start_hv_tscdeadline(apic)))
1479 			start_sw_tscdeadline(apic);
1480 	}
1481 }
1482 
apic_manage_nmi_watchdog(struct kvm_lapic * apic,u32 lvt0_val)1483 static void apic_manage_nmi_watchdog(struct kvm_lapic *apic, u32 lvt0_val)
1484 {
1485 	bool lvt0_in_nmi_mode = apic_lvt_nmi_mode(lvt0_val);
1486 
1487 	if (apic->lvt0_in_nmi_mode != lvt0_in_nmi_mode) {
1488 		apic->lvt0_in_nmi_mode = lvt0_in_nmi_mode;
1489 		if (lvt0_in_nmi_mode) {
1490 			apic_debug("Receive NMI setting on APIC_LVT0 "
1491 				   "for cpu %d\n", apic->vcpu->vcpu_id);
1492 			atomic_inc(&apic->vcpu->kvm->arch.vapics_in_nmi_mode);
1493 		} else
1494 			atomic_dec(&apic->vcpu->kvm->arch.vapics_in_nmi_mode);
1495 	}
1496 }
1497 
kvm_lapic_reg_write(struct kvm_lapic * apic,u32 reg,u32 val)1498 int kvm_lapic_reg_write(struct kvm_lapic *apic, u32 reg, u32 val)
1499 {
1500 	int ret = 0;
1501 
1502 	trace_kvm_apic_write(reg, val);
1503 
1504 	switch (reg) {
1505 	case APIC_ID:		/* Local APIC ID */
1506 		if (!apic_x2apic_mode(apic))
1507 			kvm_apic_set_xapic_id(apic, val >> 24);
1508 		else
1509 			ret = 1;
1510 		break;
1511 
1512 	case APIC_TASKPRI:
1513 		report_tpr_access(apic, true);
1514 		apic_set_tpr(apic, val & 0xff);
1515 		break;
1516 
1517 	case APIC_EOI:
1518 		apic_set_eoi(apic);
1519 		break;
1520 
1521 	case APIC_LDR:
1522 		if (!apic_x2apic_mode(apic))
1523 			kvm_apic_set_ldr(apic, val & APIC_LDR_MASK);
1524 		else
1525 			ret = 1;
1526 		break;
1527 
1528 	case APIC_DFR:
1529 		if (!apic_x2apic_mode(apic)) {
1530 			kvm_lapic_set_reg(apic, APIC_DFR, val | 0x0FFFFFFF);
1531 			recalculate_apic_map(apic->vcpu->kvm);
1532 		} else
1533 			ret = 1;
1534 		break;
1535 
1536 	case APIC_SPIV: {
1537 		u32 mask = 0x3ff;
1538 		if (kvm_lapic_get_reg(apic, APIC_LVR) & APIC_LVR_DIRECTED_EOI)
1539 			mask |= APIC_SPIV_DIRECTED_EOI;
1540 		apic_set_spiv(apic, val & mask);
1541 		if (!(val & APIC_SPIV_APIC_ENABLED)) {
1542 			int i;
1543 			u32 lvt_val;
1544 
1545 			for (i = 0; i < KVM_APIC_LVT_NUM; i++) {
1546 				lvt_val = kvm_lapic_get_reg(apic,
1547 						       APIC_LVTT + 0x10 * i);
1548 				kvm_lapic_set_reg(apic, APIC_LVTT + 0x10 * i,
1549 					     lvt_val | APIC_LVT_MASKED);
1550 			}
1551 			apic_update_lvtt(apic);
1552 			atomic_set(&apic->lapic_timer.pending, 0);
1553 
1554 		}
1555 		break;
1556 	}
1557 	case APIC_ICR:
1558 		/* No delay here, so we always clear the pending bit */
1559 		kvm_lapic_set_reg(apic, APIC_ICR, val & ~(1 << 12));
1560 		apic_send_ipi(apic);
1561 		break;
1562 
1563 	case APIC_ICR2:
1564 		if (!apic_x2apic_mode(apic))
1565 			val &= 0xff000000;
1566 		kvm_lapic_set_reg(apic, APIC_ICR2, val);
1567 		break;
1568 
1569 	case APIC_LVT0:
1570 		apic_manage_nmi_watchdog(apic, val);
1571 	case APIC_LVTTHMR:
1572 	case APIC_LVTPC:
1573 	case APIC_LVT1:
1574 	case APIC_LVTERR:
1575 		/* TODO: Check vector */
1576 		if (!kvm_apic_sw_enabled(apic))
1577 			val |= APIC_LVT_MASKED;
1578 
1579 		val &= apic_lvt_mask[(reg - APIC_LVTT) >> 4];
1580 		kvm_lapic_set_reg(apic, reg, val);
1581 
1582 		break;
1583 
1584 	case APIC_LVTT:
1585 		if (!kvm_apic_sw_enabled(apic))
1586 			val |= APIC_LVT_MASKED;
1587 		val &= (apic_lvt_mask[0] | apic->lapic_timer.timer_mode_mask);
1588 		kvm_lapic_set_reg(apic, APIC_LVTT, val);
1589 		apic_update_lvtt(apic);
1590 		break;
1591 
1592 	case APIC_TMICT:
1593 		if (apic_lvtt_tscdeadline(apic))
1594 			break;
1595 
1596 		hrtimer_cancel(&apic->lapic_timer.timer);
1597 		kvm_lapic_set_reg(apic, APIC_TMICT, val);
1598 		start_apic_timer(apic);
1599 		break;
1600 
1601 	case APIC_TDCR:
1602 		if (val & 4)
1603 			apic_debug("KVM_WRITE:TDCR %x\n", val);
1604 		kvm_lapic_set_reg(apic, APIC_TDCR, val);
1605 		update_divide_count(apic);
1606 		break;
1607 
1608 	case APIC_ESR:
1609 		if (apic_x2apic_mode(apic) && val != 0) {
1610 			apic_debug("KVM_WRITE:ESR not zero %x\n", val);
1611 			ret = 1;
1612 		}
1613 		break;
1614 
1615 	case APIC_SELF_IPI:
1616 		if (apic_x2apic_mode(apic)) {
1617 			kvm_lapic_reg_write(apic, APIC_ICR, 0x40000 | (val & 0xff));
1618 		} else
1619 			ret = 1;
1620 		break;
1621 	default:
1622 		ret = 1;
1623 		break;
1624 	}
1625 	if (ret)
1626 		apic_debug("Local APIC Write to read-only register %x\n", reg);
1627 	return ret;
1628 }
1629 EXPORT_SYMBOL_GPL(kvm_lapic_reg_write);
1630 
apic_mmio_write(struct kvm_vcpu * vcpu,struct kvm_io_device * this,gpa_t address,int len,const void * data)1631 static int apic_mmio_write(struct kvm_vcpu *vcpu, struct kvm_io_device *this,
1632 			    gpa_t address, int len, const void *data)
1633 {
1634 	struct kvm_lapic *apic = to_lapic(this);
1635 	unsigned int offset = address - apic->base_address;
1636 	u32 val;
1637 
1638 	if (!apic_mmio_in_range(apic, address))
1639 		return -EOPNOTSUPP;
1640 
1641 	/*
1642 	 * APIC register must be aligned on 128-bits boundary.
1643 	 * 32/64/128 bits registers must be accessed thru 32 bits.
1644 	 * Refer SDM 8.4.1
1645 	 */
1646 	if (len != 4 || (offset & 0xf)) {
1647 		/* Don't shout loud, $infamous_os would cause only noise. */
1648 		apic_debug("apic write: bad size=%d %lx\n", len, (long)address);
1649 		return 0;
1650 	}
1651 
1652 	val = *(u32*)data;
1653 
1654 	/* too common printing */
1655 	if (offset != APIC_EOI)
1656 		apic_debug("%s: offset 0x%x with length 0x%x, and value is "
1657 			   "0x%x\n", __func__, offset, len, val);
1658 
1659 	kvm_lapic_reg_write(apic, offset & 0xff0, val);
1660 
1661 	return 0;
1662 }
1663 
kvm_lapic_set_eoi(struct kvm_vcpu * vcpu)1664 void kvm_lapic_set_eoi(struct kvm_vcpu *vcpu)
1665 {
1666 	kvm_lapic_reg_write(vcpu->arch.apic, APIC_EOI, 0);
1667 }
1668 EXPORT_SYMBOL_GPL(kvm_lapic_set_eoi);
1669 
1670 /* emulate APIC access in a trap manner */
kvm_apic_write_nodecode(struct kvm_vcpu * vcpu,u32 offset)1671 void kvm_apic_write_nodecode(struct kvm_vcpu *vcpu, u32 offset)
1672 {
1673 	u32 val = 0;
1674 
1675 	/* hw has done the conditional check and inst decode */
1676 	offset &= 0xff0;
1677 
1678 	kvm_lapic_reg_read(vcpu->arch.apic, offset, 4, &val);
1679 
1680 	/* TODO: optimize to just emulate side effect w/o one more write */
1681 	kvm_lapic_reg_write(vcpu->arch.apic, offset, val);
1682 }
1683 EXPORT_SYMBOL_GPL(kvm_apic_write_nodecode);
1684 
kvm_free_lapic(struct kvm_vcpu * vcpu)1685 void kvm_free_lapic(struct kvm_vcpu *vcpu)
1686 {
1687 	struct kvm_lapic *apic = vcpu->arch.apic;
1688 
1689 	if (!vcpu->arch.apic)
1690 		return;
1691 
1692 	hrtimer_cancel(&apic->lapic_timer.timer);
1693 
1694 	if (!(vcpu->arch.apic_base & MSR_IA32_APICBASE_ENABLE))
1695 		static_key_slow_dec_deferred(&apic_hw_disabled);
1696 
1697 	if (!apic->sw_enabled)
1698 		static_key_slow_dec_deferred(&apic_sw_disabled);
1699 
1700 	if (apic->regs)
1701 		free_page((unsigned long)apic->regs);
1702 
1703 	kfree(apic);
1704 }
1705 
1706 /*
1707  *----------------------------------------------------------------------
1708  * LAPIC interface
1709  *----------------------------------------------------------------------
1710  */
1711 
kvm_get_lapic_tscdeadline_msr(struct kvm_vcpu * vcpu)1712 u64 kvm_get_lapic_tscdeadline_msr(struct kvm_vcpu *vcpu)
1713 {
1714 	struct kvm_lapic *apic = vcpu->arch.apic;
1715 
1716 	if (!lapic_in_kernel(vcpu) || apic_lvtt_oneshot(apic) ||
1717 			apic_lvtt_period(apic))
1718 		return 0;
1719 
1720 	return apic->lapic_timer.tscdeadline;
1721 }
1722 
kvm_set_lapic_tscdeadline_msr(struct kvm_vcpu * vcpu,u64 data)1723 void kvm_set_lapic_tscdeadline_msr(struct kvm_vcpu *vcpu, u64 data)
1724 {
1725 	struct kvm_lapic *apic = vcpu->arch.apic;
1726 
1727 	if (!lapic_in_kernel(vcpu) || apic_lvtt_oneshot(apic) ||
1728 			apic_lvtt_period(apic))
1729 		return;
1730 
1731 	hrtimer_cancel(&apic->lapic_timer.timer);
1732 	apic->lapic_timer.tscdeadline = data;
1733 	start_apic_timer(apic);
1734 }
1735 
kvm_lapic_set_tpr(struct kvm_vcpu * vcpu,unsigned long cr8)1736 void kvm_lapic_set_tpr(struct kvm_vcpu *vcpu, unsigned long cr8)
1737 {
1738 	struct kvm_lapic *apic = vcpu->arch.apic;
1739 
1740 	apic_set_tpr(apic, ((cr8 & 0x0f) << 4)
1741 		     | (kvm_lapic_get_reg(apic, APIC_TASKPRI) & 4));
1742 }
1743 
kvm_lapic_get_cr8(struct kvm_vcpu * vcpu)1744 u64 kvm_lapic_get_cr8(struct kvm_vcpu *vcpu)
1745 {
1746 	u64 tpr;
1747 
1748 	tpr = (u64) kvm_lapic_get_reg(vcpu->arch.apic, APIC_TASKPRI);
1749 
1750 	return (tpr & 0xf0) >> 4;
1751 }
1752 
kvm_lapic_set_base(struct kvm_vcpu * vcpu,u64 value)1753 void kvm_lapic_set_base(struct kvm_vcpu *vcpu, u64 value)
1754 {
1755 	u64 old_value = vcpu->arch.apic_base;
1756 	struct kvm_lapic *apic = vcpu->arch.apic;
1757 
1758 	if (!apic) {
1759 		value |= MSR_IA32_APICBASE_BSP;
1760 		vcpu->arch.apic_base = value;
1761 		return;
1762 	}
1763 
1764 	vcpu->arch.apic_base = value;
1765 
1766 	/* update jump label if enable bit changes */
1767 	if ((old_value ^ value) & MSR_IA32_APICBASE_ENABLE) {
1768 		if (value & MSR_IA32_APICBASE_ENABLE) {
1769 			kvm_apic_set_xapic_id(apic, vcpu->vcpu_id);
1770 			static_key_slow_dec_deferred(&apic_hw_disabled);
1771 		} else {
1772 			static_key_slow_inc(&apic_hw_disabled.key);
1773 			recalculate_apic_map(vcpu->kvm);
1774 		}
1775 	}
1776 
1777 	if ((old_value ^ value) & X2APIC_ENABLE) {
1778 		if (value & X2APIC_ENABLE) {
1779 			kvm_apic_set_x2apic_id(apic, vcpu->vcpu_id);
1780 			kvm_x86_ops->set_virtual_x2apic_mode(vcpu, true);
1781 		} else
1782 			kvm_x86_ops->set_virtual_x2apic_mode(vcpu, false);
1783 	}
1784 
1785 	apic->base_address = apic->vcpu->arch.apic_base &
1786 			     MSR_IA32_APICBASE_BASE;
1787 
1788 	if ((value & MSR_IA32_APICBASE_ENABLE) &&
1789 	     apic->base_address != APIC_DEFAULT_PHYS_BASE)
1790 		pr_warn_once("APIC base relocation is unsupported by KVM");
1791 
1792 	/* with FSB delivery interrupt, we can restart APIC functionality */
1793 	apic_debug("apic base msr is 0x%016" PRIx64 ", and base address is "
1794 		   "0x%lx.\n", apic->vcpu->arch.apic_base, apic->base_address);
1795 
1796 }
1797 
kvm_lapic_reset(struct kvm_vcpu * vcpu,bool init_event)1798 void kvm_lapic_reset(struct kvm_vcpu *vcpu, bool init_event)
1799 {
1800 	struct kvm_lapic *apic;
1801 	int i;
1802 
1803 	apic_debug("%s\n", __func__);
1804 
1805 	ASSERT(vcpu);
1806 	apic = vcpu->arch.apic;
1807 	ASSERT(apic != NULL);
1808 
1809 	/* Stop the timer in case it's a reset to an active apic */
1810 	hrtimer_cancel(&apic->lapic_timer.timer);
1811 
1812 	if (!init_event) {
1813 		kvm_lapic_set_base(vcpu, APIC_DEFAULT_PHYS_BASE |
1814 		                         MSR_IA32_APICBASE_ENABLE);
1815 		kvm_apic_set_xapic_id(apic, vcpu->vcpu_id);
1816 	}
1817 	kvm_apic_set_version(apic->vcpu);
1818 
1819 	for (i = 0; i < KVM_APIC_LVT_NUM; i++)
1820 		kvm_lapic_set_reg(apic, APIC_LVTT + 0x10 * i, APIC_LVT_MASKED);
1821 	apic_update_lvtt(apic);
1822 	if (kvm_check_has_quirk(vcpu->kvm, KVM_X86_QUIRK_LINT0_REENABLED))
1823 		kvm_lapic_set_reg(apic, APIC_LVT0,
1824 			     SET_APIC_DELIVERY_MODE(0, APIC_MODE_EXTINT));
1825 	apic_manage_nmi_watchdog(apic, kvm_lapic_get_reg(apic, APIC_LVT0));
1826 
1827 	kvm_lapic_set_reg(apic, APIC_DFR, 0xffffffffU);
1828 	apic_set_spiv(apic, 0xff);
1829 	kvm_lapic_set_reg(apic, APIC_TASKPRI, 0);
1830 	if (!apic_x2apic_mode(apic))
1831 		kvm_apic_set_ldr(apic, 0);
1832 	kvm_lapic_set_reg(apic, APIC_ESR, 0);
1833 	kvm_lapic_set_reg(apic, APIC_ICR, 0);
1834 	kvm_lapic_set_reg(apic, APIC_ICR2, 0);
1835 	kvm_lapic_set_reg(apic, APIC_TDCR, 0);
1836 	kvm_lapic_set_reg(apic, APIC_TMICT, 0);
1837 	for (i = 0; i < 8; i++) {
1838 		kvm_lapic_set_reg(apic, APIC_IRR + 0x10 * i, 0);
1839 		kvm_lapic_set_reg(apic, APIC_ISR + 0x10 * i, 0);
1840 		kvm_lapic_set_reg(apic, APIC_TMR + 0x10 * i, 0);
1841 	}
1842 	apic->irr_pending = vcpu->arch.apicv_active;
1843 	apic->isr_count = vcpu->arch.apicv_active ? 1 : 0;
1844 	apic->highest_isr_cache = -1;
1845 	update_divide_count(apic);
1846 	atomic_set(&apic->lapic_timer.pending, 0);
1847 	if (kvm_vcpu_is_bsp(vcpu))
1848 		kvm_lapic_set_base(vcpu,
1849 				vcpu->arch.apic_base | MSR_IA32_APICBASE_BSP);
1850 	vcpu->arch.pv_eoi.msr_val = 0;
1851 	apic_update_ppr(apic);
1852 
1853 	vcpu->arch.apic_arb_prio = 0;
1854 	vcpu->arch.apic_attention = 0;
1855 
1856 	apic_debug("%s: vcpu=%p, id=%d, base_msr="
1857 		   "0x%016" PRIx64 ", base_address=0x%0lx.\n", __func__,
1858 		   vcpu, kvm_apic_id(apic),
1859 		   vcpu->arch.apic_base, apic->base_address);
1860 }
1861 
1862 /*
1863  *----------------------------------------------------------------------
1864  * timer interface
1865  *----------------------------------------------------------------------
1866  */
1867 
lapic_is_periodic(struct kvm_lapic * apic)1868 static bool lapic_is_periodic(struct kvm_lapic *apic)
1869 {
1870 	return apic_lvtt_period(apic);
1871 }
1872 
apic_has_pending_timer(struct kvm_vcpu * vcpu)1873 int apic_has_pending_timer(struct kvm_vcpu *vcpu)
1874 {
1875 	struct kvm_lapic *apic = vcpu->arch.apic;
1876 
1877 	if (apic_enabled(apic) && apic_lvt_enabled(apic, APIC_LVTT))
1878 		return atomic_read(&apic->lapic_timer.pending);
1879 
1880 	return 0;
1881 }
1882 
kvm_apic_local_deliver(struct kvm_lapic * apic,int lvt_type)1883 int kvm_apic_local_deliver(struct kvm_lapic *apic, int lvt_type)
1884 {
1885 	u32 reg = kvm_lapic_get_reg(apic, lvt_type);
1886 	int vector, mode, trig_mode;
1887 
1888 	if (kvm_apic_hw_enabled(apic) && !(reg & APIC_LVT_MASKED)) {
1889 		vector = reg & APIC_VECTOR_MASK;
1890 		mode = reg & APIC_MODE_MASK;
1891 		trig_mode = reg & APIC_LVT_LEVEL_TRIGGER;
1892 		return __apic_accept_irq(apic, mode, vector, 1, trig_mode,
1893 					NULL);
1894 	}
1895 	return 0;
1896 }
1897 
kvm_apic_nmi_wd_deliver(struct kvm_vcpu * vcpu)1898 void kvm_apic_nmi_wd_deliver(struct kvm_vcpu *vcpu)
1899 {
1900 	struct kvm_lapic *apic = vcpu->arch.apic;
1901 
1902 	if (apic)
1903 		kvm_apic_local_deliver(apic, APIC_LVT0);
1904 }
1905 
1906 static const struct kvm_io_device_ops apic_mmio_ops = {
1907 	.read     = apic_mmio_read,
1908 	.write    = apic_mmio_write,
1909 };
1910 
apic_timer_fn(struct hrtimer * data)1911 static enum hrtimer_restart apic_timer_fn(struct hrtimer *data)
1912 {
1913 	struct kvm_timer *ktimer = container_of(data, struct kvm_timer, timer);
1914 	struct kvm_lapic *apic = container_of(ktimer, struct kvm_lapic, lapic_timer);
1915 
1916 	apic_timer_expired(apic);
1917 
1918 	if (lapic_is_periodic(apic)) {
1919 		hrtimer_add_expires_ns(&ktimer->timer, ktimer->period);
1920 		return HRTIMER_RESTART;
1921 	} else
1922 		return HRTIMER_NORESTART;
1923 }
1924 
kvm_create_lapic(struct kvm_vcpu * vcpu)1925 int kvm_create_lapic(struct kvm_vcpu *vcpu)
1926 {
1927 	struct kvm_lapic *apic;
1928 
1929 	ASSERT(vcpu != NULL);
1930 	apic_debug("apic_init %d\n", vcpu->vcpu_id);
1931 
1932 	apic = kzalloc(sizeof(*apic), GFP_KERNEL);
1933 	if (!apic)
1934 		goto nomem;
1935 
1936 	vcpu->arch.apic = apic;
1937 
1938 	apic->regs = (void *)get_zeroed_page(GFP_KERNEL);
1939 	if (!apic->regs) {
1940 		printk(KERN_ERR "malloc apic regs error for vcpu %x\n",
1941 		       vcpu->vcpu_id);
1942 		goto nomem_free_apic;
1943 	}
1944 	apic->vcpu = vcpu;
1945 
1946 	hrtimer_init(&apic->lapic_timer.timer, CLOCK_MONOTONIC,
1947 		     HRTIMER_MODE_ABS_PINNED);
1948 	apic->lapic_timer.timer.function = apic_timer_fn;
1949 
1950 	/*
1951 	 * APIC is created enabled. This will prevent kvm_lapic_set_base from
1952 	 * thinking that APIC satet has changed.
1953 	 */
1954 	vcpu->arch.apic_base = MSR_IA32_APICBASE_ENABLE;
1955 	static_key_slow_inc(&apic_sw_disabled.key); /* sw disabled at reset */
1956 	kvm_lapic_reset(vcpu, false);
1957 	kvm_iodevice_init(&apic->dev, &apic_mmio_ops);
1958 
1959 	return 0;
1960 nomem_free_apic:
1961 	kfree(apic);
1962 nomem:
1963 	return -ENOMEM;
1964 }
1965 
kvm_apic_has_interrupt(struct kvm_vcpu * vcpu)1966 int kvm_apic_has_interrupt(struct kvm_vcpu *vcpu)
1967 {
1968 	struct kvm_lapic *apic = vcpu->arch.apic;
1969 	int highest_irr;
1970 
1971 	if (!apic_enabled(apic))
1972 		return -1;
1973 
1974 	apic_update_ppr(apic);
1975 	highest_irr = apic_find_highest_irr(apic);
1976 	if ((highest_irr == -1) ||
1977 	    ((highest_irr & 0xF0) <= kvm_lapic_get_reg(apic, APIC_PROCPRI)))
1978 		return -1;
1979 	return highest_irr;
1980 }
1981 
kvm_apic_accept_pic_intr(struct kvm_vcpu * vcpu)1982 int kvm_apic_accept_pic_intr(struct kvm_vcpu *vcpu)
1983 {
1984 	u32 lvt0 = kvm_lapic_get_reg(vcpu->arch.apic, APIC_LVT0);
1985 	int r = 0;
1986 
1987 	if (!kvm_apic_hw_enabled(vcpu->arch.apic))
1988 		r = 1;
1989 	if ((lvt0 & APIC_LVT_MASKED) == 0 &&
1990 	    GET_APIC_DELIVERY_MODE(lvt0) == APIC_MODE_EXTINT)
1991 		r = 1;
1992 	return r;
1993 }
1994 
kvm_inject_apic_timer_irqs(struct kvm_vcpu * vcpu)1995 void kvm_inject_apic_timer_irqs(struct kvm_vcpu *vcpu)
1996 {
1997 	struct kvm_lapic *apic = vcpu->arch.apic;
1998 
1999 	if (atomic_read(&apic->lapic_timer.pending) > 0) {
2000 		kvm_apic_local_deliver(apic, APIC_LVTT);
2001 		if (apic_lvtt_tscdeadline(apic))
2002 			apic->lapic_timer.tscdeadline = 0;
2003 		atomic_set(&apic->lapic_timer.pending, 0);
2004 	}
2005 }
2006 
kvm_get_apic_interrupt(struct kvm_vcpu * vcpu)2007 int kvm_get_apic_interrupt(struct kvm_vcpu *vcpu)
2008 {
2009 	int vector = kvm_apic_has_interrupt(vcpu);
2010 	struct kvm_lapic *apic = vcpu->arch.apic;
2011 
2012 	if (vector == -1)
2013 		return -1;
2014 
2015 	/*
2016 	 * We get here even with APIC virtualization enabled, if doing
2017 	 * nested virtualization and L1 runs with the "acknowledge interrupt
2018 	 * on exit" mode.  Then we cannot inject the interrupt via RVI,
2019 	 * because the process would deliver it through the IDT.
2020 	 */
2021 
2022 	apic_set_isr(vector, apic);
2023 	apic_update_ppr(apic);
2024 	apic_clear_irr(vector, apic);
2025 
2026 	if (test_bit(vector, vcpu_to_synic(vcpu)->auto_eoi_bitmap)) {
2027 		apic_clear_isr(vector, apic);
2028 		apic_update_ppr(apic);
2029 	}
2030 
2031 	return vector;
2032 }
2033 
kvm_apic_state_fixup(struct kvm_vcpu * vcpu,struct kvm_lapic_state * s,bool set)2034 static int kvm_apic_state_fixup(struct kvm_vcpu *vcpu,
2035 		struct kvm_lapic_state *s, bool set)
2036 {
2037 	if (apic_x2apic_mode(vcpu->arch.apic)) {
2038 		u32 *id = (u32 *)(s->regs + APIC_ID);
2039 		u32 *ldr = (u32 *)(s->regs + APIC_LDR);
2040 
2041 		if (vcpu->kvm->arch.x2apic_format) {
2042 			if (*id != vcpu->vcpu_id)
2043 				return -EINVAL;
2044 		} else {
2045 			if (set)
2046 				*id >>= 24;
2047 			else
2048 				*id <<= 24;
2049 		}
2050 
2051 		/* In x2APIC mode, the LDR is fixed and based on the id */
2052 		if (set)
2053 			*ldr = kvm_apic_calc_x2apic_ldr(*id);
2054 	}
2055 
2056 	return 0;
2057 }
2058 
kvm_apic_get_state(struct kvm_vcpu * vcpu,struct kvm_lapic_state * s)2059 int kvm_apic_get_state(struct kvm_vcpu *vcpu, struct kvm_lapic_state *s)
2060 {
2061 	memcpy(s->regs, vcpu->arch.apic->regs, sizeof(*s));
2062 	return kvm_apic_state_fixup(vcpu, s, false);
2063 }
2064 
kvm_apic_set_state(struct kvm_vcpu * vcpu,struct kvm_lapic_state * s)2065 int kvm_apic_set_state(struct kvm_vcpu *vcpu, struct kvm_lapic_state *s)
2066 {
2067 	struct kvm_lapic *apic = vcpu->arch.apic;
2068 	int r;
2069 
2070 
2071 	kvm_lapic_set_base(vcpu, vcpu->arch.apic_base);
2072 	/* set SPIV separately to get count of SW disabled APICs right */
2073 	apic_set_spiv(apic, *((u32 *)(s->regs + APIC_SPIV)));
2074 
2075 	r = kvm_apic_state_fixup(vcpu, s, true);
2076 	if (r)
2077 		return r;
2078 	memcpy(vcpu->arch.apic->regs, s->regs, sizeof *s);
2079 
2080 	recalculate_apic_map(vcpu->kvm);
2081 	kvm_apic_set_version(vcpu);
2082 
2083 	apic_update_ppr(apic);
2084 	hrtimer_cancel(&apic->lapic_timer.timer);
2085 	apic_update_lvtt(apic);
2086 	apic_manage_nmi_watchdog(apic, kvm_lapic_get_reg(apic, APIC_LVT0));
2087 	update_divide_count(apic);
2088 	start_apic_timer(apic);
2089 	apic->irr_pending = true;
2090 	apic->isr_count = vcpu->arch.apicv_active ?
2091 				1 : count_vectors(apic->regs + APIC_ISR);
2092 	apic->highest_isr_cache = -1;
2093 	if (vcpu->arch.apicv_active) {
2094 		if (kvm_x86_ops->apicv_post_state_restore)
2095 			kvm_x86_ops->apicv_post_state_restore(vcpu);
2096 		kvm_x86_ops->hwapic_irr_update(vcpu,
2097 				apic_find_highest_irr(apic));
2098 		kvm_x86_ops->hwapic_isr_update(vcpu,
2099 				apic_find_highest_isr(apic));
2100 	}
2101 	kvm_make_request(KVM_REQ_EVENT, vcpu);
2102 	if (ioapic_in_kernel(vcpu->kvm))
2103 		kvm_rtc_eoi_tracking_restore_one(vcpu);
2104 
2105 	vcpu->arch.apic_arb_prio = 0;
2106 
2107 	return 0;
2108 }
2109 
__kvm_migrate_apic_timer(struct kvm_vcpu * vcpu)2110 void __kvm_migrate_apic_timer(struct kvm_vcpu *vcpu)
2111 {
2112 	struct hrtimer *timer;
2113 
2114 	if (!lapic_in_kernel(vcpu))
2115 		return;
2116 
2117 	timer = &vcpu->arch.apic->lapic_timer.timer;
2118 	if (hrtimer_cancel(timer))
2119 		hrtimer_start_expires(timer, HRTIMER_MODE_ABS_PINNED);
2120 }
2121 
2122 /*
2123  * apic_sync_pv_eoi_from_guest - called on vmexit or cancel interrupt
2124  *
2125  * Detect whether guest triggered PV EOI since the
2126  * last entry. If yes, set EOI on guests's behalf.
2127  * Clear PV EOI in guest memory in any case.
2128  */
apic_sync_pv_eoi_from_guest(struct kvm_vcpu * vcpu,struct kvm_lapic * apic)2129 static void apic_sync_pv_eoi_from_guest(struct kvm_vcpu *vcpu,
2130 					struct kvm_lapic *apic)
2131 {
2132 	bool pending;
2133 	int vector;
2134 	/*
2135 	 * PV EOI state is derived from KVM_APIC_PV_EOI_PENDING in host
2136 	 * and KVM_PV_EOI_ENABLED in guest memory as follows:
2137 	 *
2138 	 * KVM_APIC_PV_EOI_PENDING is unset:
2139 	 * 	-> host disabled PV EOI.
2140 	 * KVM_APIC_PV_EOI_PENDING is set, KVM_PV_EOI_ENABLED is set:
2141 	 * 	-> host enabled PV EOI, guest did not execute EOI yet.
2142 	 * KVM_APIC_PV_EOI_PENDING is set, KVM_PV_EOI_ENABLED is unset:
2143 	 * 	-> host enabled PV EOI, guest executed EOI.
2144 	 */
2145 	BUG_ON(!pv_eoi_enabled(vcpu));
2146 	pending = pv_eoi_get_pending(vcpu);
2147 	/*
2148 	 * Clear pending bit in any case: it will be set again on vmentry.
2149 	 * While this might not be ideal from performance point of view,
2150 	 * this makes sure pv eoi is only enabled when we know it's safe.
2151 	 */
2152 	pv_eoi_clr_pending(vcpu);
2153 	if (pending)
2154 		return;
2155 	vector = apic_set_eoi(apic);
2156 	trace_kvm_pv_eoi(apic, vector);
2157 }
2158 
kvm_lapic_sync_from_vapic(struct kvm_vcpu * vcpu)2159 void kvm_lapic_sync_from_vapic(struct kvm_vcpu *vcpu)
2160 {
2161 	u32 data;
2162 
2163 	if (test_bit(KVM_APIC_PV_EOI_PENDING, &vcpu->arch.apic_attention))
2164 		apic_sync_pv_eoi_from_guest(vcpu, vcpu->arch.apic);
2165 
2166 	if (!test_bit(KVM_APIC_CHECK_VAPIC, &vcpu->arch.apic_attention))
2167 		return;
2168 
2169 	if (kvm_read_guest_cached(vcpu->kvm, &vcpu->arch.apic->vapic_cache, &data,
2170 				  sizeof(u32)))
2171 		return;
2172 
2173 	apic_set_tpr(vcpu->arch.apic, data & 0xff);
2174 }
2175 
2176 /*
2177  * apic_sync_pv_eoi_to_guest - called before vmentry
2178  *
2179  * Detect whether it's safe to enable PV EOI and
2180  * if yes do so.
2181  */
apic_sync_pv_eoi_to_guest(struct kvm_vcpu * vcpu,struct kvm_lapic * apic)2182 static void apic_sync_pv_eoi_to_guest(struct kvm_vcpu *vcpu,
2183 					struct kvm_lapic *apic)
2184 {
2185 	if (!pv_eoi_enabled(vcpu) ||
2186 	    /* IRR set or many bits in ISR: could be nested. */
2187 	    apic->irr_pending ||
2188 	    /* Cache not set: could be safe but we don't bother. */
2189 	    apic->highest_isr_cache == -1 ||
2190 	    /* Need EOI to update ioapic. */
2191 	    kvm_ioapic_handles_vector(apic, apic->highest_isr_cache)) {
2192 		/*
2193 		 * PV EOI was disabled by apic_sync_pv_eoi_from_guest
2194 		 * so we need not do anything here.
2195 		 */
2196 		return;
2197 	}
2198 
2199 	pv_eoi_set_pending(apic->vcpu);
2200 }
2201 
kvm_lapic_sync_to_vapic(struct kvm_vcpu * vcpu)2202 void kvm_lapic_sync_to_vapic(struct kvm_vcpu *vcpu)
2203 {
2204 	u32 data, tpr;
2205 	int max_irr, max_isr;
2206 	struct kvm_lapic *apic = vcpu->arch.apic;
2207 
2208 	apic_sync_pv_eoi_to_guest(vcpu, apic);
2209 
2210 	if (!test_bit(KVM_APIC_CHECK_VAPIC, &vcpu->arch.apic_attention))
2211 		return;
2212 
2213 	tpr = kvm_lapic_get_reg(apic, APIC_TASKPRI) & 0xff;
2214 	max_irr = apic_find_highest_irr(apic);
2215 	if (max_irr < 0)
2216 		max_irr = 0;
2217 	max_isr = apic_find_highest_isr(apic);
2218 	if (max_isr < 0)
2219 		max_isr = 0;
2220 	data = (tpr & 0xff) | ((max_isr & 0xf0) << 8) | (max_irr << 24);
2221 
2222 	kvm_write_guest_cached(vcpu->kvm, &vcpu->arch.apic->vapic_cache, &data,
2223 				sizeof(u32));
2224 }
2225 
kvm_lapic_set_vapic_addr(struct kvm_vcpu * vcpu,gpa_t vapic_addr)2226 int kvm_lapic_set_vapic_addr(struct kvm_vcpu *vcpu, gpa_t vapic_addr)
2227 {
2228 	if (vapic_addr) {
2229 		if (kvm_gfn_to_hva_cache_init(vcpu->kvm,
2230 					&vcpu->arch.apic->vapic_cache,
2231 					vapic_addr, sizeof(u32)))
2232 			return -EINVAL;
2233 		__set_bit(KVM_APIC_CHECK_VAPIC, &vcpu->arch.apic_attention);
2234 	} else {
2235 		__clear_bit(KVM_APIC_CHECK_VAPIC, &vcpu->arch.apic_attention);
2236 	}
2237 
2238 	vcpu->arch.apic->vapic_addr = vapic_addr;
2239 	return 0;
2240 }
2241 
kvm_x2apic_msr_write(struct kvm_vcpu * vcpu,u32 msr,u64 data)2242 int kvm_x2apic_msr_write(struct kvm_vcpu *vcpu, u32 msr, u64 data)
2243 {
2244 	struct kvm_lapic *apic = vcpu->arch.apic;
2245 	u32 reg = (msr - APIC_BASE_MSR) << 4;
2246 
2247 	if (!lapic_in_kernel(vcpu) || !apic_x2apic_mode(apic))
2248 		return 1;
2249 
2250 	if (reg == APIC_ICR2)
2251 		return 1;
2252 
2253 	/* if this is ICR write vector before command */
2254 	if (reg == APIC_ICR)
2255 		kvm_lapic_reg_write(apic, APIC_ICR2, (u32)(data >> 32));
2256 	return kvm_lapic_reg_write(apic, reg, (u32)data);
2257 }
2258 
kvm_x2apic_msr_read(struct kvm_vcpu * vcpu,u32 msr,u64 * data)2259 int kvm_x2apic_msr_read(struct kvm_vcpu *vcpu, u32 msr, u64 *data)
2260 {
2261 	struct kvm_lapic *apic = vcpu->arch.apic;
2262 	u32 reg = (msr - APIC_BASE_MSR) << 4, low, high = 0;
2263 
2264 	if (!lapic_in_kernel(vcpu) || !apic_x2apic_mode(apic))
2265 		return 1;
2266 
2267 	if (reg == APIC_DFR || reg == APIC_ICR2) {
2268 		apic_debug("KVM_APIC_READ: read x2apic reserved register %x\n",
2269 			   reg);
2270 		return 1;
2271 	}
2272 
2273 	if (kvm_lapic_reg_read(apic, reg, 4, &low))
2274 		return 1;
2275 	if (reg == APIC_ICR)
2276 		kvm_lapic_reg_read(apic, APIC_ICR2, 4, &high);
2277 
2278 	*data = (((u64)high) << 32) | low;
2279 
2280 	return 0;
2281 }
2282 
kvm_hv_vapic_msr_write(struct kvm_vcpu * vcpu,u32 reg,u64 data)2283 int kvm_hv_vapic_msr_write(struct kvm_vcpu *vcpu, u32 reg, u64 data)
2284 {
2285 	struct kvm_lapic *apic = vcpu->arch.apic;
2286 
2287 	if (!lapic_in_kernel(vcpu))
2288 		return 1;
2289 
2290 	/* if this is ICR write vector before command */
2291 	if (reg == APIC_ICR)
2292 		kvm_lapic_reg_write(apic, APIC_ICR2, (u32)(data >> 32));
2293 	return kvm_lapic_reg_write(apic, reg, (u32)data);
2294 }
2295 
kvm_hv_vapic_msr_read(struct kvm_vcpu * vcpu,u32 reg,u64 * data)2296 int kvm_hv_vapic_msr_read(struct kvm_vcpu *vcpu, u32 reg, u64 *data)
2297 {
2298 	struct kvm_lapic *apic = vcpu->arch.apic;
2299 	u32 low, high = 0;
2300 
2301 	if (!lapic_in_kernel(vcpu))
2302 		return 1;
2303 
2304 	if (kvm_lapic_reg_read(apic, reg, 4, &low))
2305 		return 1;
2306 	if (reg == APIC_ICR)
2307 		kvm_lapic_reg_read(apic, APIC_ICR2, 4, &high);
2308 
2309 	*data = (((u64)high) << 32) | low;
2310 
2311 	return 0;
2312 }
2313 
kvm_lapic_enable_pv_eoi(struct kvm_vcpu * vcpu,u64 data)2314 int kvm_lapic_enable_pv_eoi(struct kvm_vcpu *vcpu, u64 data)
2315 {
2316 	u64 addr = data & ~KVM_MSR_ENABLED;
2317 	if (!IS_ALIGNED(addr, 4))
2318 		return 1;
2319 
2320 	vcpu->arch.pv_eoi.msr_val = data;
2321 	if (!pv_eoi_enabled(vcpu))
2322 		return 0;
2323 	return kvm_gfn_to_hva_cache_init(vcpu->kvm, &vcpu->arch.pv_eoi.data,
2324 					 addr, sizeof(u8));
2325 }
2326 
kvm_apic_accept_events(struct kvm_vcpu * vcpu)2327 void kvm_apic_accept_events(struct kvm_vcpu *vcpu)
2328 {
2329 	struct kvm_lapic *apic = vcpu->arch.apic;
2330 	u8 sipi_vector;
2331 	unsigned long pe;
2332 
2333 	if (!lapic_in_kernel(vcpu) || !apic->pending_events)
2334 		return;
2335 
2336 	/*
2337 	 * INITs are latched while in SMM.  Because an SMM CPU cannot
2338 	 * be in KVM_MP_STATE_INIT_RECEIVED state, just eat SIPIs
2339 	 * and delay processing of INIT until the next RSM.
2340 	 */
2341 	if (is_smm(vcpu)) {
2342 		WARN_ON_ONCE(vcpu->arch.mp_state == KVM_MP_STATE_INIT_RECEIVED);
2343 		if (test_bit(KVM_APIC_SIPI, &apic->pending_events))
2344 			clear_bit(KVM_APIC_SIPI, &apic->pending_events);
2345 		return;
2346 	}
2347 
2348 	pe = xchg(&apic->pending_events, 0);
2349 	if (test_bit(KVM_APIC_INIT, &pe)) {
2350 		kvm_lapic_reset(vcpu, true);
2351 		kvm_vcpu_reset(vcpu, true);
2352 		if (kvm_vcpu_is_bsp(apic->vcpu))
2353 			vcpu->arch.mp_state = KVM_MP_STATE_RUNNABLE;
2354 		else
2355 			vcpu->arch.mp_state = KVM_MP_STATE_INIT_RECEIVED;
2356 	}
2357 	if (test_bit(KVM_APIC_SIPI, &pe) &&
2358 	    vcpu->arch.mp_state == KVM_MP_STATE_INIT_RECEIVED) {
2359 		/* evaluate pending_events before reading the vector */
2360 		smp_rmb();
2361 		sipi_vector = apic->sipi_vector;
2362 		apic_debug("vcpu %d received sipi with vector # %x\n",
2363 			 vcpu->vcpu_id, sipi_vector);
2364 		kvm_vcpu_deliver_sipi_vector(vcpu, sipi_vector);
2365 		vcpu->arch.mp_state = KVM_MP_STATE_RUNNABLE;
2366 	}
2367 }
2368 
kvm_lapic_init(void)2369 void kvm_lapic_init(void)
2370 {
2371 	/* do not patch jump label more than once per second */
2372 	jump_label_rate_limit(&apic_hw_disabled, HZ);
2373 	jump_label_rate_limit(&apic_sw_disabled, HZ);
2374 }
2375 
kvm_lapic_exit(void)2376 void kvm_lapic_exit(void)
2377 {
2378 	static_key_deferred_flush(&apic_hw_disabled);
2379 	static_key_deferred_flush(&apic_sw_disabled);
2380 }
2381