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