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