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