xref: /openbmc/linux/arch/x86/kvm/lapic.c (revision 0f4b20ef)
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 		if (KVM_BUG_ON(!src, kvm)) {
1028 			*r = 0;
1029 			return true;
1030 		}
1031 		*r = kvm_apic_set_irq(src->vcpu, irq, dest_map);
1032 		return true;
1033 	}
1034 
1035 	rcu_read_lock();
1036 	map = rcu_dereference(kvm->arch.apic_map);
1037 
1038 	ret = kvm_apic_map_get_dest_lapic(kvm, &src, irq, map, &dst, &bitmap);
1039 	if (ret) {
1040 		*r = 0;
1041 		for_each_set_bit(i, &bitmap, 16) {
1042 			if (!dst[i])
1043 				continue;
1044 			*r += kvm_apic_set_irq(dst[i]->vcpu, irq, dest_map);
1045 		}
1046 	}
1047 
1048 	rcu_read_unlock();
1049 	return ret;
1050 }
1051 
1052 /*
1053  * This routine tries to handle interrupts in posted mode, here is how
1054  * it deals with different cases:
1055  * - For single-destination interrupts, handle it in posted mode
1056  * - Else if vector hashing is enabled and it is a lowest-priority
1057  *   interrupt, handle it in posted mode and use the following mechanism
1058  *   to find the destination vCPU.
1059  *	1. For lowest-priority interrupts, store all the possible
1060  *	   destination vCPUs in an array.
1061  *	2. Use "guest vector % max number of destination vCPUs" to find
1062  *	   the right destination vCPU in the array for the lowest-priority
1063  *	   interrupt.
1064  * - Otherwise, use remapped mode to inject the interrupt.
1065  */
1066 bool kvm_intr_is_single_vcpu_fast(struct kvm *kvm, struct kvm_lapic_irq *irq,
1067 			struct kvm_vcpu **dest_vcpu)
1068 {
1069 	struct kvm_apic_map *map;
1070 	unsigned long bitmap;
1071 	struct kvm_lapic **dst = NULL;
1072 	bool ret = false;
1073 
1074 	if (irq->shorthand)
1075 		return false;
1076 
1077 	rcu_read_lock();
1078 	map = rcu_dereference(kvm->arch.apic_map);
1079 
1080 	if (kvm_apic_map_get_dest_lapic(kvm, NULL, irq, map, &dst, &bitmap) &&
1081 			hweight16(bitmap) == 1) {
1082 		unsigned long i = find_first_bit(&bitmap, 16);
1083 
1084 		if (dst[i]) {
1085 			*dest_vcpu = dst[i]->vcpu;
1086 			ret = true;
1087 		}
1088 	}
1089 
1090 	rcu_read_unlock();
1091 	return ret;
1092 }
1093 
1094 /*
1095  * Add a pending IRQ into lapic.
1096  * Return 1 if successfully added and 0 if discarded.
1097  */
1098 static int __apic_accept_irq(struct kvm_lapic *apic, int delivery_mode,
1099 			     int vector, int level, int trig_mode,
1100 			     struct dest_map *dest_map)
1101 {
1102 	int result = 0;
1103 	struct kvm_vcpu *vcpu = apic->vcpu;
1104 
1105 	trace_kvm_apic_accept_irq(vcpu->vcpu_id, delivery_mode,
1106 				  trig_mode, vector);
1107 	switch (delivery_mode) {
1108 	case APIC_DM_LOWEST:
1109 		vcpu->arch.apic_arb_prio++;
1110 		fallthrough;
1111 	case APIC_DM_FIXED:
1112 		if (unlikely(trig_mode && !level))
1113 			break;
1114 
1115 		/* FIXME add logic for vcpu on reset */
1116 		if (unlikely(!apic_enabled(apic)))
1117 			break;
1118 
1119 		result = 1;
1120 
1121 		if (dest_map) {
1122 			__set_bit(vcpu->vcpu_id, dest_map->map);
1123 			dest_map->vectors[vcpu->vcpu_id] = vector;
1124 		}
1125 
1126 		if (apic_test_vector(vector, apic->regs + APIC_TMR) != !!trig_mode) {
1127 			if (trig_mode)
1128 				kvm_lapic_set_vector(vector,
1129 						     apic->regs + APIC_TMR);
1130 			else
1131 				kvm_lapic_clear_vector(vector,
1132 						       apic->regs + APIC_TMR);
1133 		}
1134 
1135 		static_call(kvm_x86_deliver_interrupt)(apic, delivery_mode,
1136 						       trig_mode, vector);
1137 		break;
1138 
1139 	case APIC_DM_REMRD:
1140 		result = 1;
1141 		vcpu->arch.pv.pv_unhalted = 1;
1142 		kvm_make_request(KVM_REQ_EVENT, vcpu);
1143 		kvm_vcpu_kick(vcpu);
1144 		break;
1145 
1146 	case APIC_DM_SMI:
1147 		result = 1;
1148 		kvm_make_request(KVM_REQ_SMI, vcpu);
1149 		kvm_vcpu_kick(vcpu);
1150 		break;
1151 
1152 	case APIC_DM_NMI:
1153 		result = 1;
1154 		kvm_inject_nmi(vcpu);
1155 		kvm_vcpu_kick(vcpu);
1156 		break;
1157 
1158 	case APIC_DM_INIT:
1159 		if (!trig_mode || level) {
1160 			result = 1;
1161 			/* assumes that there are only KVM_APIC_INIT/SIPI */
1162 			apic->pending_events = (1UL << KVM_APIC_INIT);
1163 			kvm_make_request(KVM_REQ_EVENT, vcpu);
1164 			kvm_vcpu_kick(vcpu);
1165 		}
1166 		break;
1167 
1168 	case APIC_DM_STARTUP:
1169 		result = 1;
1170 		apic->sipi_vector = vector;
1171 		/* make sure sipi_vector is visible for the receiver */
1172 		smp_wmb();
1173 		set_bit(KVM_APIC_SIPI, &apic->pending_events);
1174 		kvm_make_request(KVM_REQ_EVENT, vcpu);
1175 		kvm_vcpu_kick(vcpu);
1176 		break;
1177 
1178 	case APIC_DM_EXTINT:
1179 		/*
1180 		 * Should only be called by kvm_apic_local_deliver() with LVT0,
1181 		 * before NMI watchdog was enabled. Already handled by
1182 		 * kvm_apic_accept_pic_intr().
1183 		 */
1184 		break;
1185 
1186 	default:
1187 		printk(KERN_ERR "TODO: unsupported delivery mode %x\n",
1188 		       delivery_mode);
1189 		break;
1190 	}
1191 	return result;
1192 }
1193 
1194 /*
1195  * This routine identifies the destination vcpus mask meant to receive the
1196  * IOAPIC interrupts. It either uses kvm_apic_map_get_dest_lapic() to find
1197  * out the destination vcpus array and set the bitmap or it traverses to
1198  * each available vcpu to identify the same.
1199  */
1200 void kvm_bitmap_or_dest_vcpus(struct kvm *kvm, struct kvm_lapic_irq *irq,
1201 			      unsigned long *vcpu_bitmap)
1202 {
1203 	struct kvm_lapic **dest_vcpu = NULL;
1204 	struct kvm_lapic *src = NULL;
1205 	struct kvm_apic_map *map;
1206 	struct kvm_vcpu *vcpu;
1207 	unsigned long bitmap, i;
1208 	int vcpu_idx;
1209 	bool ret;
1210 
1211 	rcu_read_lock();
1212 	map = rcu_dereference(kvm->arch.apic_map);
1213 
1214 	ret = kvm_apic_map_get_dest_lapic(kvm, &src, irq, map, &dest_vcpu,
1215 					  &bitmap);
1216 	if (ret) {
1217 		for_each_set_bit(i, &bitmap, 16) {
1218 			if (!dest_vcpu[i])
1219 				continue;
1220 			vcpu_idx = dest_vcpu[i]->vcpu->vcpu_idx;
1221 			__set_bit(vcpu_idx, vcpu_bitmap);
1222 		}
1223 	} else {
1224 		kvm_for_each_vcpu(i, vcpu, kvm) {
1225 			if (!kvm_apic_present(vcpu))
1226 				continue;
1227 			if (!kvm_apic_match_dest(vcpu, NULL,
1228 						 irq->shorthand,
1229 						 irq->dest_id,
1230 						 irq->dest_mode))
1231 				continue;
1232 			__set_bit(i, vcpu_bitmap);
1233 		}
1234 	}
1235 	rcu_read_unlock();
1236 }
1237 
1238 int kvm_apic_compare_prio(struct kvm_vcpu *vcpu1, struct kvm_vcpu *vcpu2)
1239 {
1240 	return vcpu1->arch.apic_arb_prio - vcpu2->arch.apic_arb_prio;
1241 }
1242 
1243 static bool kvm_ioapic_handles_vector(struct kvm_lapic *apic, int vector)
1244 {
1245 	return test_bit(vector, apic->vcpu->arch.ioapic_handled_vectors);
1246 }
1247 
1248 static void kvm_ioapic_send_eoi(struct kvm_lapic *apic, int vector)
1249 {
1250 	int trigger_mode;
1251 
1252 	/* Eoi the ioapic only if the ioapic doesn't own the vector. */
1253 	if (!kvm_ioapic_handles_vector(apic, vector))
1254 		return;
1255 
1256 	/* Request a KVM exit to inform the userspace IOAPIC. */
1257 	if (irqchip_split(apic->vcpu->kvm)) {
1258 		apic->vcpu->arch.pending_ioapic_eoi = vector;
1259 		kvm_make_request(KVM_REQ_IOAPIC_EOI_EXIT, apic->vcpu);
1260 		return;
1261 	}
1262 
1263 	if (apic_test_vector(vector, apic->regs + APIC_TMR))
1264 		trigger_mode = IOAPIC_LEVEL_TRIG;
1265 	else
1266 		trigger_mode = IOAPIC_EDGE_TRIG;
1267 
1268 	kvm_ioapic_update_eoi(apic->vcpu, vector, trigger_mode);
1269 }
1270 
1271 static int apic_set_eoi(struct kvm_lapic *apic)
1272 {
1273 	int vector = apic_find_highest_isr(apic);
1274 
1275 	trace_kvm_eoi(apic, vector);
1276 
1277 	/*
1278 	 * Not every write EOI will has corresponding ISR,
1279 	 * one example is when Kernel check timer on setup_IO_APIC
1280 	 */
1281 	if (vector == -1)
1282 		return vector;
1283 
1284 	apic_clear_isr(vector, apic);
1285 	apic_update_ppr(apic);
1286 
1287 	if (to_hv_vcpu(apic->vcpu) &&
1288 	    test_bit(vector, to_hv_synic(apic->vcpu)->vec_bitmap))
1289 		kvm_hv_synic_send_eoi(apic->vcpu, vector);
1290 
1291 	kvm_ioapic_send_eoi(apic, vector);
1292 	kvm_make_request(KVM_REQ_EVENT, apic->vcpu);
1293 	return vector;
1294 }
1295 
1296 /*
1297  * this interface assumes a trap-like exit, which has already finished
1298  * desired side effect including vISR and vPPR update.
1299  */
1300 void kvm_apic_set_eoi_accelerated(struct kvm_vcpu *vcpu, int vector)
1301 {
1302 	struct kvm_lapic *apic = vcpu->arch.apic;
1303 
1304 	trace_kvm_eoi(apic, vector);
1305 
1306 	kvm_ioapic_send_eoi(apic, vector);
1307 	kvm_make_request(KVM_REQ_EVENT, apic->vcpu);
1308 }
1309 EXPORT_SYMBOL_GPL(kvm_apic_set_eoi_accelerated);
1310 
1311 void kvm_apic_send_ipi(struct kvm_lapic *apic, u32 icr_low, u32 icr_high)
1312 {
1313 	struct kvm_lapic_irq irq;
1314 
1315 	/* KVM has no delay and should always clear the BUSY/PENDING flag. */
1316 	WARN_ON_ONCE(icr_low & APIC_ICR_BUSY);
1317 
1318 	irq.vector = icr_low & APIC_VECTOR_MASK;
1319 	irq.delivery_mode = icr_low & APIC_MODE_MASK;
1320 	irq.dest_mode = icr_low & APIC_DEST_MASK;
1321 	irq.level = (icr_low & APIC_INT_ASSERT) != 0;
1322 	irq.trig_mode = icr_low & APIC_INT_LEVELTRIG;
1323 	irq.shorthand = icr_low & APIC_SHORT_MASK;
1324 	irq.msi_redir_hint = false;
1325 	if (apic_x2apic_mode(apic))
1326 		irq.dest_id = icr_high;
1327 	else
1328 		irq.dest_id = GET_APIC_DEST_FIELD(icr_high);
1329 
1330 	trace_kvm_apic_ipi(icr_low, irq.dest_id);
1331 
1332 	kvm_irq_delivery_to_apic(apic->vcpu->kvm, apic, &irq, NULL);
1333 }
1334 EXPORT_SYMBOL_GPL(kvm_apic_send_ipi);
1335 
1336 static u32 apic_get_tmcct(struct kvm_lapic *apic)
1337 {
1338 	ktime_t remaining, now;
1339 	s64 ns;
1340 	u32 tmcct;
1341 
1342 	ASSERT(apic != NULL);
1343 
1344 	/* if initial count is 0, current count should also be 0 */
1345 	if (kvm_lapic_get_reg(apic, APIC_TMICT) == 0 ||
1346 		apic->lapic_timer.period == 0)
1347 		return 0;
1348 
1349 	now = ktime_get();
1350 	remaining = ktime_sub(apic->lapic_timer.target_expiration, now);
1351 	if (ktime_to_ns(remaining) < 0)
1352 		remaining = 0;
1353 
1354 	ns = mod_64(ktime_to_ns(remaining), apic->lapic_timer.period);
1355 	tmcct = div64_u64(ns,
1356 			 (APIC_BUS_CYCLE_NS * apic->divide_count));
1357 
1358 	return tmcct;
1359 }
1360 
1361 static void __report_tpr_access(struct kvm_lapic *apic, bool write)
1362 {
1363 	struct kvm_vcpu *vcpu = apic->vcpu;
1364 	struct kvm_run *run = vcpu->run;
1365 
1366 	kvm_make_request(KVM_REQ_REPORT_TPR_ACCESS, vcpu);
1367 	run->tpr_access.rip = kvm_rip_read(vcpu);
1368 	run->tpr_access.is_write = write;
1369 }
1370 
1371 static inline void report_tpr_access(struct kvm_lapic *apic, bool write)
1372 {
1373 	if (apic->vcpu->arch.tpr_access_reporting)
1374 		__report_tpr_access(apic, write);
1375 }
1376 
1377 static u32 __apic_read(struct kvm_lapic *apic, unsigned int offset)
1378 {
1379 	u32 val = 0;
1380 
1381 	if (offset >= LAPIC_MMIO_LENGTH)
1382 		return 0;
1383 
1384 	switch (offset) {
1385 	case APIC_ARBPRI:
1386 		break;
1387 
1388 	case APIC_TMCCT:	/* Timer CCR */
1389 		if (apic_lvtt_tscdeadline(apic))
1390 			return 0;
1391 
1392 		val = apic_get_tmcct(apic);
1393 		break;
1394 	case APIC_PROCPRI:
1395 		apic_update_ppr(apic);
1396 		val = kvm_lapic_get_reg(apic, offset);
1397 		break;
1398 	case APIC_TASKPRI:
1399 		report_tpr_access(apic, false);
1400 		fallthrough;
1401 	default:
1402 		val = kvm_lapic_get_reg(apic, offset);
1403 		break;
1404 	}
1405 
1406 	return val;
1407 }
1408 
1409 static inline struct kvm_lapic *to_lapic(struct kvm_io_device *dev)
1410 {
1411 	return container_of(dev, struct kvm_lapic, dev);
1412 }
1413 
1414 #define APIC_REG_MASK(reg)	(1ull << ((reg) >> 4))
1415 #define APIC_REGS_MASK(first, count) \
1416 	(APIC_REG_MASK(first) * ((1ull << (count)) - 1))
1417 
1418 static int kvm_lapic_reg_read(struct kvm_lapic *apic, u32 offset, int len,
1419 			      void *data)
1420 {
1421 	unsigned char alignment = offset & 0xf;
1422 	u32 result;
1423 	/* this bitmask has a bit cleared for each reserved register */
1424 	u64 valid_reg_mask =
1425 		APIC_REG_MASK(APIC_ID) |
1426 		APIC_REG_MASK(APIC_LVR) |
1427 		APIC_REG_MASK(APIC_TASKPRI) |
1428 		APIC_REG_MASK(APIC_PROCPRI) |
1429 		APIC_REG_MASK(APIC_LDR) |
1430 		APIC_REG_MASK(APIC_DFR) |
1431 		APIC_REG_MASK(APIC_SPIV) |
1432 		APIC_REGS_MASK(APIC_ISR, APIC_ISR_NR) |
1433 		APIC_REGS_MASK(APIC_TMR, APIC_ISR_NR) |
1434 		APIC_REGS_MASK(APIC_IRR, APIC_ISR_NR) |
1435 		APIC_REG_MASK(APIC_ESR) |
1436 		APIC_REG_MASK(APIC_ICR) |
1437 		APIC_REG_MASK(APIC_LVTT) |
1438 		APIC_REG_MASK(APIC_LVTTHMR) |
1439 		APIC_REG_MASK(APIC_LVTPC) |
1440 		APIC_REG_MASK(APIC_LVT0) |
1441 		APIC_REG_MASK(APIC_LVT1) |
1442 		APIC_REG_MASK(APIC_LVTERR) |
1443 		APIC_REG_MASK(APIC_TMICT) |
1444 		APIC_REG_MASK(APIC_TMCCT) |
1445 		APIC_REG_MASK(APIC_TDCR);
1446 
1447 	/*
1448 	 * ARBPRI and ICR2 are not valid in x2APIC mode.  WARN if KVM reads ICR
1449 	 * in x2APIC mode as it's an 8-byte register in x2APIC and needs to be
1450 	 * manually handled by the caller.
1451 	 */
1452 	if (!apic_x2apic_mode(apic))
1453 		valid_reg_mask |= APIC_REG_MASK(APIC_ARBPRI) |
1454 				  APIC_REG_MASK(APIC_ICR2);
1455 	else
1456 		WARN_ON_ONCE(offset == APIC_ICR);
1457 
1458 	if (alignment + len > 4)
1459 		return 1;
1460 
1461 	if (offset > 0x3f0 || !(valid_reg_mask & APIC_REG_MASK(offset)))
1462 		return 1;
1463 
1464 	result = __apic_read(apic, offset & ~0xf);
1465 
1466 	trace_kvm_apic_read(offset, result);
1467 
1468 	switch (len) {
1469 	case 1:
1470 	case 2:
1471 	case 4:
1472 		memcpy(data, (char *)&result + alignment, len);
1473 		break;
1474 	default:
1475 		printk(KERN_ERR "Local APIC read with len = %x, "
1476 		       "should be 1,2, or 4 instead\n", len);
1477 		break;
1478 	}
1479 	return 0;
1480 }
1481 
1482 static int apic_mmio_in_range(struct kvm_lapic *apic, gpa_t addr)
1483 {
1484 	return addr >= apic->base_address &&
1485 		addr < apic->base_address + LAPIC_MMIO_LENGTH;
1486 }
1487 
1488 static int apic_mmio_read(struct kvm_vcpu *vcpu, struct kvm_io_device *this,
1489 			   gpa_t address, int len, void *data)
1490 {
1491 	struct kvm_lapic *apic = to_lapic(this);
1492 	u32 offset = address - apic->base_address;
1493 
1494 	if (!apic_mmio_in_range(apic, address))
1495 		return -EOPNOTSUPP;
1496 
1497 	if (!kvm_apic_hw_enabled(apic) || apic_x2apic_mode(apic)) {
1498 		if (!kvm_check_has_quirk(vcpu->kvm,
1499 					 KVM_X86_QUIRK_LAPIC_MMIO_HOLE))
1500 			return -EOPNOTSUPP;
1501 
1502 		memset(data, 0xff, len);
1503 		return 0;
1504 	}
1505 
1506 	kvm_lapic_reg_read(apic, offset, len, data);
1507 
1508 	return 0;
1509 }
1510 
1511 static void update_divide_count(struct kvm_lapic *apic)
1512 {
1513 	u32 tmp1, tmp2, tdcr;
1514 
1515 	tdcr = kvm_lapic_get_reg(apic, APIC_TDCR);
1516 	tmp1 = tdcr & 0xf;
1517 	tmp2 = ((tmp1 & 0x3) | ((tmp1 & 0x8) >> 1)) + 1;
1518 	apic->divide_count = 0x1 << (tmp2 & 0x7);
1519 }
1520 
1521 static void limit_periodic_timer_frequency(struct kvm_lapic *apic)
1522 {
1523 	/*
1524 	 * Do not allow the guest to program periodic timers with small
1525 	 * interval, since the hrtimers are not throttled by the host
1526 	 * scheduler.
1527 	 */
1528 	if (apic_lvtt_period(apic) && apic->lapic_timer.period) {
1529 		s64 min_period = min_timer_period_us * 1000LL;
1530 
1531 		if (apic->lapic_timer.period < min_period) {
1532 			pr_info_ratelimited(
1533 			    "kvm: vcpu %i: requested %lld ns "
1534 			    "lapic timer period limited to %lld ns\n",
1535 			    apic->vcpu->vcpu_id,
1536 			    apic->lapic_timer.period, min_period);
1537 			apic->lapic_timer.period = min_period;
1538 		}
1539 	}
1540 }
1541 
1542 static void cancel_hv_timer(struct kvm_lapic *apic);
1543 
1544 static void cancel_apic_timer(struct kvm_lapic *apic)
1545 {
1546 	hrtimer_cancel(&apic->lapic_timer.timer);
1547 	preempt_disable();
1548 	if (apic->lapic_timer.hv_timer_in_use)
1549 		cancel_hv_timer(apic);
1550 	preempt_enable();
1551 }
1552 
1553 static void apic_update_lvtt(struct kvm_lapic *apic)
1554 {
1555 	u32 timer_mode = kvm_lapic_get_reg(apic, APIC_LVTT) &
1556 			apic->lapic_timer.timer_mode_mask;
1557 
1558 	if (apic->lapic_timer.timer_mode != timer_mode) {
1559 		if (apic_lvtt_tscdeadline(apic) != (timer_mode ==
1560 				APIC_LVT_TIMER_TSCDEADLINE)) {
1561 			cancel_apic_timer(apic);
1562 			kvm_lapic_set_reg(apic, APIC_TMICT, 0);
1563 			apic->lapic_timer.period = 0;
1564 			apic->lapic_timer.tscdeadline = 0;
1565 		}
1566 		apic->lapic_timer.timer_mode = timer_mode;
1567 		limit_periodic_timer_frequency(apic);
1568 	}
1569 }
1570 
1571 /*
1572  * On APICv, this test will cause a busy wait
1573  * during a higher-priority task.
1574  */
1575 
1576 static bool lapic_timer_int_injected(struct kvm_vcpu *vcpu)
1577 {
1578 	struct kvm_lapic *apic = vcpu->arch.apic;
1579 	u32 reg = kvm_lapic_get_reg(apic, APIC_LVTT);
1580 
1581 	if (kvm_apic_hw_enabled(apic)) {
1582 		int vec = reg & APIC_VECTOR_MASK;
1583 		void *bitmap = apic->regs + APIC_ISR;
1584 
1585 		if (vcpu->arch.apicv_active)
1586 			bitmap = apic->regs + APIC_IRR;
1587 
1588 		if (apic_test_vector(vec, bitmap))
1589 			return true;
1590 	}
1591 	return false;
1592 }
1593 
1594 static inline void __wait_lapic_expire(struct kvm_vcpu *vcpu, u64 guest_cycles)
1595 {
1596 	u64 timer_advance_ns = vcpu->arch.apic->lapic_timer.timer_advance_ns;
1597 
1598 	/*
1599 	 * If the guest TSC is running at a different ratio than the host, then
1600 	 * convert the delay to nanoseconds to achieve an accurate delay.  Note
1601 	 * that __delay() uses delay_tsc whenever the hardware has TSC, thus
1602 	 * always for VMX enabled hardware.
1603 	 */
1604 	if (vcpu->arch.tsc_scaling_ratio == kvm_default_tsc_scaling_ratio) {
1605 		__delay(min(guest_cycles,
1606 			nsec_to_cycles(vcpu, timer_advance_ns)));
1607 	} else {
1608 		u64 delay_ns = guest_cycles * 1000000ULL;
1609 		do_div(delay_ns, vcpu->arch.virtual_tsc_khz);
1610 		ndelay(min_t(u32, delay_ns, timer_advance_ns));
1611 	}
1612 }
1613 
1614 static inline void adjust_lapic_timer_advance(struct kvm_vcpu *vcpu,
1615 					      s64 advance_expire_delta)
1616 {
1617 	struct kvm_lapic *apic = vcpu->arch.apic;
1618 	u32 timer_advance_ns = apic->lapic_timer.timer_advance_ns;
1619 	u64 ns;
1620 
1621 	/* Do not adjust for tiny fluctuations or large random spikes. */
1622 	if (abs(advance_expire_delta) > LAPIC_TIMER_ADVANCE_ADJUST_MAX ||
1623 	    abs(advance_expire_delta) < LAPIC_TIMER_ADVANCE_ADJUST_MIN)
1624 		return;
1625 
1626 	/* too early */
1627 	if (advance_expire_delta < 0) {
1628 		ns = -advance_expire_delta * 1000000ULL;
1629 		do_div(ns, vcpu->arch.virtual_tsc_khz);
1630 		timer_advance_ns -= ns/LAPIC_TIMER_ADVANCE_ADJUST_STEP;
1631 	} else {
1632 	/* too late */
1633 		ns = advance_expire_delta * 1000000ULL;
1634 		do_div(ns, vcpu->arch.virtual_tsc_khz);
1635 		timer_advance_ns += ns/LAPIC_TIMER_ADVANCE_ADJUST_STEP;
1636 	}
1637 
1638 	if (unlikely(timer_advance_ns > LAPIC_TIMER_ADVANCE_NS_MAX))
1639 		timer_advance_ns = LAPIC_TIMER_ADVANCE_NS_INIT;
1640 	apic->lapic_timer.timer_advance_ns = timer_advance_ns;
1641 }
1642 
1643 static void __kvm_wait_lapic_expire(struct kvm_vcpu *vcpu)
1644 {
1645 	struct kvm_lapic *apic = vcpu->arch.apic;
1646 	u64 guest_tsc, tsc_deadline;
1647 
1648 	tsc_deadline = apic->lapic_timer.expired_tscdeadline;
1649 	apic->lapic_timer.expired_tscdeadline = 0;
1650 	guest_tsc = kvm_read_l1_tsc(vcpu, rdtsc());
1651 	apic->lapic_timer.advance_expire_delta = guest_tsc - tsc_deadline;
1652 
1653 	if (lapic_timer_advance_dynamic) {
1654 		adjust_lapic_timer_advance(vcpu, apic->lapic_timer.advance_expire_delta);
1655 		/*
1656 		 * If the timer fired early, reread the TSC to account for the
1657 		 * overhead of the above adjustment to avoid waiting longer
1658 		 * than is necessary.
1659 		 */
1660 		if (guest_tsc < tsc_deadline)
1661 			guest_tsc = kvm_read_l1_tsc(vcpu, rdtsc());
1662 	}
1663 
1664 	if (guest_tsc < tsc_deadline)
1665 		__wait_lapic_expire(vcpu, tsc_deadline - guest_tsc);
1666 }
1667 
1668 void kvm_wait_lapic_expire(struct kvm_vcpu *vcpu)
1669 {
1670 	if (lapic_in_kernel(vcpu) &&
1671 	    vcpu->arch.apic->lapic_timer.expired_tscdeadline &&
1672 	    vcpu->arch.apic->lapic_timer.timer_advance_ns &&
1673 	    lapic_timer_int_injected(vcpu))
1674 		__kvm_wait_lapic_expire(vcpu);
1675 }
1676 EXPORT_SYMBOL_GPL(kvm_wait_lapic_expire);
1677 
1678 static void kvm_apic_inject_pending_timer_irqs(struct kvm_lapic *apic)
1679 {
1680 	struct kvm_timer *ktimer = &apic->lapic_timer;
1681 
1682 	kvm_apic_local_deliver(apic, APIC_LVTT);
1683 	if (apic_lvtt_tscdeadline(apic)) {
1684 		ktimer->tscdeadline = 0;
1685 	} else if (apic_lvtt_oneshot(apic)) {
1686 		ktimer->tscdeadline = 0;
1687 		ktimer->target_expiration = 0;
1688 	}
1689 }
1690 
1691 static void apic_timer_expired(struct kvm_lapic *apic, bool from_timer_fn)
1692 {
1693 	struct kvm_vcpu *vcpu = apic->vcpu;
1694 	struct kvm_timer *ktimer = &apic->lapic_timer;
1695 
1696 	if (atomic_read(&apic->lapic_timer.pending))
1697 		return;
1698 
1699 	if (apic_lvtt_tscdeadline(apic) || ktimer->hv_timer_in_use)
1700 		ktimer->expired_tscdeadline = ktimer->tscdeadline;
1701 
1702 	if (!from_timer_fn && vcpu->arch.apicv_active) {
1703 		WARN_ON(kvm_get_running_vcpu() != vcpu);
1704 		kvm_apic_inject_pending_timer_irqs(apic);
1705 		return;
1706 	}
1707 
1708 	if (kvm_use_posted_timer_interrupt(apic->vcpu)) {
1709 		/*
1710 		 * Ensure the guest's timer has truly expired before posting an
1711 		 * interrupt.  Open code the relevant checks to avoid querying
1712 		 * lapic_timer_int_injected(), which will be false since the
1713 		 * interrupt isn't yet injected.  Waiting until after injecting
1714 		 * is not an option since that won't help a posted interrupt.
1715 		 */
1716 		if (vcpu->arch.apic->lapic_timer.expired_tscdeadline &&
1717 		    vcpu->arch.apic->lapic_timer.timer_advance_ns)
1718 			__kvm_wait_lapic_expire(vcpu);
1719 		kvm_apic_inject_pending_timer_irqs(apic);
1720 		return;
1721 	}
1722 
1723 	atomic_inc(&apic->lapic_timer.pending);
1724 	kvm_make_request(KVM_REQ_UNBLOCK, vcpu);
1725 	if (from_timer_fn)
1726 		kvm_vcpu_kick(vcpu);
1727 }
1728 
1729 static void start_sw_tscdeadline(struct kvm_lapic *apic)
1730 {
1731 	struct kvm_timer *ktimer = &apic->lapic_timer;
1732 	u64 guest_tsc, tscdeadline = ktimer->tscdeadline;
1733 	u64 ns = 0;
1734 	ktime_t expire;
1735 	struct kvm_vcpu *vcpu = apic->vcpu;
1736 	unsigned long this_tsc_khz = vcpu->arch.virtual_tsc_khz;
1737 	unsigned long flags;
1738 	ktime_t now;
1739 
1740 	if (unlikely(!tscdeadline || !this_tsc_khz))
1741 		return;
1742 
1743 	local_irq_save(flags);
1744 
1745 	now = ktime_get();
1746 	guest_tsc = kvm_read_l1_tsc(vcpu, rdtsc());
1747 
1748 	ns = (tscdeadline - guest_tsc) * 1000000ULL;
1749 	do_div(ns, this_tsc_khz);
1750 
1751 	if (likely(tscdeadline > guest_tsc) &&
1752 	    likely(ns > apic->lapic_timer.timer_advance_ns)) {
1753 		expire = ktime_add_ns(now, ns);
1754 		expire = ktime_sub_ns(expire, ktimer->timer_advance_ns);
1755 		hrtimer_start(&ktimer->timer, expire, HRTIMER_MODE_ABS_HARD);
1756 	} else
1757 		apic_timer_expired(apic, false);
1758 
1759 	local_irq_restore(flags);
1760 }
1761 
1762 static inline u64 tmict_to_ns(struct kvm_lapic *apic, u32 tmict)
1763 {
1764 	return (u64)tmict * APIC_BUS_CYCLE_NS * (u64)apic->divide_count;
1765 }
1766 
1767 static void update_target_expiration(struct kvm_lapic *apic, uint32_t old_divisor)
1768 {
1769 	ktime_t now, remaining;
1770 	u64 ns_remaining_old, ns_remaining_new;
1771 
1772 	apic->lapic_timer.period =
1773 			tmict_to_ns(apic, kvm_lapic_get_reg(apic, APIC_TMICT));
1774 	limit_periodic_timer_frequency(apic);
1775 
1776 	now = ktime_get();
1777 	remaining = ktime_sub(apic->lapic_timer.target_expiration, now);
1778 	if (ktime_to_ns(remaining) < 0)
1779 		remaining = 0;
1780 
1781 	ns_remaining_old = ktime_to_ns(remaining);
1782 	ns_remaining_new = mul_u64_u32_div(ns_remaining_old,
1783 	                                   apic->divide_count, old_divisor);
1784 
1785 	apic->lapic_timer.tscdeadline +=
1786 		nsec_to_cycles(apic->vcpu, ns_remaining_new) -
1787 		nsec_to_cycles(apic->vcpu, ns_remaining_old);
1788 	apic->lapic_timer.target_expiration = ktime_add_ns(now, ns_remaining_new);
1789 }
1790 
1791 static bool set_target_expiration(struct kvm_lapic *apic, u32 count_reg)
1792 {
1793 	ktime_t now;
1794 	u64 tscl = rdtsc();
1795 	s64 deadline;
1796 
1797 	now = ktime_get();
1798 	apic->lapic_timer.period =
1799 			tmict_to_ns(apic, kvm_lapic_get_reg(apic, APIC_TMICT));
1800 
1801 	if (!apic->lapic_timer.period) {
1802 		apic->lapic_timer.tscdeadline = 0;
1803 		return false;
1804 	}
1805 
1806 	limit_periodic_timer_frequency(apic);
1807 	deadline = apic->lapic_timer.period;
1808 
1809 	if (apic_lvtt_period(apic) || apic_lvtt_oneshot(apic)) {
1810 		if (unlikely(count_reg != APIC_TMICT)) {
1811 			deadline = tmict_to_ns(apic,
1812 				     kvm_lapic_get_reg(apic, count_reg));
1813 			if (unlikely(deadline <= 0))
1814 				deadline = apic->lapic_timer.period;
1815 			else if (unlikely(deadline > apic->lapic_timer.period)) {
1816 				pr_info_ratelimited(
1817 				    "kvm: vcpu %i: requested lapic timer restore with "
1818 				    "starting count register %#x=%u (%lld ns) > initial count (%lld ns). "
1819 				    "Using initial count to start timer.\n",
1820 				    apic->vcpu->vcpu_id,
1821 				    count_reg,
1822 				    kvm_lapic_get_reg(apic, count_reg),
1823 				    deadline, apic->lapic_timer.period);
1824 				kvm_lapic_set_reg(apic, count_reg, 0);
1825 				deadline = apic->lapic_timer.period;
1826 			}
1827 		}
1828 	}
1829 
1830 	apic->lapic_timer.tscdeadline = kvm_read_l1_tsc(apic->vcpu, tscl) +
1831 		nsec_to_cycles(apic->vcpu, deadline);
1832 	apic->lapic_timer.target_expiration = ktime_add_ns(now, deadline);
1833 
1834 	return true;
1835 }
1836 
1837 static void advance_periodic_target_expiration(struct kvm_lapic *apic)
1838 {
1839 	ktime_t now = ktime_get();
1840 	u64 tscl = rdtsc();
1841 	ktime_t delta;
1842 
1843 	/*
1844 	 * Synchronize both deadlines to the same time source or
1845 	 * differences in the periods (caused by differences in the
1846 	 * underlying clocks or numerical approximation errors) will
1847 	 * cause the two to drift apart over time as the errors
1848 	 * accumulate.
1849 	 */
1850 	apic->lapic_timer.target_expiration =
1851 		ktime_add_ns(apic->lapic_timer.target_expiration,
1852 				apic->lapic_timer.period);
1853 	delta = ktime_sub(apic->lapic_timer.target_expiration, now);
1854 	apic->lapic_timer.tscdeadline = kvm_read_l1_tsc(apic->vcpu, tscl) +
1855 		nsec_to_cycles(apic->vcpu, delta);
1856 }
1857 
1858 static void start_sw_period(struct kvm_lapic *apic)
1859 {
1860 	if (!apic->lapic_timer.period)
1861 		return;
1862 
1863 	if (ktime_after(ktime_get(),
1864 			apic->lapic_timer.target_expiration)) {
1865 		apic_timer_expired(apic, false);
1866 
1867 		if (apic_lvtt_oneshot(apic))
1868 			return;
1869 
1870 		advance_periodic_target_expiration(apic);
1871 	}
1872 
1873 	hrtimer_start(&apic->lapic_timer.timer,
1874 		apic->lapic_timer.target_expiration,
1875 		HRTIMER_MODE_ABS_HARD);
1876 }
1877 
1878 bool kvm_lapic_hv_timer_in_use(struct kvm_vcpu *vcpu)
1879 {
1880 	if (!lapic_in_kernel(vcpu))
1881 		return false;
1882 
1883 	return vcpu->arch.apic->lapic_timer.hv_timer_in_use;
1884 }
1885 EXPORT_SYMBOL_GPL(kvm_lapic_hv_timer_in_use);
1886 
1887 static void cancel_hv_timer(struct kvm_lapic *apic)
1888 {
1889 	WARN_ON(preemptible());
1890 	WARN_ON(!apic->lapic_timer.hv_timer_in_use);
1891 	static_call(kvm_x86_cancel_hv_timer)(apic->vcpu);
1892 	apic->lapic_timer.hv_timer_in_use = false;
1893 }
1894 
1895 static bool start_hv_timer(struct kvm_lapic *apic)
1896 {
1897 	struct kvm_timer *ktimer = &apic->lapic_timer;
1898 	struct kvm_vcpu *vcpu = apic->vcpu;
1899 	bool expired;
1900 
1901 	WARN_ON(preemptible());
1902 	if (!kvm_can_use_hv_timer(vcpu))
1903 		return false;
1904 
1905 	if (!ktimer->tscdeadline)
1906 		return false;
1907 
1908 	if (static_call(kvm_x86_set_hv_timer)(vcpu, ktimer->tscdeadline, &expired))
1909 		return false;
1910 
1911 	ktimer->hv_timer_in_use = true;
1912 	hrtimer_cancel(&ktimer->timer);
1913 
1914 	/*
1915 	 * To simplify handling the periodic timer, leave the hv timer running
1916 	 * even if the deadline timer has expired, i.e. rely on the resulting
1917 	 * VM-Exit to recompute the periodic timer's target expiration.
1918 	 */
1919 	if (!apic_lvtt_period(apic)) {
1920 		/*
1921 		 * Cancel the hv timer if the sw timer fired while the hv timer
1922 		 * was being programmed, or if the hv timer itself expired.
1923 		 */
1924 		if (atomic_read(&ktimer->pending)) {
1925 			cancel_hv_timer(apic);
1926 		} else if (expired) {
1927 			apic_timer_expired(apic, false);
1928 			cancel_hv_timer(apic);
1929 		}
1930 	}
1931 
1932 	trace_kvm_hv_timer_state(vcpu->vcpu_id, ktimer->hv_timer_in_use);
1933 
1934 	return true;
1935 }
1936 
1937 static void start_sw_timer(struct kvm_lapic *apic)
1938 {
1939 	struct kvm_timer *ktimer = &apic->lapic_timer;
1940 
1941 	WARN_ON(preemptible());
1942 	if (apic->lapic_timer.hv_timer_in_use)
1943 		cancel_hv_timer(apic);
1944 	if (!apic_lvtt_period(apic) && atomic_read(&ktimer->pending))
1945 		return;
1946 
1947 	if (apic_lvtt_period(apic) || apic_lvtt_oneshot(apic))
1948 		start_sw_period(apic);
1949 	else if (apic_lvtt_tscdeadline(apic))
1950 		start_sw_tscdeadline(apic);
1951 	trace_kvm_hv_timer_state(apic->vcpu->vcpu_id, false);
1952 }
1953 
1954 static void restart_apic_timer(struct kvm_lapic *apic)
1955 {
1956 	preempt_disable();
1957 
1958 	if (!apic_lvtt_period(apic) && atomic_read(&apic->lapic_timer.pending))
1959 		goto out;
1960 
1961 	if (!start_hv_timer(apic))
1962 		start_sw_timer(apic);
1963 out:
1964 	preempt_enable();
1965 }
1966 
1967 void kvm_lapic_expired_hv_timer(struct kvm_vcpu *vcpu)
1968 {
1969 	struct kvm_lapic *apic = vcpu->arch.apic;
1970 
1971 	preempt_disable();
1972 	/* If the preempt notifier has already run, it also called apic_timer_expired */
1973 	if (!apic->lapic_timer.hv_timer_in_use)
1974 		goto out;
1975 	WARN_ON(kvm_vcpu_is_blocking(vcpu));
1976 	apic_timer_expired(apic, false);
1977 	cancel_hv_timer(apic);
1978 
1979 	if (apic_lvtt_period(apic) && apic->lapic_timer.period) {
1980 		advance_periodic_target_expiration(apic);
1981 		restart_apic_timer(apic);
1982 	}
1983 out:
1984 	preempt_enable();
1985 }
1986 EXPORT_SYMBOL_GPL(kvm_lapic_expired_hv_timer);
1987 
1988 void kvm_lapic_switch_to_hv_timer(struct kvm_vcpu *vcpu)
1989 {
1990 	restart_apic_timer(vcpu->arch.apic);
1991 }
1992 
1993 void kvm_lapic_switch_to_sw_timer(struct kvm_vcpu *vcpu)
1994 {
1995 	struct kvm_lapic *apic = vcpu->arch.apic;
1996 
1997 	preempt_disable();
1998 	/* Possibly the TSC deadline timer is not enabled yet */
1999 	if (apic->lapic_timer.hv_timer_in_use)
2000 		start_sw_timer(apic);
2001 	preempt_enable();
2002 }
2003 
2004 void kvm_lapic_restart_hv_timer(struct kvm_vcpu *vcpu)
2005 {
2006 	struct kvm_lapic *apic = vcpu->arch.apic;
2007 
2008 	WARN_ON(!apic->lapic_timer.hv_timer_in_use);
2009 	restart_apic_timer(apic);
2010 }
2011 
2012 static void __start_apic_timer(struct kvm_lapic *apic, u32 count_reg)
2013 {
2014 	atomic_set(&apic->lapic_timer.pending, 0);
2015 
2016 	if ((apic_lvtt_period(apic) || apic_lvtt_oneshot(apic))
2017 	    && !set_target_expiration(apic, count_reg))
2018 		return;
2019 
2020 	restart_apic_timer(apic);
2021 }
2022 
2023 static void start_apic_timer(struct kvm_lapic *apic)
2024 {
2025 	__start_apic_timer(apic, APIC_TMICT);
2026 }
2027 
2028 static void apic_manage_nmi_watchdog(struct kvm_lapic *apic, u32 lvt0_val)
2029 {
2030 	bool lvt0_in_nmi_mode = apic_lvt_nmi_mode(lvt0_val);
2031 
2032 	if (apic->lvt0_in_nmi_mode != lvt0_in_nmi_mode) {
2033 		apic->lvt0_in_nmi_mode = lvt0_in_nmi_mode;
2034 		if (lvt0_in_nmi_mode) {
2035 			atomic_inc(&apic->vcpu->kvm->arch.vapics_in_nmi_mode);
2036 		} else
2037 			atomic_dec(&apic->vcpu->kvm->arch.vapics_in_nmi_mode);
2038 	}
2039 }
2040 
2041 static int kvm_lapic_reg_write(struct kvm_lapic *apic, u32 reg, u32 val)
2042 {
2043 	int ret = 0;
2044 
2045 	trace_kvm_apic_write(reg, val);
2046 
2047 	switch (reg) {
2048 	case APIC_ID:		/* Local APIC ID */
2049 		if (!apic_x2apic_mode(apic))
2050 			kvm_apic_set_xapic_id(apic, val >> 24);
2051 		else
2052 			ret = 1;
2053 		break;
2054 
2055 	case APIC_TASKPRI:
2056 		report_tpr_access(apic, true);
2057 		apic_set_tpr(apic, val & 0xff);
2058 		break;
2059 
2060 	case APIC_EOI:
2061 		apic_set_eoi(apic);
2062 		break;
2063 
2064 	case APIC_LDR:
2065 		if (!apic_x2apic_mode(apic))
2066 			kvm_apic_set_ldr(apic, val & APIC_LDR_MASK);
2067 		else
2068 			ret = 1;
2069 		break;
2070 
2071 	case APIC_DFR:
2072 		if (!apic_x2apic_mode(apic))
2073 			kvm_apic_set_dfr(apic, val | 0x0FFFFFFF);
2074 		else
2075 			ret = 1;
2076 		break;
2077 
2078 	case APIC_SPIV: {
2079 		u32 mask = 0x3ff;
2080 		if (kvm_lapic_get_reg(apic, APIC_LVR) & APIC_LVR_DIRECTED_EOI)
2081 			mask |= APIC_SPIV_DIRECTED_EOI;
2082 		apic_set_spiv(apic, val & mask);
2083 		if (!(val & APIC_SPIV_APIC_ENABLED)) {
2084 			int i;
2085 			u32 lvt_val;
2086 
2087 			for (i = 0; i < KVM_APIC_LVT_NUM; i++) {
2088 				lvt_val = kvm_lapic_get_reg(apic,
2089 						       APIC_LVTT + 0x10 * i);
2090 				kvm_lapic_set_reg(apic, APIC_LVTT + 0x10 * i,
2091 					     lvt_val | APIC_LVT_MASKED);
2092 			}
2093 			apic_update_lvtt(apic);
2094 			atomic_set(&apic->lapic_timer.pending, 0);
2095 
2096 		}
2097 		break;
2098 	}
2099 	case APIC_ICR:
2100 		WARN_ON_ONCE(apic_x2apic_mode(apic));
2101 
2102 		/* No delay here, so we always clear the pending bit */
2103 		val &= ~APIC_ICR_BUSY;
2104 		kvm_apic_send_ipi(apic, val, kvm_lapic_get_reg(apic, APIC_ICR2));
2105 		kvm_lapic_set_reg(apic, APIC_ICR, val);
2106 		break;
2107 	case APIC_ICR2:
2108 		if (apic_x2apic_mode(apic))
2109 			ret = 1;
2110 		else
2111 			kvm_lapic_set_reg(apic, APIC_ICR2, val & 0xff000000);
2112 		break;
2113 
2114 	case APIC_LVT0:
2115 		apic_manage_nmi_watchdog(apic, val);
2116 		fallthrough;
2117 	case APIC_LVTTHMR:
2118 	case APIC_LVTPC:
2119 	case APIC_LVT1:
2120 	case APIC_LVTERR: {
2121 		/* TODO: Check vector */
2122 		size_t size;
2123 		u32 index;
2124 
2125 		if (!kvm_apic_sw_enabled(apic))
2126 			val |= APIC_LVT_MASKED;
2127 		size = ARRAY_SIZE(apic_lvt_mask);
2128 		index = array_index_nospec(
2129 				(reg - APIC_LVTT) >> 4, size);
2130 		val &= apic_lvt_mask[index];
2131 		kvm_lapic_set_reg(apic, reg, val);
2132 		break;
2133 	}
2134 
2135 	case APIC_LVTT:
2136 		if (!kvm_apic_sw_enabled(apic))
2137 			val |= APIC_LVT_MASKED;
2138 		val &= (apic_lvt_mask[0] | apic->lapic_timer.timer_mode_mask);
2139 		kvm_lapic_set_reg(apic, APIC_LVTT, val);
2140 		apic_update_lvtt(apic);
2141 		break;
2142 
2143 	case APIC_TMICT:
2144 		if (apic_lvtt_tscdeadline(apic))
2145 			break;
2146 
2147 		cancel_apic_timer(apic);
2148 		kvm_lapic_set_reg(apic, APIC_TMICT, val);
2149 		start_apic_timer(apic);
2150 		break;
2151 
2152 	case APIC_TDCR: {
2153 		uint32_t old_divisor = apic->divide_count;
2154 
2155 		kvm_lapic_set_reg(apic, APIC_TDCR, val & 0xb);
2156 		update_divide_count(apic);
2157 		if (apic->divide_count != old_divisor &&
2158 				apic->lapic_timer.period) {
2159 			hrtimer_cancel(&apic->lapic_timer.timer);
2160 			update_target_expiration(apic, old_divisor);
2161 			restart_apic_timer(apic);
2162 		}
2163 		break;
2164 	}
2165 	case APIC_ESR:
2166 		if (apic_x2apic_mode(apic) && val != 0)
2167 			ret = 1;
2168 		break;
2169 
2170 	case APIC_SELF_IPI:
2171 		if (apic_x2apic_mode(apic))
2172 			kvm_apic_send_ipi(apic, APIC_DEST_SELF | (val & APIC_VECTOR_MASK), 0);
2173 		else
2174 			ret = 1;
2175 		break;
2176 	default:
2177 		ret = 1;
2178 		break;
2179 	}
2180 
2181 	/*
2182 	 * Recalculate APIC maps if necessary, e.g. if the software enable bit
2183 	 * was toggled, the APIC ID changed, etc...   The maps are marked dirty
2184 	 * on relevant changes, i.e. this is a nop for most writes.
2185 	 */
2186 	kvm_recalculate_apic_map(apic->vcpu->kvm);
2187 
2188 	return ret;
2189 }
2190 
2191 static int apic_mmio_write(struct kvm_vcpu *vcpu, struct kvm_io_device *this,
2192 			    gpa_t address, int len, const void *data)
2193 {
2194 	struct kvm_lapic *apic = to_lapic(this);
2195 	unsigned int offset = address - apic->base_address;
2196 	u32 val;
2197 
2198 	if (!apic_mmio_in_range(apic, address))
2199 		return -EOPNOTSUPP;
2200 
2201 	if (!kvm_apic_hw_enabled(apic) || apic_x2apic_mode(apic)) {
2202 		if (!kvm_check_has_quirk(vcpu->kvm,
2203 					 KVM_X86_QUIRK_LAPIC_MMIO_HOLE))
2204 			return -EOPNOTSUPP;
2205 
2206 		return 0;
2207 	}
2208 
2209 	/*
2210 	 * APIC register must be aligned on 128-bits boundary.
2211 	 * 32/64/128 bits registers must be accessed thru 32 bits.
2212 	 * Refer SDM 8.4.1
2213 	 */
2214 	if (len != 4 || (offset & 0xf))
2215 		return 0;
2216 
2217 	val = *(u32*)data;
2218 
2219 	kvm_lapic_reg_write(apic, offset & 0xff0, val);
2220 
2221 	return 0;
2222 }
2223 
2224 void kvm_lapic_set_eoi(struct kvm_vcpu *vcpu)
2225 {
2226 	kvm_lapic_reg_write(vcpu->arch.apic, APIC_EOI, 0);
2227 }
2228 EXPORT_SYMBOL_GPL(kvm_lapic_set_eoi);
2229 
2230 /* emulate APIC access in a trap manner */
2231 void kvm_apic_write_nodecode(struct kvm_vcpu *vcpu, u32 offset)
2232 {
2233 	u32 val = kvm_lapic_get_reg(vcpu->arch.apic, offset);
2234 
2235 	/* TODO: optimize to just emulate side effect w/o one more write */
2236 	kvm_lapic_reg_write(vcpu->arch.apic, offset, val);
2237 }
2238 EXPORT_SYMBOL_GPL(kvm_apic_write_nodecode);
2239 
2240 void kvm_free_lapic(struct kvm_vcpu *vcpu)
2241 {
2242 	struct kvm_lapic *apic = vcpu->arch.apic;
2243 
2244 	if (!vcpu->arch.apic)
2245 		return;
2246 
2247 	hrtimer_cancel(&apic->lapic_timer.timer);
2248 
2249 	if (!(vcpu->arch.apic_base & MSR_IA32_APICBASE_ENABLE))
2250 		static_branch_slow_dec_deferred(&apic_hw_disabled);
2251 
2252 	if (!apic->sw_enabled)
2253 		static_branch_slow_dec_deferred(&apic_sw_disabled);
2254 
2255 	if (apic->regs)
2256 		free_page((unsigned long)apic->regs);
2257 
2258 	kfree(apic);
2259 }
2260 
2261 /*
2262  *----------------------------------------------------------------------
2263  * LAPIC interface
2264  *----------------------------------------------------------------------
2265  */
2266 u64 kvm_get_lapic_tscdeadline_msr(struct kvm_vcpu *vcpu)
2267 {
2268 	struct kvm_lapic *apic = vcpu->arch.apic;
2269 
2270 	if (!kvm_apic_present(vcpu) || !apic_lvtt_tscdeadline(apic))
2271 		return 0;
2272 
2273 	return apic->lapic_timer.tscdeadline;
2274 }
2275 
2276 void kvm_set_lapic_tscdeadline_msr(struct kvm_vcpu *vcpu, u64 data)
2277 {
2278 	struct kvm_lapic *apic = vcpu->arch.apic;
2279 
2280 	if (!kvm_apic_present(vcpu) || !apic_lvtt_tscdeadline(apic))
2281 		return;
2282 
2283 	hrtimer_cancel(&apic->lapic_timer.timer);
2284 	apic->lapic_timer.tscdeadline = data;
2285 	start_apic_timer(apic);
2286 }
2287 
2288 void kvm_lapic_set_tpr(struct kvm_vcpu *vcpu, unsigned long cr8)
2289 {
2290 	apic_set_tpr(vcpu->arch.apic, (cr8 & 0x0f) << 4);
2291 }
2292 
2293 u64 kvm_lapic_get_cr8(struct kvm_vcpu *vcpu)
2294 {
2295 	u64 tpr;
2296 
2297 	tpr = (u64) kvm_lapic_get_reg(vcpu->arch.apic, APIC_TASKPRI);
2298 
2299 	return (tpr & 0xf0) >> 4;
2300 }
2301 
2302 void kvm_lapic_set_base(struct kvm_vcpu *vcpu, u64 value)
2303 {
2304 	u64 old_value = vcpu->arch.apic_base;
2305 	struct kvm_lapic *apic = vcpu->arch.apic;
2306 
2307 	vcpu->arch.apic_base = value;
2308 
2309 	if ((old_value ^ value) & MSR_IA32_APICBASE_ENABLE)
2310 		kvm_update_cpuid_runtime(vcpu);
2311 
2312 	if (!apic)
2313 		return;
2314 
2315 	/* update jump label if enable bit changes */
2316 	if ((old_value ^ value) & MSR_IA32_APICBASE_ENABLE) {
2317 		if (value & MSR_IA32_APICBASE_ENABLE) {
2318 			kvm_apic_set_xapic_id(apic, vcpu->vcpu_id);
2319 			static_branch_slow_dec_deferred(&apic_hw_disabled);
2320 			/* Check if there are APF page ready requests pending */
2321 			kvm_make_request(KVM_REQ_APF_READY, vcpu);
2322 		} else {
2323 			static_branch_inc(&apic_hw_disabled.key);
2324 			atomic_set_release(&apic->vcpu->kvm->arch.apic_map_dirty, DIRTY);
2325 		}
2326 	}
2327 
2328 	if (((old_value ^ value) & X2APIC_ENABLE) && (value & X2APIC_ENABLE))
2329 		kvm_apic_set_x2apic_id(apic, vcpu->vcpu_id);
2330 
2331 	if ((old_value ^ value) & (MSR_IA32_APICBASE_ENABLE | X2APIC_ENABLE))
2332 		static_call_cond(kvm_x86_set_virtual_apic_mode)(vcpu);
2333 
2334 	apic->base_address = apic->vcpu->arch.apic_base &
2335 			     MSR_IA32_APICBASE_BASE;
2336 
2337 	if ((value & MSR_IA32_APICBASE_ENABLE) &&
2338 	     apic->base_address != APIC_DEFAULT_PHYS_BASE)
2339 		pr_warn_once("APIC base relocation is unsupported by KVM");
2340 }
2341 
2342 void kvm_apic_update_apicv(struct kvm_vcpu *vcpu)
2343 {
2344 	struct kvm_lapic *apic = vcpu->arch.apic;
2345 
2346 	if (vcpu->arch.apicv_active) {
2347 		/* irr_pending is always true when apicv is activated. */
2348 		apic->irr_pending = true;
2349 		apic->isr_count = 1;
2350 	} else {
2351 		/*
2352 		 * Don't clear irr_pending, searching the IRR can race with
2353 		 * updates from the CPU as APICv is still active from hardware's
2354 		 * perspective.  The flag will be cleared as appropriate when
2355 		 * KVM injects the interrupt.
2356 		 */
2357 		apic->isr_count = count_vectors(apic->regs + APIC_ISR);
2358 	}
2359 }
2360 EXPORT_SYMBOL_GPL(kvm_apic_update_apicv);
2361 
2362 void kvm_lapic_reset(struct kvm_vcpu *vcpu, bool init_event)
2363 {
2364 	struct kvm_lapic *apic = vcpu->arch.apic;
2365 	u64 msr_val;
2366 	int i;
2367 
2368 	if (!init_event) {
2369 		msr_val = APIC_DEFAULT_PHYS_BASE | MSR_IA32_APICBASE_ENABLE;
2370 		if (kvm_vcpu_is_reset_bsp(vcpu))
2371 			msr_val |= MSR_IA32_APICBASE_BSP;
2372 		kvm_lapic_set_base(vcpu, msr_val);
2373 	}
2374 
2375 	if (!apic)
2376 		return;
2377 
2378 	/* Stop the timer in case it's a reset to an active apic */
2379 	hrtimer_cancel(&apic->lapic_timer.timer);
2380 
2381 	/* The xAPIC ID is set at RESET even if the APIC was already enabled. */
2382 	if (!init_event)
2383 		kvm_apic_set_xapic_id(apic, vcpu->vcpu_id);
2384 	kvm_apic_set_version(apic->vcpu);
2385 
2386 	for (i = 0; i < KVM_APIC_LVT_NUM; i++)
2387 		kvm_lapic_set_reg(apic, APIC_LVTT + 0x10 * i, APIC_LVT_MASKED);
2388 	apic_update_lvtt(apic);
2389 	if (kvm_vcpu_is_reset_bsp(vcpu) &&
2390 	    kvm_check_has_quirk(vcpu->kvm, KVM_X86_QUIRK_LINT0_REENABLED))
2391 		kvm_lapic_set_reg(apic, APIC_LVT0,
2392 			     SET_APIC_DELIVERY_MODE(0, APIC_MODE_EXTINT));
2393 	apic_manage_nmi_watchdog(apic, kvm_lapic_get_reg(apic, APIC_LVT0));
2394 
2395 	kvm_apic_set_dfr(apic, 0xffffffffU);
2396 	apic_set_spiv(apic, 0xff);
2397 	kvm_lapic_set_reg(apic, APIC_TASKPRI, 0);
2398 	if (!apic_x2apic_mode(apic))
2399 		kvm_apic_set_ldr(apic, 0);
2400 	kvm_lapic_set_reg(apic, APIC_ESR, 0);
2401 	if (!apic_x2apic_mode(apic)) {
2402 		kvm_lapic_set_reg(apic, APIC_ICR, 0);
2403 		kvm_lapic_set_reg(apic, APIC_ICR2, 0);
2404 	} else {
2405 		kvm_lapic_set_reg64(apic, APIC_ICR, 0);
2406 	}
2407 	kvm_lapic_set_reg(apic, APIC_TDCR, 0);
2408 	kvm_lapic_set_reg(apic, APIC_TMICT, 0);
2409 	for (i = 0; i < 8; i++) {
2410 		kvm_lapic_set_reg(apic, APIC_IRR + 0x10 * i, 0);
2411 		kvm_lapic_set_reg(apic, APIC_ISR + 0x10 * i, 0);
2412 		kvm_lapic_set_reg(apic, APIC_TMR + 0x10 * i, 0);
2413 	}
2414 	kvm_apic_update_apicv(vcpu);
2415 	apic->highest_isr_cache = -1;
2416 	update_divide_count(apic);
2417 	atomic_set(&apic->lapic_timer.pending, 0);
2418 
2419 	vcpu->arch.pv_eoi.msr_val = 0;
2420 	apic_update_ppr(apic);
2421 	if (vcpu->arch.apicv_active) {
2422 		static_call_cond(kvm_x86_apicv_post_state_restore)(vcpu);
2423 		static_call_cond(kvm_x86_hwapic_irr_update)(vcpu, -1);
2424 		static_call_cond(kvm_x86_hwapic_isr_update)(vcpu, -1);
2425 	}
2426 
2427 	vcpu->arch.apic_arb_prio = 0;
2428 	vcpu->arch.apic_attention = 0;
2429 
2430 	kvm_recalculate_apic_map(vcpu->kvm);
2431 }
2432 
2433 /*
2434  *----------------------------------------------------------------------
2435  * timer interface
2436  *----------------------------------------------------------------------
2437  */
2438 
2439 static bool lapic_is_periodic(struct kvm_lapic *apic)
2440 {
2441 	return apic_lvtt_period(apic);
2442 }
2443 
2444 int apic_has_pending_timer(struct kvm_vcpu *vcpu)
2445 {
2446 	struct kvm_lapic *apic = vcpu->arch.apic;
2447 
2448 	if (apic_enabled(apic) && apic_lvt_enabled(apic, APIC_LVTT))
2449 		return atomic_read(&apic->lapic_timer.pending);
2450 
2451 	return 0;
2452 }
2453 
2454 int kvm_apic_local_deliver(struct kvm_lapic *apic, int lvt_type)
2455 {
2456 	u32 reg = kvm_lapic_get_reg(apic, lvt_type);
2457 	int vector, mode, trig_mode;
2458 
2459 	if (kvm_apic_hw_enabled(apic) && !(reg & APIC_LVT_MASKED)) {
2460 		vector = reg & APIC_VECTOR_MASK;
2461 		mode = reg & APIC_MODE_MASK;
2462 		trig_mode = reg & APIC_LVT_LEVEL_TRIGGER;
2463 		return __apic_accept_irq(apic, mode, vector, 1, trig_mode,
2464 					NULL);
2465 	}
2466 	return 0;
2467 }
2468 
2469 void kvm_apic_nmi_wd_deliver(struct kvm_vcpu *vcpu)
2470 {
2471 	struct kvm_lapic *apic = vcpu->arch.apic;
2472 
2473 	if (apic)
2474 		kvm_apic_local_deliver(apic, APIC_LVT0);
2475 }
2476 
2477 static const struct kvm_io_device_ops apic_mmio_ops = {
2478 	.read     = apic_mmio_read,
2479 	.write    = apic_mmio_write,
2480 };
2481 
2482 static enum hrtimer_restart apic_timer_fn(struct hrtimer *data)
2483 {
2484 	struct kvm_timer *ktimer = container_of(data, struct kvm_timer, timer);
2485 	struct kvm_lapic *apic = container_of(ktimer, struct kvm_lapic, lapic_timer);
2486 
2487 	apic_timer_expired(apic, true);
2488 
2489 	if (lapic_is_periodic(apic)) {
2490 		advance_periodic_target_expiration(apic);
2491 		hrtimer_add_expires_ns(&ktimer->timer, ktimer->period);
2492 		return HRTIMER_RESTART;
2493 	} else
2494 		return HRTIMER_NORESTART;
2495 }
2496 
2497 int kvm_create_lapic(struct kvm_vcpu *vcpu, int timer_advance_ns)
2498 {
2499 	struct kvm_lapic *apic;
2500 
2501 	ASSERT(vcpu != NULL);
2502 
2503 	apic = kzalloc(sizeof(*apic), GFP_KERNEL_ACCOUNT);
2504 	if (!apic)
2505 		goto nomem;
2506 
2507 	vcpu->arch.apic = apic;
2508 
2509 	apic->regs = (void *)get_zeroed_page(GFP_KERNEL_ACCOUNT);
2510 	if (!apic->regs) {
2511 		printk(KERN_ERR "malloc apic regs error for vcpu %x\n",
2512 		       vcpu->vcpu_id);
2513 		goto nomem_free_apic;
2514 	}
2515 	apic->vcpu = vcpu;
2516 
2517 	hrtimer_init(&apic->lapic_timer.timer, CLOCK_MONOTONIC,
2518 		     HRTIMER_MODE_ABS_HARD);
2519 	apic->lapic_timer.timer.function = apic_timer_fn;
2520 	if (timer_advance_ns == -1) {
2521 		apic->lapic_timer.timer_advance_ns = LAPIC_TIMER_ADVANCE_NS_INIT;
2522 		lapic_timer_advance_dynamic = true;
2523 	} else {
2524 		apic->lapic_timer.timer_advance_ns = timer_advance_ns;
2525 		lapic_timer_advance_dynamic = false;
2526 	}
2527 
2528 	/*
2529 	 * Stuff the APIC ENABLE bit in lieu of temporarily incrementing
2530 	 * apic_hw_disabled; the full RESET value is set by kvm_lapic_reset().
2531 	 */
2532 	vcpu->arch.apic_base = MSR_IA32_APICBASE_ENABLE;
2533 	static_branch_inc(&apic_sw_disabled.key); /* sw disabled at reset */
2534 	kvm_iodevice_init(&apic->dev, &apic_mmio_ops);
2535 
2536 	return 0;
2537 nomem_free_apic:
2538 	kfree(apic);
2539 	vcpu->arch.apic = NULL;
2540 nomem:
2541 	return -ENOMEM;
2542 }
2543 
2544 int kvm_apic_has_interrupt(struct kvm_vcpu *vcpu)
2545 {
2546 	struct kvm_lapic *apic = vcpu->arch.apic;
2547 	u32 ppr;
2548 
2549 	if (!kvm_apic_present(vcpu))
2550 		return -1;
2551 
2552 	__apic_update_ppr(apic, &ppr);
2553 	return apic_has_interrupt_for_ppr(apic, ppr);
2554 }
2555 EXPORT_SYMBOL_GPL(kvm_apic_has_interrupt);
2556 
2557 int kvm_apic_accept_pic_intr(struct kvm_vcpu *vcpu)
2558 {
2559 	u32 lvt0 = kvm_lapic_get_reg(vcpu->arch.apic, APIC_LVT0);
2560 
2561 	if (!kvm_apic_hw_enabled(vcpu->arch.apic))
2562 		return 1;
2563 	if ((lvt0 & APIC_LVT_MASKED) == 0 &&
2564 	    GET_APIC_DELIVERY_MODE(lvt0) == APIC_MODE_EXTINT)
2565 		return 1;
2566 	return 0;
2567 }
2568 
2569 void kvm_inject_apic_timer_irqs(struct kvm_vcpu *vcpu)
2570 {
2571 	struct kvm_lapic *apic = vcpu->arch.apic;
2572 
2573 	if (atomic_read(&apic->lapic_timer.pending) > 0) {
2574 		kvm_apic_inject_pending_timer_irqs(apic);
2575 		atomic_set(&apic->lapic_timer.pending, 0);
2576 	}
2577 }
2578 
2579 int kvm_get_apic_interrupt(struct kvm_vcpu *vcpu)
2580 {
2581 	int vector = kvm_apic_has_interrupt(vcpu);
2582 	struct kvm_lapic *apic = vcpu->arch.apic;
2583 	u32 ppr;
2584 
2585 	if (vector == -1)
2586 		return -1;
2587 
2588 	/*
2589 	 * We get here even with APIC virtualization enabled, if doing
2590 	 * nested virtualization and L1 runs with the "acknowledge interrupt
2591 	 * on exit" mode.  Then we cannot inject the interrupt via RVI,
2592 	 * because the process would deliver it through the IDT.
2593 	 */
2594 
2595 	apic_clear_irr(vector, apic);
2596 	if (to_hv_vcpu(vcpu) && test_bit(vector, to_hv_synic(vcpu)->auto_eoi_bitmap)) {
2597 		/*
2598 		 * For auto-EOI interrupts, there might be another pending
2599 		 * interrupt above PPR, so check whether to raise another
2600 		 * KVM_REQ_EVENT.
2601 		 */
2602 		apic_update_ppr(apic);
2603 	} else {
2604 		/*
2605 		 * For normal interrupts, PPR has been raised and there cannot
2606 		 * be a higher-priority pending interrupt---except if there was
2607 		 * a concurrent interrupt injection, but that would have
2608 		 * triggered KVM_REQ_EVENT already.
2609 		 */
2610 		apic_set_isr(vector, apic);
2611 		__apic_update_ppr(apic, &ppr);
2612 	}
2613 
2614 	return vector;
2615 }
2616 
2617 static int kvm_apic_state_fixup(struct kvm_vcpu *vcpu,
2618 		struct kvm_lapic_state *s, bool set)
2619 {
2620 	if (apic_x2apic_mode(vcpu->arch.apic)) {
2621 		u32 *id = (u32 *)(s->regs + APIC_ID);
2622 		u32 *ldr = (u32 *)(s->regs + APIC_LDR);
2623 		u64 icr;
2624 
2625 		if (vcpu->kvm->arch.x2apic_format) {
2626 			if (*id != vcpu->vcpu_id)
2627 				return -EINVAL;
2628 		} else {
2629 			if (set)
2630 				*id >>= 24;
2631 			else
2632 				*id <<= 24;
2633 		}
2634 
2635 		/*
2636 		 * In x2APIC mode, the LDR is fixed and based on the id.  And
2637 		 * ICR is internally a single 64-bit register, but needs to be
2638 		 * split to ICR+ICR2 in userspace for backwards compatibility.
2639 		 */
2640 		if (set) {
2641 			*ldr = kvm_apic_calc_x2apic_ldr(*id);
2642 
2643 			icr = __kvm_lapic_get_reg(s->regs, APIC_ICR) |
2644 			      (u64)__kvm_lapic_get_reg(s->regs, APIC_ICR2) << 32;
2645 			__kvm_lapic_set_reg64(s->regs, APIC_ICR, icr);
2646 		} else {
2647 			icr = __kvm_lapic_get_reg64(s->regs, APIC_ICR);
2648 			__kvm_lapic_set_reg(s->regs, APIC_ICR2, icr >> 32);
2649 		}
2650 	}
2651 
2652 	return 0;
2653 }
2654 
2655 int kvm_apic_get_state(struct kvm_vcpu *vcpu, struct kvm_lapic_state *s)
2656 {
2657 	memcpy(s->regs, vcpu->arch.apic->regs, sizeof(*s));
2658 
2659 	/*
2660 	 * Get calculated timer current count for remaining timer period (if
2661 	 * any) and store it in the returned register set.
2662 	 */
2663 	__kvm_lapic_set_reg(s->regs, APIC_TMCCT,
2664 			    __apic_read(vcpu->arch.apic, APIC_TMCCT));
2665 
2666 	return kvm_apic_state_fixup(vcpu, s, false);
2667 }
2668 
2669 int kvm_apic_set_state(struct kvm_vcpu *vcpu, struct kvm_lapic_state *s)
2670 {
2671 	struct kvm_lapic *apic = vcpu->arch.apic;
2672 	int r;
2673 
2674 	kvm_lapic_set_base(vcpu, vcpu->arch.apic_base);
2675 	/* set SPIV separately to get count of SW disabled APICs right */
2676 	apic_set_spiv(apic, *((u32 *)(s->regs + APIC_SPIV)));
2677 
2678 	r = kvm_apic_state_fixup(vcpu, s, true);
2679 	if (r) {
2680 		kvm_recalculate_apic_map(vcpu->kvm);
2681 		return r;
2682 	}
2683 	memcpy(vcpu->arch.apic->regs, s->regs, sizeof(*s));
2684 
2685 	atomic_set_release(&apic->vcpu->kvm->arch.apic_map_dirty, DIRTY);
2686 	kvm_recalculate_apic_map(vcpu->kvm);
2687 	kvm_apic_set_version(vcpu);
2688 
2689 	apic_update_ppr(apic);
2690 	cancel_apic_timer(apic);
2691 	apic->lapic_timer.expired_tscdeadline = 0;
2692 	apic_update_lvtt(apic);
2693 	apic_manage_nmi_watchdog(apic, kvm_lapic_get_reg(apic, APIC_LVT0));
2694 	update_divide_count(apic);
2695 	__start_apic_timer(apic, APIC_TMCCT);
2696 	kvm_lapic_set_reg(apic, APIC_TMCCT, 0);
2697 	kvm_apic_update_apicv(vcpu);
2698 	apic->highest_isr_cache = -1;
2699 	if (vcpu->arch.apicv_active) {
2700 		static_call_cond(kvm_x86_apicv_post_state_restore)(vcpu);
2701 		static_call_cond(kvm_x86_hwapic_irr_update)(vcpu, apic_find_highest_irr(apic));
2702 		static_call_cond(kvm_x86_hwapic_isr_update)(vcpu, apic_find_highest_isr(apic));
2703 	}
2704 	kvm_make_request(KVM_REQ_EVENT, vcpu);
2705 	if (ioapic_in_kernel(vcpu->kvm))
2706 		kvm_rtc_eoi_tracking_restore_one(vcpu);
2707 
2708 	vcpu->arch.apic_arb_prio = 0;
2709 
2710 	return 0;
2711 }
2712 
2713 void __kvm_migrate_apic_timer(struct kvm_vcpu *vcpu)
2714 {
2715 	struct hrtimer *timer;
2716 
2717 	if (!lapic_in_kernel(vcpu) ||
2718 		kvm_can_post_timer_interrupt(vcpu))
2719 		return;
2720 
2721 	timer = &vcpu->arch.apic->lapic_timer.timer;
2722 	if (hrtimer_cancel(timer))
2723 		hrtimer_start_expires(timer, HRTIMER_MODE_ABS_HARD);
2724 }
2725 
2726 /*
2727  * apic_sync_pv_eoi_from_guest - called on vmexit or cancel interrupt
2728  *
2729  * Detect whether guest triggered PV EOI since the
2730  * last entry. If yes, set EOI on guests's behalf.
2731  * Clear PV EOI in guest memory in any case.
2732  */
2733 static void apic_sync_pv_eoi_from_guest(struct kvm_vcpu *vcpu,
2734 					struct kvm_lapic *apic)
2735 {
2736 	int vector;
2737 	/*
2738 	 * PV EOI state is derived from KVM_APIC_PV_EOI_PENDING in host
2739 	 * and KVM_PV_EOI_ENABLED in guest memory as follows:
2740 	 *
2741 	 * KVM_APIC_PV_EOI_PENDING is unset:
2742 	 * 	-> host disabled PV EOI.
2743 	 * KVM_APIC_PV_EOI_PENDING is set, KVM_PV_EOI_ENABLED is set:
2744 	 * 	-> host enabled PV EOI, guest did not execute EOI yet.
2745 	 * KVM_APIC_PV_EOI_PENDING is set, KVM_PV_EOI_ENABLED is unset:
2746 	 * 	-> host enabled PV EOI, guest executed EOI.
2747 	 */
2748 	BUG_ON(!pv_eoi_enabled(vcpu));
2749 
2750 	if (pv_eoi_test_and_clr_pending(vcpu))
2751 		return;
2752 	vector = apic_set_eoi(apic);
2753 	trace_kvm_pv_eoi(apic, vector);
2754 }
2755 
2756 void kvm_lapic_sync_from_vapic(struct kvm_vcpu *vcpu)
2757 {
2758 	u32 data;
2759 
2760 	if (test_bit(KVM_APIC_PV_EOI_PENDING, &vcpu->arch.apic_attention))
2761 		apic_sync_pv_eoi_from_guest(vcpu, vcpu->arch.apic);
2762 
2763 	if (!test_bit(KVM_APIC_CHECK_VAPIC, &vcpu->arch.apic_attention))
2764 		return;
2765 
2766 	if (kvm_read_guest_cached(vcpu->kvm, &vcpu->arch.apic->vapic_cache, &data,
2767 				  sizeof(u32)))
2768 		return;
2769 
2770 	apic_set_tpr(vcpu->arch.apic, data & 0xff);
2771 }
2772 
2773 /*
2774  * apic_sync_pv_eoi_to_guest - called before vmentry
2775  *
2776  * Detect whether it's safe to enable PV EOI and
2777  * if yes do so.
2778  */
2779 static void apic_sync_pv_eoi_to_guest(struct kvm_vcpu *vcpu,
2780 					struct kvm_lapic *apic)
2781 {
2782 	if (!pv_eoi_enabled(vcpu) ||
2783 	    /* IRR set or many bits in ISR: could be nested. */
2784 	    apic->irr_pending ||
2785 	    /* Cache not set: could be safe but we don't bother. */
2786 	    apic->highest_isr_cache == -1 ||
2787 	    /* Need EOI to update ioapic. */
2788 	    kvm_ioapic_handles_vector(apic, apic->highest_isr_cache)) {
2789 		/*
2790 		 * PV EOI was disabled by apic_sync_pv_eoi_from_guest
2791 		 * so we need not do anything here.
2792 		 */
2793 		return;
2794 	}
2795 
2796 	pv_eoi_set_pending(apic->vcpu);
2797 }
2798 
2799 void kvm_lapic_sync_to_vapic(struct kvm_vcpu *vcpu)
2800 {
2801 	u32 data, tpr;
2802 	int max_irr, max_isr;
2803 	struct kvm_lapic *apic = vcpu->arch.apic;
2804 
2805 	apic_sync_pv_eoi_to_guest(vcpu, apic);
2806 
2807 	if (!test_bit(KVM_APIC_CHECK_VAPIC, &vcpu->arch.apic_attention))
2808 		return;
2809 
2810 	tpr = kvm_lapic_get_reg(apic, APIC_TASKPRI) & 0xff;
2811 	max_irr = apic_find_highest_irr(apic);
2812 	if (max_irr < 0)
2813 		max_irr = 0;
2814 	max_isr = apic_find_highest_isr(apic);
2815 	if (max_isr < 0)
2816 		max_isr = 0;
2817 	data = (tpr & 0xff) | ((max_isr & 0xf0) << 8) | (max_irr << 24);
2818 
2819 	kvm_write_guest_cached(vcpu->kvm, &vcpu->arch.apic->vapic_cache, &data,
2820 				sizeof(u32));
2821 }
2822 
2823 int kvm_lapic_set_vapic_addr(struct kvm_vcpu *vcpu, gpa_t vapic_addr)
2824 {
2825 	if (vapic_addr) {
2826 		if (kvm_gfn_to_hva_cache_init(vcpu->kvm,
2827 					&vcpu->arch.apic->vapic_cache,
2828 					vapic_addr, sizeof(u32)))
2829 			return -EINVAL;
2830 		__set_bit(KVM_APIC_CHECK_VAPIC, &vcpu->arch.apic_attention);
2831 	} else {
2832 		__clear_bit(KVM_APIC_CHECK_VAPIC, &vcpu->arch.apic_attention);
2833 	}
2834 
2835 	vcpu->arch.apic->vapic_addr = vapic_addr;
2836 	return 0;
2837 }
2838 
2839 int kvm_x2apic_icr_write(struct kvm_lapic *apic, u64 data)
2840 {
2841 	data &= ~APIC_ICR_BUSY;
2842 
2843 	kvm_apic_send_ipi(apic, (u32)data, (u32)(data >> 32));
2844 	kvm_lapic_set_reg64(apic, APIC_ICR, data);
2845 	trace_kvm_apic_write(APIC_ICR, data);
2846 	return 0;
2847 }
2848 
2849 static int kvm_lapic_msr_read(struct kvm_lapic *apic, u32 reg, u64 *data)
2850 {
2851 	u32 low;
2852 
2853 	if (reg == APIC_ICR) {
2854 		*data = kvm_lapic_get_reg64(apic, APIC_ICR);
2855 		return 0;
2856 	}
2857 
2858 	if (kvm_lapic_reg_read(apic, reg, 4, &low))
2859 		return 1;
2860 
2861 	*data = low;
2862 
2863 	return 0;
2864 }
2865 
2866 static int kvm_lapic_msr_write(struct kvm_lapic *apic, u32 reg, u64 data)
2867 {
2868 	/*
2869 	 * ICR is a 64-bit register in x2APIC mode (and Hyper'v PV vAPIC) and
2870 	 * can be written as such, all other registers remain accessible only
2871 	 * through 32-bit reads/writes.
2872 	 */
2873 	if (reg == APIC_ICR)
2874 		return kvm_x2apic_icr_write(apic, data);
2875 
2876 	return kvm_lapic_reg_write(apic, reg, (u32)data);
2877 }
2878 
2879 int kvm_x2apic_msr_write(struct kvm_vcpu *vcpu, u32 msr, u64 data)
2880 {
2881 	struct kvm_lapic *apic = vcpu->arch.apic;
2882 	u32 reg = (msr - APIC_BASE_MSR) << 4;
2883 
2884 	if (!lapic_in_kernel(vcpu) || !apic_x2apic_mode(apic))
2885 		return 1;
2886 
2887 	return kvm_lapic_msr_write(apic, reg, data);
2888 }
2889 
2890 int kvm_x2apic_msr_read(struct kvm_vcpu *vcpu, u32 msr, u64 *data)
2891 {
2892 	struct kvm_lapic *apic = vcpu->arch.apic;
2893 	u32 reg = (msr - APIC_BASE_MSR) << 4;
2894 
2895 	if (!lapic_in_kernel(vcpu) || !apic_x2apic_mode(apic))
2896 		return 1;
2897 
2898 	if (reg == APIC_DFR)
2899 		return 1;
2900 
2901 	return kvm_lapic_msr_read(apic, reg, data);
2902 }
2903 
2904 int kvm_hv_vapic_msr_write(struct kvm_vcpu *vcpu, u32 reg, u64 data)
2905 {
2906 	if (!lapic_in_kernel(vcpu))
2907 		return 1;
2908 
2909 	return kvm_lapic_msr_write(vcpu->arch.apic, reg, data);
2910 }
2911 
2912 int kvm_hv_vapic_msr_read(struct kvm_vcpu *vcpu, u32 reg, u64 *data)
2913 {
2914 	if (!lapic_in_kernel(vcpu))
2915 		return 1;
2916 
2917 	return kvm_lapic_msr_read(vcpu->arch.apic, reg, data);
2918 }
2919 
2920 int kvm_lapic_set_pv_eoi(struct kvm_vcpu *vcpu, u64 data, unsigned long len)
2921 {
2922 	u64 addr = data & ~KVM_MSR_ENABLED;
2923 	struct gfn_to_hva_cache *ghc = &vcpu->arch.pv_eoi.data;
2924 	unsigned long new_len;
2925 	int ret;
2926 
2927 	if (!IS_ALIGNED(addr, 4))
2928 		return 1;
2929 
2930 	if (data & KVM_MSR_ENABLED) {
2931 		if (addr == ghc->gpa && len <= ghc->len)
2932 			new_len = ghc->len;
2933 		else
2934 			new_len = len;
2935 
2936 		ret = kvm_gfn_to_hva_cache_init(vcpu->kvm, ghc, addr, new_len);
2937 		if (ret)
2938 			return ret;
2939 	}
2940 
2941 	vcpu->arch.pv_eoi.msr_val = data;
2942 
2943 	return 0;
2944 }
2945 
2946 int kvm_apic_accept_events(struct kvm_vcpu *vcpu)
2947 {
2948 	struct kvm_lapic *apic = vcpu->arch.apic;
2949 	u8 sipi_vector;
2950 	int r;
2951 	unsigned long pe;
2952 
2953 	if (!lapic_in_kernel(vcpu))
2954 		return 0;
2955 
2956 	/*
2957 	 * Read pending events before calling the check_events
2958 	 * callback.
2959 	 */
2960 	pe = smp_load_acquire(&apic->pending_events);
2961 	if (!pe)
2962 		return 0;
2963 
2964 	if (is_guest_mode(vcpu)) {
2965 		r = kvm_check_nested_events(vcpu);
2966 		if (r < 0)
2967 			return r == -EBUSY ? 0 : r;
2968 		/*
2969 		 * If an event has happened and caused a vmexit,
2970 		 * we know INITs are latched and therefore
2971 		 * we will not incorrectly deliver an APIC
2972 		 * event instead of a vmexit.
2973 		 */
2974 	}
2975 
2976 	/*
2977 	 * INITs are latched while CPU is in specific states
2978 	 * (SMM, VMX root mode, SVM with GIF=0).
2979 	 * Because a CPU cannot be in these states immediately
2980 	 * after it has processed an INIT signal (and thus in
2981 	 * KVM_MP_STATE_INIT_RECEIVED state), just eat SIPIs
2982 	 * and leave the INIT pending.
2983 	 */
2984 	if (kvm_vcpu_latch_init(vcpu)) {
2985 		WARN_ON_ONCE(vcpu->arch.mp_state == KVM_MP_STATE_INIT_RECEIVED);
2986 		if (test_bit(KVM_APIC_SIPI, &pe))
2987 			clear_bit(KVM_APIC_SIPI, &apic->pending_events);
2988 		return 0;
2989 	}
2990 
2991 	if (test_bit(KVM_APIC_INIT, &pe)) {
2992 		clear_bit(KVM_APIC_INIT, &apic->pending_events);
2993 		kvm_vcpu_reset(vcpu, true);
2994 		if (kvm_vcpu_is_bsp(apic->vcpu))
2995 			vcpu->arch.mp_state = KVM_MP_STATE_RUNNABLE;
2996 		else
2997 			vcpu->arch.mp_state = KVM_MP_STATE_INIT_RECEIVED;
2998 	}
2999 	if (test_bit(KVM_APIC_SIPI, &pe)) {
3000 		clear_bit(KVM_APIC_SIPI, &apic->pending_events);
3001 		if (vcpu->arch.mp_state == KVM_MP_STATE_INIT_RECEIVED) {
3002 			/* evaluate pending_events before reading the vector */
3003 			smp_rmb();
3004 			sipi_vector = apic->sipi_vector;
3005 			static_call(kvm_x86_vcpu_deliver_sipi_vector)(vcpu, sipi_vector);
3006 			vcpu->arch.mp_state = KVM_MP_STATE_RUNNABLE;
3007 		}
3008 	}
3009 	return 0;
3010 }
3011 
3012 void kvm_lapic_exit(void)
3013 {
3014 	static_key_deferred_flush(&apic_hw_disabled);
3015 	WARN_ON(static_branch_unlikely(&apic_hw_disabled.key));
3016 	static_key_deferred_flush(&apic_sw_disabled);
3017 	WARN_ON(static_branch_unlikely(&apic_sw_disabled.key));
3018 }
3019