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