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