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