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