]> git.ipfire.org Git - thirdparty/linux.git/blame - arch/x86/kvm/lapic.c
Merge tag 'mmc-v6.16-rc1' of git://git.kernel.org/pub/scm/linux/kernel/git/ulfh/mmc
[thirdparty/linux.git] / arch / x86 / kvm / lapic.c
CommitLineData
20c8ccb1 1// SPDX-License-Identifier: GPL-2.0-only
97222cc8
ED
2
3/*
4 * Local APIC virtualization
5 *
6 * Copyright (C) 2006 Qumranet, Inc.
7 * Copyright (C) 2007 Novell
8 * Copyright (C) 2007 Intel
9611c187 9 * Copyright 2009 Red Hat, Inc. and/or its affiliates.
97222cc8
ED
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.
97222cc8 17 */
8d20bd63 18#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
97222cc8 19
edf88417 20#include <linux/kvm_host.h>
97222cc8
ED
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>
1767e931 27#include <linux/export.h>
6f6d6a1a 28#include <linux/math64.h>
5a0e3ad6 29#include <linux/slab.h>
97222cc8 30#include <asm/processor.h>
4b903561 31#include <asm/mce.h>
97222cc8
ED
32#include <asm/msr.h>
33#include <asm/page.h>
34#include <asm/current.h>
35#include <asm/apicdef.h>
d0659d94 36#include <asm/delay.h>
60063497 37#include <linux/atomic.h>
c5cc421b 38#include <linux/jump_label.h>
5fdbf976 39#include "kvm_cache_regs.h"
97222cc8 40#include "irq.h"
88197e6a 41#include "ioapic.h"
229456fc 42#include "trace.h"
fc61b800 43#include "x86.h"
8e62bf2b 44#include "xen.h"
00b27a3e 45#include "cpuid.h"
5c919412 46#include "hyperv.h"
b0b42197 47#include "smm.h"
97222cc8 48
b682b814
MT
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
97222cc8 55/* 14 is the version for Xeon and Pentium 8.4.8*/
951ceb94 56#define APIC_VERSION 0x14UL
97222cc8
ED
57#define LAPIC_MMIO_LENGTH (1 << 12)
58/* followed define is not in apicdef.h */
97222cc8 59#define MAX_APIC_VECTOR 256
ecba9a52 60#define APIC_VECTORS_PER_REG 32
97222cc8 61
89a58812
SC
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 */
70static bool lapic_timer_advance __read_mostly = true;
71module_param(lapic_timer_advance, bool, 0444);
72
a0f0037e
WL
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
3b8a5df6
WL
77/* step-by-step approximation to mitigate fluctuation */
78#define LAPIC_TIMER_ADVANCE_ADJUST_STEP 8
5413bcba 79static int kvm_lapic_msr_read(struct kvm_lapic *apic, u32 reg, u64 *data);
1bd9dfec 80static int kvm_lapic_msr_write(struct kvm_lapic *apic, u32 reg, u64 data);
3b8a5df6 81
b9964ee3
SC
82static inline void __kvm_lapic_set_reg(char *regs, int reg_off, u32 val)
83{
84 *((u32 *) (regs + reg_off)) = val;
85}
86
87static 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
a57a3168
SC
92static __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
98static __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
103static __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
109static __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
a0c9a822
MT
115static inline int apic_test_vector(int vec, void *bitmap)
116{
117 return test_bit(VEC_POS(vec), (bitmap) + REG_POS(vec));
118}
119
10606919
YZ
120bool 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
8680b94b
MT
128static 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
133static 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
a78d9046
SC
138__read_mostly DEFINE_STATIC_KEY_FALSE(kvm_has_noapic_vcpu);
139EXPORT_SYMBOL_GPL(kvm_has_noapic_vcpu);
140
6e4e3b4d
CL
141__read_mostly DEFINE_STATIC_KEY_DEFERRED_FALSE(apic_hw_disabled, HZ);
142__read_mostly DEFINE_STATIC_KEY_DEFERRED_FALSE(apic_sw_disabled, HZ);
f8c1ea10 143
97222cc8
ED
144static inline int apic_enabled(struct kvm_lapic *apic)
145{
c48f1496 146 return kvm_apic_sw_enabled(apic) && kvm_apic_hw_enabled(apic);
54e9818f
GN
147}
148
97222cc8
ED
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
6e500439
RK
156static inline u32 kvm_x2apic_id(struct kvm_lapic *apic)
157{
158 return apic->vcpu->vcpu_id;
159}
160
199a8b84 161static bool kvm_can_post_timer_interrupt(struct kvm_vcpu *vcpu)
0c5f81da 162{
1714a4eb
WL
163 return pi_inject_timer && kvm_vcpu_apicv_active(vcpu) &&
164 (kvm_mwait_in_guest(vcpu->kvm) || kvm_hlt_in_guest(vcpu->kvm));
0c5f81da 165}
199a8b84
PB
166
167bool 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}
0c5f81da
WL
173
174static 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
76e52750
SC
179static inline u32 kvm_apic_calc_x2apic_ldr(u32 id)
180{
181 return ((id >> 4) << 16) | (1 << (id & 0xf));
182}
183
e45115b6
RK
184static inline bool kvm_apic_map_get_logical_dest(struct kvm_apic_map *map,
185 u32 dest_id, struct kvm_lapic ***cluster, u16 *mask) {
35366901
SC
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;
e45115b6
RK
192 case KVM_APIC_MODE_X2APIC: {
193 u32 offset = (dest_id >> 16) * 16;
0ca52e7b 194 u32 max_apic_id = map->max_apic_id;
e45115b6
RK
195
196 if (offset <= max_apic_id) {
197 u8 cluster_size = min(max_apic_id - offset + 1, 16U);
198
1d487e9b 199 offset = array_index_nospec(offset, map->max_apic_id + 1);
e45115b6
RK
200 *cluster = &map->phys_map[offset];
201 *mask = dest_id & (0xffff >> (16 - cluster_size));
202 } else {
203 *mask = 0;
204 }
3b5a5ffa 205
e45115b6
RK
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:
444fdad8 213 *cluster = map->xapic_cluster_map[(dest_id >> 4) & 0xf];
e45115b6
RK
214 *mask = dest_id & 0xf;
215 return true;
35366901
SC
216 case KVM_APIC_MODE_MAP_DISABLED:
217 return false;
e45115b6 218 default:
35366901 219 WARN_ON_ONCE(1);
e45115b6
RK
220 return false;
221 }
3548a259
RK
222}
223
72c70cee
SC
224static 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
4364b287
SC
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
72c70cee
SC
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(). */
4364b287 275 if (apic_x2apic_mode(apic) || x2apic_id > 0xff)
72c70cee
SC
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
300static 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 */
4b7c3f6d 347 if (apic_x2apic_mode(apic))
72c70cee 348 return;
72c70cee
SC
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
44d52717
PB
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 */
372enum {
373 CLEAN,
374 UPDATE_IN_PROGRESS,
375 DIRTY
376};
377
ff6ce56e 378static void kvm_recalculate_apic_map(struct kvm *kvm)
1e08ec4a
GN
379{
380 struct kvm_apic_map *new, *old = NULL;
381 struct kvm_vcpu *vcpu;
46808a4c 382 unsigned long i;
6e500439 383 u32 max_id = 255; /* enough space for any xAPIC ID */
41e90a69
SC
384 bool xapic_id_mismatch;
385 int r;
1e08ec4a 386
44d52717
PB
387 /* Read kvm->arch.apic_map_dirty before kvm->arch.apic_map. */
388 if (atomic_read_acquire(&kvm->arch.apic_map_dirty) == CLEAN)
4abaffce 389 return;
4abaffce 390
c2f79a65
SC
391 WARN_ONCE(!irqchip_in_kernel(kvm),
392 "Dirty APIC map without an in-kernel local APIC");
393
1e08ec4a 394 mutex_lock(&kvm->arch.apic_map_lock);
41e90a69
SC
395
396retry:
44d52717 397 /*
41e90a69
SC
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.
44d52717
PB
403 */
404 if (atomic_cmpxchg_acquire(&kvm->arch.apic_map_dirty,
405 DIRTY, UPDATE_IN_PROGRESS) == CLEAN) {
4abaffce
WL
406 /* Someone else has updated the map. */
407 mutex_unlock(&kvm->arch.apic_map_lock);
408 return;
409 }
1e08ec4a 410
41e90a69
SC
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
0ca52e7b
RK
420 kvm_for_each_vcpu(i, vcpu, kvm)
421 if (kvm_apic_present(vcpu))
6e500439 422 max_id = max(max_id, kvm_x2apic_id(vcpu->arch.apic));
0ca52e7b 423
a7c3e901 424 new = kvzalloc(sizeof(struct kvm_apic_map) +
254272ce
BG
425 sizeof(struct kvm_lapic *) * ((u64)max_id + 1),
426 GFP_KERNEL_ACCOUNT);
0ca52e7b 427
1e08ec4a
GN
428 if (!new)
429 goto out;
430
0ca52e7b 431 new->max_apic_id = max_id;
35366901 432 new->logical_mode = KVM_APIC_MODE_SW_DISABLED;
0ca52e7b 433
173beedc 434 kvm_for_each_vcpu(i, vcpu, kvm) {
df04d1d1
RK
435 if (!kvm_apic_present(vcpu))
436 continue;
437
41e90a69
SC
438 r = kvm_recalculate_phys_map(new, vcpu, &xapic_id_mismatch);
439 if (r) {
72c70cee
SC
440 kvfree(new);
441 new = NULL;
41e90a69
SC
442 if (r == -E2BIG) {
443 cond_resched();
444 goto retry;
445 }
446
72c70cee 447 goto out;
3b5a5ffa
RK
448 }
449
72c70cee 450 kvm_recalculate_logical_map(new, vcpu);
1e08ec4a
GN
451 }
452out:
5063c41b
SC
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
9a364857
SC
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
d471bd85
GE
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
1e08ec4a
GN
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);
4abaffce 476 /*
44d52717
PB
477 * Write kvm->arch.apic_map before clearing apic->apic_map_dirty.
478 * If another update has come in, leave it DIRTY.
4abaffce 479 */
44d52717
PB
480 atomic_cmpxchg_release(&kvm->arch.apic_map_dirty,
481 UPDATE_IN_PROGRESS, CLEAN);
1e08ec4a
GN
482 mutex_unlock(&kvm->arch.apic_map_lock);
483
484 if (old)
82c47012 485 kvfree_rcu(old, rcu);
c7c9c56c 486
b053b2ae 487 kvm_make_scan_ioapic_request(kvm);
1e08ec4a
GN
488}
489
1e1b6c26
NA
490static inline void apic_set_spiv(struct kvm_lapic *apic, u32 val)
491{
e462755c 492 bool enabled = val & APIC_SPIV_APIC_ENABLED;
1e1b6c26 493
1e6e2755 494 kvm_lapic_set_reg(apic, APIC_SPIV, val);
e462755c
RK
495
496 if (enabled != apic->sw_enabled) {
497 apic->sw_enabled = enabled;
eb1ff0a9 498 if (enabled)
6e4e3b4d 499 static_branch_slow_dec_deferred(&apic_sw_disabled);
eb1ff0a9 500 else
6e4e3b4d 501 static_branch_inc(&apic_sw_disabled.key);
b14c876b 502
44d52717 503 atomic_set_release(&apic->vcpu->kvm->arch.apic_map_dirty, DIRTY);
1e1b6c26 504 }
2f15d027
VK
505
506 /* Check if there are APF page ready requests pending */
8e62bf2b 507 if (enabled) {
2f15d027 508 kvm_make_request(KVM_REQ_APF_READY, apic->vcpu);
8e62bf2b
DW
509 kvm_xen_sw_enable_lapic(apic->vcpu);
510 }
1e1b6c26
NA
511}
512
a92e2543 513static inline void kvm_apic_set_xapic_id(struct kvm_lapic *apic, u8 id)
1e08ec4a 514{
1e6e2755 515 kvm_lapic_set_reg(apic, APIC_ID, id << 24);
44d52717 516 atomic_set_release(&apic->vcpu->kvm->arch.apic_map_dirty, DIRTY);
1e08ec4a
GN
517}
518
519static inline void kvm_apic_set_ldr(struct kvm_lapic *apic, u32 id)
520{
1e6e2755 521 kvm_lapic_set_reg(apic, APIC_LDR, id);
44d52717 522 atomic_set_release(&apic->vcpu->kvm->arch.apic_map_dirty, DIRTY);
1e08ec4a
GN
523}
524
ae6f2496
WL
525static 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
a92e2543 531static inline void kvm_apic_set_x2apic_id(struct kvm_lapic *apic, u32 id)
257b9a5f 532{
e872fa94 533 u32 ldr = kvm_apic_calc_x2apic_ldr(id);
257b9a5f 534
6e500439
RK
535 WARN_ON_ONCE(id != apic->vcpu->vcpu_id);
536
a92e2543 537 kvm_lapic_set_reg(apic, APIC_ID, id);
1e6e2755 538 kvm_lapic_set_reg(apic, APIC_LDR, ldr);
44d52717 539 atomic_set_release(&apic->vcpu->kvm->arch.apic_map_dirty, DIRTY);
257b9a5f
RK
540}
541
97222cc8
ED
542static inline int apic_lvt_enabled(struct kvm_lapic *apic, int lvt_type)
543{
dfb95954 544 return !(kvm_lapic_get_reg(apic, lvt_type) & APIC_LVT_MASKED);
97222cc8
ED
545}
546
a3e06bbe
LJ
547static inline int apic_lvtt_oneshot(struct kvm_lapic *apic)
548{
f30ebc31 549 return apic->lapic_timer.timer_mode == APIC_LVT_TIMER_ONESHOT;
a3e06bbe
LJ
550}
551
97222cc8
ED
552static inline int apic_lvtt_period(struct kvm_lapic *apic)
553{
f30ebc31 554 return apic->lapic_timer.timer_mode == APIC_LVT_TIMER_PERIODIC;
a3e06bbe
LJ
555}
556
557static inline int apic_lvtt_tscdeadline(struct kvm_lapic *apic)
558{
f30ebc31 559 return apic->lapic_timer.timer_mode == APIC_LVT_TIMER_TSCDEADLINE;
97222cc8
ED
560}
561
cc6e462c
JK
562static 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
4b903561
JW
567static inline bool kvm_lapic_lvt_supported(struct kvm_lapic *apic, int lvt_index)
568{
569 return apic->nr_lvt_entries > lvt_index;
570}
571
03d84f96
SC
572static 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
fc61b800
GN
577void kvm_apic_set_version(struct kvm_vcpu *vcpu)
578{
579 struct kvm_lapic *apic = vcpu->arch.apic;
4b903561 580 u32 v = 0;
fc61b800 581
bce87cce 582 if (!lapic_in_kernel(vcpu))
fc61b800
GN
583 return;
584
4b903561
JW
585 v = APIC_VERSION | ((apic->nr_lvt_entries - 1) << 16);
586
0bcc3fb9
VK
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 */
8f2a2775 594 if (guest_cpu_cap_has(vcpu, X86_FEATURE_X2APIC) &&
0bcc3fb9 595 !ioapic_in_kernel(vcpu->kvm))
fc61b800 596 v |= APIC_LVR_DIRECTED_EOI;
1e6e2755 597 kvm_lapic_set_reg(apic, APIC_LVR, v);
fc61b800
GN
598}
599
f83894b2
SC
600void 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
1d8c681f
JW
619static 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,
4b903561
JW
625 [LVT_ERROR] = LVT_MASK,
626 [LVT_CMCI] = LVT_MASK | APIC_MODE_MASK
97222cc8
ED
627};
628
629static int find_highest_vector(void *bitmap)
630{
ecba9a52
TY
631 int vec;
632 u32 *reg;
97222cc8 633
ecba9a52
TY
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)
810e6def 638 return __fls(*reg) + vec;
ecba9a52 639 }
97222cc8 640
ecba9a52 641 return -1;
97222cc8
ED
642}
643
8680b94b
MT
644static u8 count_vectors(void *bitmap)
645{
ecba9a52
TY
646 int vec;
647 u32 *reg;
8680b94b 648 u8 count = 0;
ecba9a52
TY
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
8680b94b
MT
655 return count;
656}
657
f1459315 658bool __kvm_apic_update_irr(unsigned long *pir, void *regs, int *max_irr)
a20ed54d 659{
edaf3ede 660 unsigned long pir_vals[NR_PIR_WORDS];
06b4d0ea 661 u32 *__pir = (void *)pir_vals;
810e6def 662 u32 i, vec;
06b4d0ea 663 u32 irr_val, prev_irr_val;
e7387b0e
LA
664 int max_updated_irr;
665
666 max_updated_irr = -1;
667 *max_irr = -1;
a20ed54d 668
edaf3ede 669 if (!pi_harvest_pir(pir, pir_vals))
b41f8638
SC
670 return false;
671
810e6def 672 for (i = vec = 0; i <= 7; i++, vec += 32) {
514946d1
ML
673 u32 *p_irr = (u32 *)(regs + APIC_IRR + i * 0x10);
674
6433fc01 675 irr_val = READ_ONCE(*p_irr);
514946d1 676
06b4d0ea 677 if (__pir[i]) {
e7387b0e 678 prev_irr_val = irr_val;
514946d1 679 do {
06b4d0ea 680 irr_val = prev_irr_val | __pir[i];
514946d1
ML
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;
ad361091 686 }
810e6def 687 if (irr_val)
e7387b0e 688 *max_irr = __fls(irr_val) + vec;
a20ed54d 689 }
810e6def 690
e7387b0e
LA
691 return ((max_updated_irr != -1) &&
692 (max_updated_irr == *max_irr));
a20ed54d 693}
705699a1
WV
694EXPORT_SYMBOL_GPL(__kvm_apic_update_irr);
695
f1459315 696bool kvm_apic_update_irr(struct kvm_vcpu *vcpu, unsigned long *pir, int *max_irr)
705699a1
WV
697{
698 struct kvm_lapic *apic = vcpu->arch.apic;
cff540eb 699 bool irr_updated = __kvm_apic_update_irr(pir, apic->regs, max_irr);
705699a1 700
cff540eb
ML
701 if (unlikely(!apic->apicv_active && irr_updated))
702 apic->irr_pending = true;
703 return irr_updated;
705699a1 704}
a20ed54d
YZ
705EXPORT_SYMBOL_GPL(kvm_apic_update_irr);
706
33e4c686 707static inline int apic_search_irr(struct kvm_lapic *apic)
97222cc8 708{
33e4c686 709 return find_highest_vector(apic->regs + APIC_IRR);
97222cc8
ED
710}
711
712static inline int apic_find_highest_irr(struct kvm_lapic *apic)
713{
714 int result;
715
c7c9c56c
YZ
716 /*
717 * Note that irr_pending is just a hint. It will be always
718 * true with virtual interrupt delivery enabled.
719 */
33e4c686
GN
720 if (!apic->irr_pending)
721 return -1;
722
723 result = apic_search_irr(apic);
97222cc8
ED
724 ASSERT(result == -1 || result >= 16);
725
726 return result;
727}
728
33e4c686
GN
729static inline void apic_clear_irr(int vec, struct kvm_lapic *apic)
730{
ce0a58f4 731 if (unlikely(apic->apicv_active)) {
ee171d2f 732 kvm_lapic_clear_vector(vec, apic->regs + APIC_IRR);
f210f757
NA
733 } else {
734 apic->irr_pending = false;
ee171d2f 735 kvm_lapic_clear_vector(vec, apic->regs + APIC_IRR);
f210f757
NA
736 if (apic_search_irr(apic) != -1)
737 apic->irr_pending = true;
56cc2406 738 }
33e4c686
GN
739}
740
25bb2cf9
SC
741void kvm_apic_clear_irr(struct kvm_vcpu *vcpu, int vec)
742{
743 apic_clear_irr(vec, vcpu->arch.apic);
744}
745EXPORT_SYMBOL_GPL(kvm_apic_clear_irr);
746
8680b94b
MT
747static inline void apic_set_isr(int vec, struct kvm_lapic *apic)
748{
56cc2406
WL
749 if (__apic_test_and_set_vector(vec, apic->regs + APIC_ISR))
750 return;
751
8680b94b 752 /*
56cc2406
WL
753 * With APIC virtualization enabled, all caching is disabled
754 * because the processor can modify ISR under the hood. Instead
755 * just set SVI.
8680b94b 756 */
ce0a58f4 757 if (unlikely(apic->apicv_active))
76bce9f1 758 kvm_x86_call(hwapic_isr_update)(apic->vcpu, vec);
56cc2406
WL
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 }
8680b94b
MT
769}
770
fc57ac2c
PB
771static 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
8680b94b
MT
790static inline void apic_clear_isr(int vec, struct kvm_lapic *apic)
791{
fc57ac2c
PB
792 if (!__apic_test_and_clear_vector(vec, apic->regs + APIC_ISR))
793 return;
794
fc57ac2c
PB
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 */
ce0a58f4 802 if (unlikely(apic->apicv_active))
76bce9f1 803 kvm_x86_call(hwapic_isr_update)(apic->vcpu, apic_find_highest_isr(apic));
fc57ac2c 804 else {
8680b94b 805 --apic->isr_count;
fc57ac2c
PB
806 BUG_ON(apic->isr_count < 0);
807 apic->highest_isr_cache = -1;
808 }
8680b94b
MT
809}
810
04bc93cf
CG
811void 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}
820EXPORT_SYMBOL_GPL(kvm_apic_update_hwapic_isr);
821
6e5d865c
YS
822int kvm_lapic_find_highest_irr(struct kvm_vcpu *vcpu)
823{
33e4c686
GN
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 */
f8543d6a 829 return apic_find_highest_irr(vcpu->arch.apic);
6e5d865c 830}
76dfafd5 831EXPORT_SYMBOL_GPL(kvm_lapic_find_highest_irr);
6e5d865c 832
6da7e3f6 833static int __apic_accept_irq(struct kvm_lapic *apic, int delivery_mode,
b4f2225c 834 int vector, int level, int trig_mode,
9e4aabe2 835 struct dest_map *dest_map);
6da7e3f6 836
b4f2225c 837int kvm_apic_set_irq(struct kvm_vcpu *vcpu, struct kvm_lapic_irq *irq,
9e4aabe2 838 struct dest_map *dest_map)
97222cc8 839{
ad312c7c 840 struct kvm_lapic *apic = vcpu->arch.apic;
8be5453f 841
58c2dde1 842 return __apic_accept_irq(apic, irq->delivery_mode, irq->vector,
b4f2225c 843 irq->level, irq->trig_mode, dest_map);
97222cc8
ED
844}
845
1a686237
ML
846static 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
4180bf1b 866int kvm_pv_send_ipi(struct kvm *kvm, unsigned long ipi_bitmap_low,
bdf7ffc8 867 unsigned long ipi_bitmap_high, u32 min,
4180bf1b
WL
868 unsigned long icr, int op_64_bit)
869{
4180bf1b 870 struct kvm_apic_map *map;
4180bf1b
WL
871 struct kvm_lapic_irq irq = {0};
872 int cluster_size = op_64_bit ? 64 : 32;
1a686237
ML
873 int count;
874
875 if (icr & (APIC_DEST_MASK | APIC_SHORT_MASK))
876 return -KVM_EINVAL;
4180bf1b
WL
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
4180bf1b
WL
883 rcu_read_lock();
884 map = rcu_dereference(kvm->arch.apic_map);
885
1a686237
ML
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);
4180bf1b
WL
891 }
892
893 rcu_read_unlock();
894 return count;
895}
896
ae7a2a3f
MT
897static int pv_eoi_put_user(struct kvm_vcpu *vcpu, u8 val)
898{
4e335d9e
PB
899
900 return kvm_write_guest_cached(vcpu->kvm, &vcpu->arch.pv_eoi.data, &val,
901 sizeof(val));
ae7a2a3f
MT
902}
903
904static int pv_eoi_get_user(struct kvm_vcpu *vcpu, u8 *val)
905{
4e335d9e
PB
906
907 return kvm_read_guest_cached(vcpu->kvm, &vcpu->arch.pv_eoi.data, val,
908 sizeof(*val));
ae7a2a3f
MT
909}
910
911static inline bool pv_eoi_enabled(struct kvm_vcpu *vcpu)
912{
913 return vcpu->arch.pv_eoi.msr_val & KVM_MSR_ENABLED;
914}
915
ae7a2a3f
MT
916static void pv_eoi_set_pending(struct kvm_vcpu *vcpu)
917{
ce5977b1 918 if (pv_eoi_put_user(vcpu, KVM_PV_EOI_ENABLED) < 0)
ae7a2a3f 919 return;
ce5977b1 920
ae7a2a3f
MT
921 __set_bit(KVM_APIC_PV_EOI_PENDING, &vcpu->arch.apic_attention);
922}
923
51b1209c 924static bool pv_eoi_test_and_clr_pending(struct kvm_vcpu *vcpu)
ae7a2a3f 925{
51b1209c
LR
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;
ce5977b1 935
51b1209c
LR
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 */
ae7a2a3f 941 __clear_bit(KVM_APIC_PV_EOI_PENDING, &vcpu->arch.apic_attention);
51b1209c
LR
942
943 return val;
ae7a2a3f
MT
944}
945
b3c045d3
PB
946static int apic_has_interrupt_for_ppr(struct kvm_lapic *apic, u32 ppr)
947{
3d92789f 948 int highest_irr;
37c4dbf3 949 if (kvm_x86_ops.sync_pir_to_irr)
89604647 950 highest_irr = kvm_x86_call(sync_pir_to_irr)(apic->vcpu);
76dfafd5
PB
951 else
952 highest_irr = apic_find_highest_irr(apic);
b3c045d3
PB
953 if (highest_irr == -1 || (highest_irr & 0xF0) <= ppr)
954 return -1;
955 return highest_irr;
956}
957
958static bool __apic_update_ppr(struct kvm_lapic *apic, u32 *new_ppr)
97222cc8 959{
3842d135 960 u32 tpr, isrv, ppr, old_ppr;
97222cc8
ED
961 int isr;
962
dfb95954
SS
963 old_ppr = kvm_lapic_get_reg(apic, APIC_PROCPRI);
964 tpr = kvm_lapic_get_reg(apic, APIC_TASKPRI);
97222cc8
ED
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
b3c045d3
PB
973 *new_ppr = ppr;
974 if (old_ppr != ppr)
1e6e2755 975 kvm_lapic_set_reg(apic, APIC_PROCPRI, ppr);
b3c045d3
PB
976
977 return ppr < old_ppr;
978}
979
980static void apic_update_ppr(struct kvm_lapic *apic)
981{
982 u32 ppr;
983
26fbbee5
PB
984 if (__apic_update_ppr(apic, &ppr) &&
985 apic_has_interrupt_for_ppr(apic, ppr) != -1)
b3c045d3 986 kvm_make_request(KVM_REQ_EVENT, apic->vcpu);
97222cc8
ED
987}
988
eb90f341
PB
989void kvm_apic_update_ppr(struct kvm_vcpu *vcpu)
990{
991 apic_update_ppr(vcpu->arch.apic);
992}
993EXPORT_SYMBOL_GPL(kvm_apic_update_ppr);
994
97222cc8
ED
995static void apic_set_tpr(struct kvm_lapic *apic, u32 tpr)
996{
1e6e2755 997 kvm_lapic_set_reg(apic, APIC_TASKPRI, tpr);
97222cc8
ED
998 apic_update_ppr(apic);
999}
1000
03d2249e 1001static bool kvm_apic_broadcast(struct kvm_lapic *apic, u32 mda)
394457a9 1002{
b4535b58
RK
1003 return mda == (apic_x2apic_mode(apic) ?
1004 X2APIC_BROADCAST : APIC_BROADCAST);
394457a9
NA
1005}
1006
03d2249e 1007static bool kvm_apic_match_physical_addr(struct kvm_lapic *apic, u32 mda)
97222cc8 1008{
03d2249e
RK
1009 if (kvm_apic_broadcast(apic, mda))
1010 return true;
1011
5bd5db38 1012 /*
8031d87a
SC
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).
5bd5db38 1020 */
8031d87a
SC
1021 if (apic_x2apic_mode(apic) || mda > 0xff)
1022 return mda == kvm_x2apic_id(apic);
5bd5db38 1023
b4535b58 1024 return mda == kvm_xapic_id(apic);
97222cc8
ED
1025}
1026
52c233a4 1027static bool kvm_apic_match_logical_addr(struct kvm_lapic *apic, u32 mda)
97222cc8 1028{
0105d1a5
GN
1029 u32 logical_id;
1030
394457a9 1031 if (kvm_apic_broadcast(apic, mda))
9368b567 1032 return true;
394457a9 1033
dfb95954 1034 logical_id = kvm_lapic_get_reg(apic, APIC_LDR);
97222cc8 1035
9368b567 1036 if (apic_x2apic_mode(apic))
8a395363
RK
1037 return ((logical_id >> 16) == (mda >> 16))
1038 && (logical_id & mda & 0xffff) != 0;
97222cc8 1039
9368b567 1040 logical_id = GET_APIC_LOGICAL_ID(logical_id);
97222cc8 1041
dfb95954 1042 switch (kvm_lapic_get_reg(apic, APIC_DFR)) {
97222cc8 1043 case APIC_DFR_FLAT:
9368b567 1044 return (logical_id & mda) != 0;
97222cc8 1045 case APIC_DFR_CLUSTER:
9368b567
RK
1046 return ((logical_id >> 4) == (mda >> 4))
1047 && (logical_id & mda & 0xf) != 0;
97222cc8 1048 default:
9368b567 1049 return false;
97222cc8 1050 }
97222cc8
ED
1051}
1052
c519265f
RK
1053/* The KVM local APIC implementation has two quirks:
1054 *
b4535b58
RK
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.
c519265f
RK
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".
03d2249e 1068 */
c519265f
RK
1069static u32 kvm_apic_mda(struct kvm_vcpu *vcpu, unsigned int dest_id,
1070 struct kvm_lapic *source, struct kvm_lapic *target)
03d2249e
RK
1071{
1072 bool ipi = source != NULL;
03d2249e 1073
c519265f 1074 if (!vcpu->kvm->arch.x2apic_broadcast_quirk_disabled &&
b4535b58 1075 !ipi && dest_id == APIC_BROADCAST && apic_x2apic_mode(target))
03d2249e
RK
1076 return X2APIC_BROADCAST;
1077
b4535b58 1078 return dest_id;
03d2249e
RK
1079}
1080
52c233a4 1081bool kvm_apic_match_dest(struct kvm_vcpu *vcpu, struct kvm_lapic *source,
5c69d5c1 1082 int shorthand, unsigned int dest, int dest_mode)
97222cc8 1083{
ad312c7c 1084 struct kvm_lapic *target = vcpu->arch.apic;
c519265f 1085 u32 mda = kvm_apic_mda(vcpu, dest, source, target);
97222cc8 1086
bd371396 1087 ASSERT(target);
5c69d5c1 1088 switch (shorthand) {
97222cc8 1089 case APIC_DEST_NOSHORT:
3697f302 1090 if (dest_mode == APIC_DEST_PHYSICAL)
03d2249e 1091 return kvm_apic_match_physical_addr(target, mda);
343f94fe 1092 else
03d2249e 1093 return kvm_apic_match_logical_addr(target, mda);
97222cc8 1094 case APIC_DEST_SELF:
9368b567 1095 return target == source;
97222cc8 1096 case APIC_DEST_ALLINC:
9368b567 1097 return true;
97222cc8 1098 case APIC_DEST_ALLBUT:
9368b567 1099 return target != source;
97222cc8 1100 default:
9368b567 1101 return false;
97222cc8 1102 }
97222cc8 1103}
1e6e2755 1104EXPORT_SYMBOL_GPL(kvm_apic_match_dest);
97222cc8 1105
52004014
FW
1106int 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
4efd805f
RK
1122static void kvm_apic_disabled_lapic_found(struct kvm *kvm)
1123{
1124 if (!kvm->arch.disabled_lapic_found) {
1125 kvm->arch.disabled_lapic_found = true;
8d20bd63 1126 pr_info("Disabled LAPIC found during irq injection\n");
4efd805f
RK
1127 }
1128}
1129
c519265f
RK
1130static bool kvm_apic_is_broadcast_dest(struct kvm *kvm, struct kvm_lapic **src,
1131 struct kvm_lapic_irq *irq, struct kvm_apic_map *map)
1e08ec4a 1132{
c519265f
RK
1133 if (kvm->arch.x2apic_broadcast_quirk_disabled) {
1134 if ((irq->dest_id == APIC_BROADCAST &&
35366901 1135 map->logical_mode != KVM_APIC_MODE_X2APIC))
c519265f
RK
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 }
1e08ec4a 1145
c519265f
RK
1146 return false;
1147}
1e08ec4a 1148
64aa47bf
RK
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 */
1156static 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;
1e08ec4a 1162
64aa47bf
RK
1163 if (irq->shorthand == APIC_DEST_SELF && src) {
1164 *dst = src;
1165 *bitmap = 1;
1166 return true;
1167 } else if (irq->shorthand)
1e08ec4a
GN
1168 return false;
1169
c519265f 1170 if (!map || kvm_apic_is_broadcast_dest(kvm, src, irq, map))
9ea369b0
RK
1171 return false;
1172
64aa47bf 1173 if (irq->dest_mode == APIC_DEST_PHYSICAL) {
0ca52e7b 1174 if (irq->dest_id > map->max_apic_id) {
64aa47bf
RK
1175 *bitmap = 0;
1176 } else {
1d487e9b
PB
1177 u32 dest_id = array_index_nospec(irq->dest_id, map->max_apic_id + 1);
1178 *dst = &map->phys_map[dest_id];
64aa47bf
RK
1179 *bitmap = 1;
1180 }
1e08ec4a 1181 return true;
bea15428 1182 }
698f9755 1183
e45115b6
RK
1184 *bitmap = 0;
1185 if (!kvm_apic_map_get_logical_dest(map, irq->dest_id, dst,
1186 (u16 *)bitmap))
1e08ec4a 1187 return false;
fa834e91 1188
64aa47bf
RK
1189 if (!kvm_lowest_prio_delivery(irq))
1190 return true;
3548a259 1191
64aa47bf
RK
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;
3548a259 1202 }
64aa47bf
RK
1203 } else {
1204 if (!*bitmap)
1205 return true;
3548a259 1206
64aa47bf
RK
1207 lowest = kvm_vector_to_index(irq->vector, hweight16(*bitmap),
1208 bitmap, 16);
45c3094a 1209
64aa47bf
RK
1210 if (!(*dst)[lowest]) {
1211 kvm_apic_disabled_lapic_found(kvm);
1212 *bitmap = 0;
1213 return true;
1214 }
1215 }
1e08ec4a 1216
64aa47bf 1217 *bitmap = (lowest >= 0) ? 1 << lowest : 0;
1e08ec4a 1218
64aa47bf
RK
1219 return true;
1220}
52004014 1221
64aa47bf
RK
1222bool 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;
52004014 1230
64aa47bf 1231 *r = -1;
52004014 1232
64aa47bf 1233 if (irq->shorthand == APIC_DEST_SELF) {
00b5f371
VK
1234 if (KVM_BUG_ON(!src, kvm)) {
1235 *r = 0;
1236 return true;
1237 }
64aa47bf
RK
1238 *r = kvm_apic_set_irq(src->vcpu, irq, dest_map);
1239 return true;
1240 }
52004014 1241
64aa47bf
RK
1242 rcu_read_lock();
1243 map = rcu_dereference(kvm->arch.apic_map);
52004014 1244
64aa47bf 1245 ret = kvm_apic_map_get_dest_lapic(kvm, &src, irq, map, &dst, &bitmap);
0624fca9
PB
1246 if (ret) {
1247 *r = 0;
64aa47bf
RK
1248 for_each_set_bit(i, &bitmap, 16) {
1249 if (!dst[i])
1250 continue;
64aa47bf 1251 *r += kvm_apic_set_irq(dst[i]->vcpu, irq, dest_map);
1e08ec4a 1252 }
0624fca9 1253 }
1e08ec4a 1254
1e08ec4a
GN
1255 rcu_read_unlock();
1256 return ret;
1257}
1258
6228a0da 1259/*
00116795 1260 * This routine tries to handle interrupts in posted mode, here is how
6228a0da
FW
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
67b0ae43 1265 * to find the destination vCPU.
6228a0da
FW
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 */
8feb4a04
FW
1273bool 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;
64aa47bf
RK
1277 unsigned long bitmap;
1278 struct kvm_lapic **dst = NULL;
8feb4a04 1279 bool ret = false;
8feb4a04
FW
1280
1281 if (irq->shorthand)
1282 return false;
1283
1284 rcu_read_lock();
1285 map = rcu_dereference(kvm->arch.apic_map);
1286
64aa47bf
RK
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);
6228a0da 1290
64aa47bf
RK
1291 if (dst[i]) {
1292 *dest_vcpu = dst[i]->vcpu;
1293 ret = true;
6228a0da 1294 }
8feb4a04
FW
1295 }
1296
8feb4a04
FW
1297 rcu_read_unlock();
1298 return ret;
1299}
1300
97222cc8
ED
1301/*
1302 * Add a pending IRQ into lapic.
1303 * Return 1 if successfully added and 0 if discarded.
1304 */
1305static int __apic_accept_irq(struct kvm_lapic *apic, int delivery_mode,
b4f2225c 1306 int vector, int level, int trig_mode,
9e4aabe2 1307 struct dest_map *dest_map)
97222cc8 1308{
6da7e3f6 1309 int result = 0;
c5ec1534 1310 struct kvm_vcpu *vcpu = apic->vcpu;
97222cc8 1311
a183b638
PB
1312 trace_kvm_apic_accept_irq(vcpu->vcpu_id, delivery_mode,
1313 trig_mode, vector);
97222cc8 1314 switch (delivery_mode) {
97222cc8 1315 case APIC_DM_LOWEST:
e1035715 1316 vcpu->arch.apic_arb_prio++;
df561f66 1317 fallthrough;
e1035715 1318 case APIC_DM_FIXED:
bdaffe1d
PB
1319 if (unlikely(trig_mode && !level))
1320 break;
1321
97222cc8
ED
1322 /* FIXME add logic for vcpu on reset */
1323 if (unlikely(!apic_enabled(apic)))
1324 break;
1325
11f5cc05
JK
1326 result = 1;
1327
9daa5007 1328 if (dest_map) {
9e4aabe2 1329 __set_bit(vcpu->vcpu_id, dest_map->map);
9daa5007
JR
1330 dest_map->vectors[vcpu->vcpu_id] = vector;
1331 }
a5d36f82 1332
bdaffe1d
PB
1333 if (apic_test_vector(vector, apic->regs + APIC_TMR) != !!trig_mode) {
1334 if (trig_mode)
ee171d2f
WY
1335 kvm_lapic_set_vector(vector,
1336 apic->regs + APIC_TMR);
bdaffe1d 1337 else
ee171d2f
WY
1338 kvm_lapic_clear_vector(vector,
1339 apic->regs + APIC_TMR);
bdaffe1d
PB
1340 }
1341
89604647
WW
1342 kvm_x86_call(deliver_interrupt)(apic, delivery_mode,
1343 trig_mode, vector);
97222cc8
ED
1344 break;
1345
1346 case APIC_DM_REMRD:
24d2166b
R
1347 result = 1;
1348 vcpu->arch.pv.pv_unhalted = 1;
1349 kvm_make_request(KVM_REQ_EVENT, vcpu);
1350 kvm_vcpu_kick(vcpu);
97222cc8
ED
1351 break;
1352
1353 case APIC_DM_SMI:
b0b42197
PB
1354 if (!kvm_inject_smi(vcpu)) {
1355 kvm_vcpu_kick(vcpu);
1356 result = 1;
1357 }
97222cc8 1358 break;
3419ffc8 1359
97222cc8 1360 case APIC_DM_NMI:
6da7e3f6 1361 result = 1;
3419ffc8 1362 kvm_inject_nmi(vcpu);
26df99c6 1363 kvm_vcpu_kick(vcpu);
97222cc8
ED
1364 break;
1365
1366 case APIC_DM_INIT:
a52315e1 1367 if (!trig_mode || level) {
6da7e3f6 1368 result = 1;
66450a21
JK
1369 /* assumes that there are only KVM_APIC_INIT/SIPI */
1370 apic->pending_events = (1UL << KVM_APIC_INIT);
3842d135 1371 kvm_make_request(KVM_REQ_EVENT, vcpu);
c5ec1534 1372 kvm_vcpu_kick(vcpu);
c5ec1534 1373 }
97222cc8
ED
1374 break;
1375
1376 case APIC_DM_STARTUP:
66450a21
JK
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);
97222cc8
ED
1384 break;
1385
23930f95
JK
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
97222cc8
ED
1394 default:
1395 printk(KERN_ERR "TODO: unsupported delivery mode %x\n",
1396 delivery_mode);
1397 break;
1398 }
1399 return result;
1400}
1401
7ee30bc1
NNL
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 */
1408void 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;
46808a4c
MZ
1415 unsigned long bitmap, i;
1416 int vcpu_idx;
7ee30bc1
NNL
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,
b4b29636 1436 irq->shorthand,
7ee30bc1
NNL
1437 irq->dest_id,
1438 irq->dest_mode))
1439 continue;
1440 __set_bit(i, vcpu_bitmap);
1441 }
1442 }
1443 rcu_read_unlock();
1444}
1445
e1035715 1446int kvm_apic_compare_prio(struct kvm_vcpu *vcpu1, struct kvm_vcpu *vcpu2)
8be5453f 1447{
e1035715 1448 return vcpu1->arch.apic_arb_prio - vcpu2->arch.apic_arb_prio;
8be5453f
ZX
1449}
1450
3bb345f3
PB
1451static bool kvm_ioapic_handles_vector(struct kvm_lapic *apic, int vector)
1452{
6308630b 1453 return test_bit(vector, apic->vcpu->arch.ioapic_handled_vectors);
3bb345f3
PB
1454}
1455
c7c9c56c
YZ
1456static void kvm_ioapic_send_eoi(struct kvm_lapic *apic, int vector)
1457{
7543a635
SR
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;
3bb345f3 1463
87e4951e 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
7543a635
SR
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;
c7c9c56c 1477 }
7543a635
SR
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);
c7c9c56c
YZ
1485}
1486
ae7a2a3f 1487static int apic_set_eoi(struct kvm_lapic *apic)
97222cc8
ED
1488{
1489 int vector = apic_find_highest_isr(apic);
ae7a2a3f
MT
1490
1491 trace_kvm_eoi(apic, vector);
1492
97222cc8
ED
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)
ae7a2a3f 1498 return vector;
97222cc8 1499
8680b94b 1500 apic_clear_isr(vector, apic);
97222cc8
ED
1501 apic_update_ppr(apic);
1502
0659262a 1503 if (kvm_hv_synic_has_vector(apic->vcpu, vector))
5c919412
AS
1504 kvm_hv_synic_send_eoi(apic->vcpu, vector);
1505
c7c9c56c 1506 kvm_ioapic_send_eoi(apic, vector);
3842d135 1507 kvm_make_request(KVM_REQ_EVENT, apic->vcpu);
ae7a2a3f 1508 return vector;
97222cc8
ED
1509}
1510
c7c9c56c
YZ
1511/*
1512 * this interface assumes a trap-like exit, which has already finished
1513 * desired side effect including vISR and vPPR update.
1514 */
1515void 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}
1524EXPORT_SYMBOL_GPL(kvm_apic_set_eoi_accelerated);
1525
d5361678 1526void kvm_apic_send_ipi(struct kvm_lapic *apic, u32 icr_low, u32 icr_high)
97222cc8 1527{
58c2dde1 1528 struct kvm_lapic_irq irq;
97222cc8 1529
bd17f417
SC
1530 /* KVM has no delay and should always clear the BUSY/PENDING flag. */
1531 WARN_ON_ONCE(icr_low & APIC_ICR_BUSY);
1532
58c2dde1
GN
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;
b7cb2231 1536 irq.level = (icr_low & APIC_INT_ASSERT) != 0;
58c2dde1
GN
1537 irq.trig_mode = icr_low & APIC_INT_LEVELTRIG;
1538 irq.shorthand = icr_low & APIC_SHORT_MASK;
93bbf0b8 1539 irq.msi_redir_hint = false;
0105d1a5
GN
1540 if (apic_x2apic_mode(apic))
1541 irq.dest_id = icr_high;
1542 else
bf348f66 1543 irq.dest_id = GET_XAPIC_DEST_FIELD(icr_high);
97222cc8 1544
1000ff8d
GN
1545 trace_kvm_apic_ipi(icr_low, irq.dest_id);
1546
b4f2225c 1547 kvm_irq_delivery_to_apic(apic->vcpu->kvm, apic, &irq, NULL);
97222cc8 1548}
b51818af 1549EXPORT_SYMBOL_GPL(kvm_apic_send_ipi);
97222cc8
ED
1550
1551static u32 apic_get_tmcct(struct kvm_lapic *apic)
1552{
8003c9ae 1553 ktime_t remaining, now;
b682b814 1554 s64 ns;
97222cc8
ED
1555
1556 ASSERT(apic != NULL);
1557
9da8f4e8 1558 /* if initial count is 0, current count should also be 0 */
dfb95954 1559 if (kvm_lapic_get_reg(apic, APIC_TMICT) == 0 ||
b963a22e 1560 apic->lapic_timer.period == 0)
9da8f4e8
KP
1561 return 0;
1562
5587859f 1563 now = ktime_get();
8003c9ae 1564 remaining = ktime_sub(apic->lapic_timer.target_expiration, now);
b682b814 1565 if (ktime_to_ns(remaining) < 0)
8b0e1953 1566 remaining = 0;
b682b814 1567
d3c7b77d 1568 ns = mod_64(ktime_to_ns(remaining), apic->lapic_timer.period);
b460256b
IY
1569 return div64_u64(ns, (apic->vcpu->kvm->arch.apic_bus_cycle_ns *
1570 apic->divide_count));
97222cc8
ED
1571}
1572
b209749f
AK
1573static 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
a8eeb04a 1578 kvm_make_request(KVM_REQ_REPORT_TPR_ACCESS, vcpu);
5fdbf976 1579 run->tpr_access.rip = kvm_rip_read(vcpu);
b209749f
AK
1580 run->tpr_access.is_write = write;
1581}
1582
1583static 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
97222cc8
ED
1589static 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:
97222cc8
ED
1598 break;
1599
1600 case APIC_TMCCT: /* Timer CCR */
a3e06bbe
LJ
1601 if (apic_lvtt_tscdeadline(apic))
1602 return 0;
1603
97222cc8
ED
1604 val = apic_get_tmcct(apic);
1605 break;
4a4541a4
AK
1606 case APIC_PROCPRI:
1607 apic_update_ppr(apic);
dfb95954 1608 val = kvm_lapic_get_reg(apic, offset);
4a4541a4 1609 break;
b209749f
AK
1610 case APIC_TASKPRI:
1611 report_tpr_access(apic, false);
df561f66 1612 fallthrough;
97222cc8 1613 default:
dfb95954 1614 val = kvm_lapic_get_reg(apic, offset);
97222cc8
ED
1615 break;
1616 }
1617
1618 return val;
1619}
1620
d76685c4
GH
1621static inline struct kvm_lapic *to_lapic(struct kvm_io_device *dev)
1622{
1623 return container_of(dev, struct kvm_lapic, dev);
1624}
1625
01402cf8
PB
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
b5fcc59b 1630u64 kvm_lapic_readable_reg_mask(struct kvm_lapic *apic)
97222cc8 1631{
b5fcc59b 1632 /* Leave bits '0' for reserved and write-only registers. */
01402cf8
PB
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) |
01402cf8
PB
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) |
01402cf8
PB
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
4b903561
JW
1655 if (kvm_lapic_lvt_supported(apic, LVT_CMCI))
1656 valid_reg_mask |= APIC_REG_MASK(APIC_LVTCMCI);
1657
b5fcc59b 1658 /* ARBPRI, DFR, and ICR2 are not valid in x2APIC mode. */
01402cf8 1659 if (!apic_x2apic_mode(apic))
a57a3168 1660 valid_reg_mask |= APIC_REG_MASK(APIC_ARBPRI) |
b2236495 1661 APIC_REG_MASK(APIC_DFR) |
a57a3168 1662 APIC_REG_MASK(APIC_ICR2);
b5fcc59b
SC
1663
1664 return valid_reg_mask;
1665}
1666EXPORT_SYMBOL_GPL(kvm_lapic_readable_reg_mask);
1667
1668static 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);
0105d1a5 1679
218bf772
JM
1680 if (alignment + len > 4)
1681 return 1;
1682
b5fcc59b
SC
1683 if (offset > 0x3f0 ||
1684 !(kvm_lapic_readable_reg_mask(apic) & APIC_REG_MASK(offset)))
0105d1a5 1685 return 1;
0105d1a5 1686
97222cc8
ED
1687 result = __apic_read(apic, offset & ~0xf);
1688
229456fc
MT
1689 trace_kvm_apic_read(offset, result);
1690
97222cc8
ED
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 }
bda9020e 1702 return 0;
97222cc8
ED
1703}
1704
0105d1a5
GN
1705static int apic_mmio_in_range(struct kvm_lapic *apic, gpa_t addr)
1706{
d1766202
VK
1707 return addr >= apic->base_address &&
1708 addr < apic->base_address + LAPIC_MMIO_LENGTH;
0105d1a5
GN
1709}
1710
e32edf4f 1711static int apic_mmio_read(struct kvm_vcpu *vcpu, struct kvm_io_device *this,
0105d1a5
GN
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
d1766202
VK
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
1e6e2755 1729 kvm_lapic_reg_read(apic, offset, len, data);
0105d1a5
GN
1730
1731 return 0;
1732}
1733
97222cc8
ED
1734static void update_divide_count(struct kvm_lapic *apic)
1735{
1736 u32 tmp1, tmp2, tdcr;
1737
dfb95954 1738 tdcr = kvm_lapic_get_reg(apic, APIC_TDCR);
97222cc8
ED
1739 tmp1 = tdcr & 0xf;
1740 tmp2 = ((tmp1 & 0x3) | ((tmp1 & 0x8) >> 1)) + 1;
d3c7b77d 1741 apic->divide_count = 0x1 << (tmp2 & 0x7);
97222cc8
ED
1742}
1743
ccbfa1d3
WL
1744static 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 */
dedf9c5e 1751 if (apic_lvtt_period(apic) && apic->lapic_timer.period) {
ccbfa1d3
WL
1752 s64 min_period = min_timer_period_us * 1000LL;
1753
1754 if (apic->lapic_timer.period < min_period) {
0005ca20 1755 pr_info_once(
8d20bd63 1756 "vcpu %i: requested %lld ns "
ccbfa1d3
WL
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
94be4b85
WL
1765static void cancel_hv_timer(struct kvm_lapic *apic);
1766
e898da78
WL
1767static 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();
619f51da 1774 atomic_set(&apic->lapic_timer.pending, 0);
e898da78
WL
1775}
1776
b6ac0695
RK
1777static void apic_update_lvtt(struct kvm_lapic *apic)
1778{
dfb95954 1779 u32 timer_mode = kvm_lapic_get_reg(apic, APIC_LVTT) &
b6ac0695
RK
1780 apic->lapic_timer.timer_mode_mask;
1781
1782 if (apic->lapic_timer.timer_mode != timer_mode) {
c69518c8 1783 if (apic_lvtt_tscdeadline(apic) != (timer_mode ==
dedf9c5e 1784 APIC_LVT_TIMER_TSCDEADLINE)) {
e898da78 1785 cancel_apic_timer(apic);
44275932
RK
1786 kvm_lapic_set_reg(apic, APIC_TMICT, 0);
1787 apic->lapic_timer.period = 0;
1788 apic->lapic_timer.tscdeadline = 0;
dedf9c5e 1789 }
b6ac0695 1790 apic->lapic_timer.timer_mode = timer_mode;
dedf9c5e 1791 limit_periodic_timer_frequency(apic);
b6ac0695
RK
1792 }
1793}
1794
d0659d94
MT
1795/*
1796 * On APICv, this test will cause a busy wait
1797 * during a higher-priority task.
1798 */
1799
1800static bool lapic_timer_int_injected(struct kvm_vcpu *vcpu)
1801{
1802 struct kvm_lapic *apic = vcpu->arch.apic;
14aecf2a 1803 u32 reg;
d0659d94 1804
14aecf2a
SC
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);
d0659d94
MT
1814 if (kvm_apic_hw_enabled(apic)) {
1815 int vec = reg & APIC_VECTOR_MASK;
f9339860 1816 void *bitmap = apic->regs + APIC_ISR;
d0659d94 1817
ce0a58f4 1818 if (apic->apicv_active)
f9339860
MT
1819 bitmap = apic->regs + APIC_IRR;
1820
1821 if (apic_test_vector(vec, bitmap))
1822 return true;
d0659d94
MT
1823 }
1824 return false;
1825}
1826
b6aa57c6
SC
1827static 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 */
938c8745 1837 if (vcpu->arch.tsc_scaling_ratio == kvm_caps.default_tsc_scaling_ratio) {
b6aa57c6
SC
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
84ea3aca 1847static inline void adjust_lapic_timer_advance(struct kvm_vcpu *vcpu,
ec0671d5 1848 s64 advance_expire_delta)
d0659d94
MT
1849{
1850 struct kvm_lapic *apic = vcpu->arch.apic;
39497d76 1851 u32 timer_advance_ns = apic->lapic_timer.timer_advance_ns;
84ea3aca
WL
1852 u64 ns;
1853
d0f5a86a
WL
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
84ea3aca 1859 /* too early */
ec0671d5
WL
1860 if (advance_expire_delta < 0) {
1861 ns = -advance_expire_delta * 1000000ULL;
84ea3aca 1862 do_div(ns, vcpu->arch.virtual_tsc_khz);
d0f5a86a 1863 timer_advance_ns -= ns/LAPIC_TIMER_ADVANCE_ADJUST_STEP;
84ea3aca
WL
1864 } else {
1865 /* too late */
ec0671d5 1866 ns = advance_expire_delta * 1000000ULL;
84ea3aca 1867 do_div(ns, vcpu->arch.virtual_tsc_khz);
d0f5a86a 1868 timer_advance_ns += ns/LAPIC_TIMER_ADVANCE_ADJUST_STEP;
84ea3aca
WL
1869 }
1870
a0f0037e
WL
1871 if (unlikely(timer_advance_ns > LAPIC_TIMER_ADVANCE_NS_MAX))
1872 timer_advance_ns = LAPIC_TIMER_ADVANCE_NS_INIT;
84ea3aca
WL
1873 apic->lapic_timer.timer_advance_ns = timer_advance_ns;
1874}
1875
0c5f81da 1876static void __kvm_wait_lapic_expire(struct kvm_vcpu *vcpu)
84ea3aca
WL
1877{
1878 struct kvm_lapic *apic = vcpu->arch.apic;
1879 u64 guest_tsc, tsc_deadline;
d0659d94 1880
d0659d94
MT
1881 tsc_deadline = apic->lapic_timer.expired_tscdeadline;
1882 apic->lapic_timer.expired_tscdeadline = 0;
4ba76538 1883 guest_tsc = kvm_read_l1_tsc(vcpu, rdtsc());
e0ac5351 1884 trace_kvm_wait_lapic_expire(vcpu->vcpu_id, guest_tsc - tsc_deadline);
d0659d94 1885
89a58812
SC
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());
9805cf03 1894
d0659d94 1895 if (guest_tsc < tsc_deadline)
b6aa57c6 1896 __wait_lapic_expire(vcpu, tsc_deadline - guest_tsc);
5d87db71 1897}
0c5f81da
WL
1898
1899void kvm_wait_lapic_expire(struct kvm_vcpu *vcpu)
1900{
010fd37f
WL
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))
0c5f81da
WL
1905 __kvm_wait_lapic_expire(vcpu);
1906}
b6c4bc65 1907EXPORT_SYMBOL_GPL(kvm_wait_lapic_expire);
5d87db71 1908
0c5f81da
WL
1909static 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);
17ac43a8 1914 if (apic_lvtt_tscdeadline(apic)) {
0c5f81da 1915 ktimer->tscdeadline = 0;
17ac43a8 1916 } else if (apic_lvtt_oneshot(apic)) {
0c5f81da
WL
1917 ktimer->tscdeadline = 0;
1918 ktimer->target_expiration = 0;
1919 }
1920}
1921
ae95f566 1922static void apic_timer_expired(struct kvm_lapic *apic, bool from_timer_fn)
0c5f81da
WL
1923{
1924 struct kvm_vcpu *vcpu = apic->vcpu;
0c5f81da
WL
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
ce0a58f4 1933 if (!from_timer_fn && apic->apicv_active) {
ae95f566
WL
1934 WARN_ON(kvm_get_running_vcpu() != vcpu);
1935 kvm_apic_inject_pending_timer_irqs(apic);
1936 return;
1937 }
1938
0c5f81da 1939 if (kvm_use_posted_timer_interrupt(apic->vcpu)) {
beda4301
SC
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);
0c5f81da
WL
1950 kvm_apic_inject_pending_timer_irqs(apic);
1951 return;
1952 }
1953
1954 atomic_inc(&apic->lapic_timer.pending);
084071d5 1955 kvm_make_request(KVM_REQ_UNBLOCK, vcpu);
68ca7663
WL
1956 if (from_timer_fn)
1957 kvm_vcpu_kick(vcpu);
0c5f81da
WL
1958}
1959
53f9eedf
YJ
1960static void start_sw_tscdeadline(struct kvm_lapic *apic)
1961{
39497d76
SC
1962 struct kvm_timer *ktimer = &apic->lapic_timer;
1963 u64 guest_tsc, tscdeadline = ktimer->tscdeadline;
53f9eedf
YJ
1964 u64 ns = 0;
1965 ktime_t expire;
1966 struct kvm_vcpu *vcpu = apic->vcpu;
1448d4a9 1967 u32 this_tsc_khz = vcpu->arch.virtual_tsc_khz;
53f9eedf
YJ
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
5587859f 1976 now = ktime_get();
53f9eedf 1977 guest_tsc = kvm_read_l1_tsc(vcpu, rdtsc());
c09d65d9
LA
1978
1979 ns = (tscdeadline - guest_tsc) * 1000000ULL;
1980 do_div(ns, this_tsc_khz);
1981
1982 if (likely(tscdeadline > guest_tsc) &&
39497d76 1983 likely(ns > apic->lapic_timer.timer_advance_ns)) {
53f9eedf 1984 expire = ktime_add_ns(now, ns);
39497d76 1985 expire = ktime_sub_ns(expire, ktimer->timer_advance_ns);
2c0d278f 1986 hrtimer_start(&ktimer->timer, expire, HRTIMER_MODE_ABS_HARD);
53f9eedf 1987 } else
ae95f566 1988 apic_timer_expired(apic, false);
53f9eedf
YJ
1989
1990 local_irq_restore(flags);
1991}
1992
24647e0a
PS
1993static inline u64 tmict_to_ns(struct kvm_lapic *apic, u32 tmict)
1994{
b460256b
IY
1995 return (u64)tmict * apic->vcpu->kvm->arch.apic_bus_cycle_ns *
1996 (u64)apic->divide_count;
24647e0a
PS
1997}
1998
c301b909
WL
1999static 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
24647e0a
PS
2004 apic->lapic_timer.period =
2005 tmict_to_ns(apic, kvm_lapic_get_reg(apic, APIC_TMICT));
c301b909
WL
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
24647e0a 2023static bool set_target_expiration(struct kvm_lapic *apic, u32 count_reg)
7d7f7da2
WL
2024{
2025 ktime_t now;
8003c9ae 2026 u64 tscl = rdtsc();
24647e0a 2027 s64 deadline;
7d7f7da2 2028
5587859f 2029 now = ktime_get();
24647e0a
PS
2030 apic->lapic_timer.period =
2031 tmict_to_ns(apic, kvm_lapic_get_reg(apic, APIC_TMICT));
7d7f7da2 2032
5d74a699
RK
2033 if (!apic->lapic_timer.period) {
2034 apic->lapic_timer.tscdeadline = 0;
8003c9ae 2035 return false;
7d7f7da2
WL
2036 }
2037
ccbfa1d3 2038 limit_periodic_timer_frequency(apic);
24647e0a
PS
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));
8e6ed96c
LR
2045 if (unlikely(deadline <= 0)) {
2046 if (apic_lvtt_period(apic))
2047 deadline = apic->lapic_timer.period;
2048 else
2049 deadline = 0;
2050 }
24647e0a
PS
2051 else if (unlikely(deadline > apic->lapic_timer.period)) {
2052 pr_info_ratelimited(
8d20bd63 2053 "vcpu %i: requested lapic timer restore with "
24647e0a
PS
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 }
7d7f7da2 2065
8003c9ae 2066 apic->lapic_timer.tscdeadline = kvm_read_l1_tsc(apic->vcpu, tscl) +
24647e0a
PS
2067 nsec_to_cycles(apic->vcpu, deadline);
2068 apic->lapic_timer.target_expiration = ktime_add_ns(now, deadline);
8003c9ae
WL
2069
2070 return true;
2071}
2072
2073static void advance_periodic_target_expiration(struct kvm_lapic *apic)
2074{
d8f2f498
DV
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 */
8003c9ae
WL
2086 apic->lapic_timer.target_expiration =
2087 ktime_add_ns(apic->lapic_timer.target_expiration,
2088 apic->lapic_timer.period);
d8f2f498
DV
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);
7d7f7da2
WL
2092}
2093
ecf08dad
AB
2094static 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)) {
ae95f566 2101 apic_timer_expired(apic, false);
ecf08dad
AB
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,
edec6e01 2111 HRTIMER_MODE_ABS_HARD);
ecf08dad
AB
2112}
2113
ce7a058a
YJ
2114bool kvm_lapic_hv_timer_in_use(struct kvm_vcpu *vcpu)
2115{
91005300
WL
2116 if (!lapic_in_kernel(vcpu))
2117 return false;
2118
ce7a058a
YJ
2119 return vcpu->arch.apic->lapic_timer.hv_timer_in_use;
2120}
ce7a058a 2121
7e810a38 2122static void cancel_hv_timer(struct kvm_lapic *apic)
bd97ad0e 2123{
1d518c68 2124 WARN_ON(preemptible());
a749e247 2125 WARN_ON(!apic->lapic_timer.hv_timer_in_use);
89604647 2126 kvm_x86_call(cancel_hv_timer)(apic->vcpu);
bd97ad0e
WL
2127 apic->lapic_timer.hv_timer_in_use = false;
2128}
2129
a749e247 2130static bool start_hv_timer(struct kvm_lapic *apic)
196f20ca 2131{
35ee9e48 2132 struct kvm_timer *ktimer = &apic->lapic_timer;
f9927982
SC
2133 struct kvm_vcpu *vcpu = apic->vcpu;
2134 bool expired;
196f20ca 2135
1d518c68 2136 WARN_ON(preemptible());
199a8b84 2137 if (!kvm_can_use_hv_timer(vcpu))
a749e247
PB
2138 return false;
2139
86bbc1e6
RK
2140 if (!ktimer->tscdeadline)
2141 return false;
2142
89604647 2143 if (kvm_x86_call(set_hv_timer)(vcpu, ktimer->tscdeadline, &expired))
35ee9e48
PB
2144 return false;
2145
2146 ktimer->hv_timer_in_use = true;
2147 hrtimer_cancel(&ktimer->timer);
196f20ca 2148
35ee9e48 2149 /*
f1ba5cfb
SC
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.
35ee9e48 2153 */
f1ba5cfb
SC
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);
f9927982 2161 } else if (expired) {
ae95f566 2162 apic_timer_expired(apic, false);
f1ba5cfb
SC
2163 cancel_hv_timer(apic);
2164 }
c8533544 2165 }
a749e247 2166
f9927982 2167 trace_kvm_hv_timer_state(vcpu->vcpu_id, ktimer->hv_timer_in_use);
f1ba5cfb 2168
35ee9e48
PB
2169 return true;
2170}
2171
a749e247 2172static void start_sw_timer(struct kvm_lapic *apic)
35ee9e48 2173{
a749e247 2174 struct kvm_timer *ktimer = &apic->lapic_timer;
1d518c68
WL
2175
2176 WARN_ON(preemptible());
a749e247
PB
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}
35ee9e48 2188
a749e247
PB
2189static void restart_apic_timer(struct kvm_lapic *apic)
2190{
1d518c68 2191 preempt_disable();
4ca88b3f
SC
2192
2193 if (!apic_lvtt_period(apic) && atomic_read(&apic->lapic_timer.pending))
2194 goto out;
2195
a749e247
PB
2196 if (!start_hv_timer(apic))
2197 start_sw_timer(apic);
4ca88b3f 2198out:
1d518c68 2199 preempt_enable();
196f20ca
WL
2200}
2201
8003c9ae
WL
2202void kvm_lapic_expired_hv_timer(struct kvm_vcpu *vcpu)
2203{
2204 struct kvm_lapic *apic = vcpu->arch.apic;
2205
1d518c68
WL
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;
d92a5d1c 2210 WARN_ON(kvm_vcpu_is_blocking(vcpu));
ae95f566 2211 apic_timer_expired(apic, false);
d981dd15 2212 cancel_hv_timer(apic);
8003c9ae
WL
2213
2214 if (apic_lvtt_period(apic) && apic->lapic_timer.period) {
2215 advance_periodic_target_expiration(apic);
a749e247 2216 restart_apic_timer(apic);
8003c9ae 2217 }
1d518c68
WL
2218out:
2219 preempt_enable();
8003c9ae
WL
2220}
2221EXPORT_SYMBOL_GPL(kvm_lapic_expired_hv_timer);
2222
ce7a058a
YJ
2223void kvm_lapic_switch_to_hv_timer(struct kvm_vcpu *vcpu)
2224{
a749e247 2225 restart_apic_timer(vcpu->arch.apic);
ce7a058a 2226}
ce7a058a
YJ
2227
2228void kvm_lapic_switch_to_sw_timer(struct kvm_vcpu *vcpu)
2229{
2230 struct kvm_lapic *apic = vcpu->arch.apic;
2231
1d518c68 2232 preempt_disable();
ce7a058a 2233 /* Possibly the TSC deadline timer is not enabled yet */
a749e247
PB
2234 if (apic->lapic_timer.hv_timer_in_use)
2235 start_sw_timer(apic);
1d518c68 2236 preempt_enable();
a749e247 2237}
ce7a058a 2238
a749e247
PB
2239void kvm_lapic_restart_hv_timer(struct kvm_vcpu *vcpu)
2240{
2241 struct kvm_lapic *apic = vcpu->arch.apic;
ce7a058a 2242
a749e247
PB
2243 WARN_ON(!apic->lapic_timer.hv_timer_in_use);
2244 restart_apic_timer(apic);
ce7a058a 2245}
ce7a058a 2246
24647e0a 2247static void __start_apic_timer(struct kvm_lapic *apic, u32 count_reg)
97222cc8 2248{
d3c7b77d 2249 atomic_set(&apic->lapic_timer.pending, 0);
0b975a3c 2250
a749e247 2251 if ((apic_lvtt_period(apic) || apic_lvtt_oneshot(apic))
24647e0a 2252 && !set_target_expiration(apic, count_reg))
a749e247
PB
2253 return;
2254
2255 restart_apic_timer(apic);
97222cc8
ED
2256}
2257
24647e0a
PS
2258static void start_apic_timer(struct kvm_lapic *apic)
2259{
2260 __start_apic_timer(apic, APIC_TMICT);
2261}
2262
cc6e462c
JK
2263static void apic_manage_nmi_watchdog(struct kvm_lapic *apic, u32 lvt0_val)
2264{
59fd1323 2265 bool lvt0_in_nmi_mode = apic_lvt_nmi_mode(lvt0_val);
cc6e462c 2266
59fd1323
RK
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) {
42720138 2270 atomic_inc(&apic->vcpu->kvm->arch.vapics_in_nmi_mode);
59fd1323
RK
2271 } else
2272 atomic_dec(&apic->vcpu->kvm->arch.vapics_in_nmi_mode);
2273 }
cc6e462c
JK
2274}
2275
4b903561
JW
2276static 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
70180052 2286static int kvm_lapic_reg_write(struct kvm_lapic *apic, u32 reg, u32 val)
97222cc8 2287{
0105d1a5 2288 int ret = 0;
97222cc8 2289
0105d1a5 2290 trace_kvm_apic_write(reg, val);
97222cc8 2291
0105d1a5 2292 switch (reg) {
97222cc8 2293 case APIC_ID: /* Local APIC ID */
3743c2f0 2294 if (!apic_x2apic_mode(apic)) {
a92e2543 2295 kvm_apic_set_xapic_id(apic, val >> 24);
3743c2f0 2296 } else {
0105d1a5 2297 ret = 1;
3743c2f0 2298 }
97222cc8
ED
2299 break;
2300
2301 case APIC_TASKPRI:
b209749f 2302 report_tpr_access(apic, true);
97222cc8
ED
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:
0105d1a5 2311 if (!apic_x2apic_mode(apic))
1e08ec4a 2312 kvm_apic_set_ldr(apic, val & APIC_LDR_MASK);
0105d1a5
GN
2313 else
2314 ret = 1;
97222cc8
ED
2315 break;
2316
2317 case APIC_DFR:
ae6f2496
WL
2318 if (!apic_x2apic_mode(apic))
2319 kvm_apic_set_dfr(apic, val | 0x0FFFFFFF);
2320 else
0105d1a5 2321 ret = 1;
97222cc8
ED
2322 break;
2323
fc61b800
GN
2324 case APIC_SPIV: {
2325 u32 mask = 0x3ff;
dfb95954 2326 if (kvm_lapic_get_reg(apic, APIC_LVR) & APIC_LVR_DIRECTED_EOI)
fc61b800 2327 mask |= APIC_SPIV_DIRECTED_EOI;
f8c1ea10 2328 apic_set_spiv(apic, val & mask);
97222cc8
ED
2329 if (!(val & APIC_SPIV_APIC_ENABLED)) {
2330 int i;
97222cc8 2331
4b903561 2332 for (i = 0; i < apic->nr_lvt_entries; i++) {
987f625e 2333 kvm_lapic_set_reg(apic, APIC_LVTx(i),
4b903561 2334 kvm_lapic_get_reg(apic, APIC_LVTx(i)) | APIC_LVT_MASKED);
97222cc8 2335 }
b6ac0695 2336 apic_update_lvtt(apic);
d3c7b77d 2337 atomic_set(&apic->lapic_timer.pending, 0);
97222cc8
ED
2338
2339 }
2340 break;
fc61b800 2341 }
97222cc8 2342 case APIC_ICR:
a57a3168
SC
2343 WARN_ON_ONCE(apic_x2apic_mode(apic));
2344
97222cc8 2345 /* No delay here, so we always clear the pending bit */
bd17f417 2346 val &= ~APIC_ICR_BUSY;
d5361678 2347 kvm_apic_send_ipi(apic, val, kvm_lapic_get_reg(apic, APIC_ICR2));
2b0911d1 2348 kvm_lapic_set_reg(apic, APIC_ICR, val);
97222cc8 2349 break;
97222cc8 2350 case APIC_ICR2:
a57a3168
SC
2351 if (apic_x2apic_mode(apic))
2352 ret = 1;
2353 else
2354 kvm_lapic_set_reg(apic, APIC_ICR2, val & 0xff000000);
97222cc8
ED
2355 break;
2356
23930f95 2357 case APIC_LVT0:
cc6e462c 2358 apic_manage_nmi_watchdog(apic, val);
df561f66 2359 fallthrough;
97222cc8
ED
2360 case APIC_LVTTHMR:
2361 case APIC_LVTPC:
97222cc8 2362 case APIC_LVT1:
4b903561
JW
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 }
c48f1496 2370 if (!kvm_apic_sw_enabled(apic))
97222cc8 2371 val |= APIC_LVT_MASKED;
4bf79cb0 2372 val &= apic_lvt_mask[index];
1e6e2755 2373 kvm_lapic_set_reg(apic, reg, val);
97222cc8 2374 break;
4bf79cb0 2375 }
97222cc8 2376
b6ac0695 2377 case APIC_LVTT:
c48f1496 2378 if (!kvm_apic_sw_enabled(apic))
a3e06bbe 2379 val |= APIC_LVT_MASKED;
d6470627 2380 val &= (apic_lvt_mask[LVT_TIMER] | apic->lapic_timer.timer_mode_mask);
1e6e2755 2381 kvm_lapic_set_reg(apic, APIC_LVTT, val);
b6ac0695 2382 apic_update_lvtt(apic);
a3e06bbe
LJ
2383 break;
2384
97222cc8 2385 case APIC_TMICT:
a3e06bbe
LJ
2386 if (apic_lvtt_tscdeadline(apic))
2387 break;
2388
e898da78 2389 cancel_apic_timer(apic);
1e6e2755 2390 kvm_lapic_set_reg(apic, APIC_TMICT, val);
97222cc8 2391 start_apic_timer(apic);
0105d1a5 2392 break;
97222cc8 2393
c301b909
WL
2394 case APIC_TDCR: {
2395 uint32_t old_divisor = apic->divide_count;
2396
a445fc45 2397 kvm_lapic_set_reg(apic, APIC_TDCR, val & 0xb);
97222cc8 2398 update_divide_count(apic);
c301b909
WL
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 }
97222cc8 2405 break;
c301b909 2406 }
0105d1a5 2407 case APIC_ESR:
0d88800d 2408 if (apic_x2apic_mode(apic) && val != 0)
0105d1a5 2409 ret = 1;
0105d1a5
GN
2410 break;
2411
2412 case APIC_SELF_IPI:
ba5838ab
SC
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))
0105d1a5 2418 ret = 1;
ba5838ab
SC
2419 else
2420 kvm_apic_send_ipi(apic, APIC_DEST_SELF | val, 0);
0105d1a5 2421 break;
97222cc8 2422 default:
0105d1a5 2423 ret = 1;
97222cc8
ED
2424 break;
2425 }
0d88800d 2426
bd17f417
SC
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 */
4abaffce
WL
2432 kvm_recalculate_apic_map(apic->vcpu->kvm);
2433
0105d1a5
GN
2434 return ret;
2435}
2436
e32edf4f 2437static int apic_mmio_write(struct kvm_vcpu *vcpu, struct kvm_io_device *this,
0105d1a5
GN
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
d1766202
VK
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
0105d1a5
GN
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 */
0d88800d 2460 if (len != 4 || (offset & 0xf))
756975bb 2461 return 0;
0105d1a5
GN
2462
2463 val = *(u32*)data;
2464
0d88800d 2465 kvm_lapic_reg_write(apic, offset & 0xff0, val);
0105d1a5 2466
bda9020e 2467 return 0;
97222cc8
ED
2468}
2469
58fbbf26
KT
2470void kvm_lapic_set_eoi(struct kvm_vcpu *vcpu)
2471{
1e6e2755 2472 kvm_lapic_reg_write(vcpu->arch.apic, APIC_EOI, 0);
58fbbf26
KT
2473}
2474EXPORT_SYMBOL_GPL(kvm_lapic_set_eoi);
2475
d3323434
SC
2476#define X2APIC_ICR_RESERVED_BITS (GENMASK_ULL(31, 20) | GENMASK_ULL(17, 16) | BIT(13))
2477
2478int 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));
73b42dc6
SC
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 }
d3323434
SC
2500 trace_kvm_apic_write(APIC_ICR, data);
2501 return 0;
2502}
2503
73b42dc6
SC
2504static 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
83d4c286
YZ
2513/* emulate APIC access in a trap manner */
2514void kvm_apic_write_nodecode(struct kvm_vcpu *vcpu, u32 offset)
2515{
5413bcba 2516 struct kvm_lapic *apic = vcpu->arch.apic;
5413bcba 2517
1bd9dfec 2518 /*
629d3698
TS
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.
1bd9dfec 2528 */
629d3698 2529 if (apic_x2apic_mode(apic) && offset == APIC_ICR)
73b42dc6 2530 WARN_ON_ONCE(kvm_x2apic_icr_write(apic, kvm_x2apic_icr_read(apic)));
629d3698
TS
2531 else
2532 kvm_lapic_reg_write(apic, offset, kvm_lapic_get_reg(apic, offset));
83d4c286
YZ
2533}
2534EXPORT_SYMBOL_GPL(kvm_apic_write_nodecode);
2535
d589444e 2536void kvm_free_lapic(struct kvm_vcpu *vcpu)
97222cc8 2537{
f8c1ea10
GN
2538 struct kvm_lapic *apic = vcpu->arch.apic;
2539
a78d9046
SC
2540 if (!vcpu->arch.apic) {
2541 static_branch_dec(&kvm_has_noapic_vcpu);
97222cc8 2542 return;
a78d9046 2543 }
97222cc8 2544
f8c1ea10 2545 hrtimer_cancel(&apic->lapic_timer.timer);
97222cc8 2546
c5cc421b 2547 if (!(vcpu->arch.apic_base & MSR_IA32_APICBASE_ENABLE))
6e4e3b4d 2548 static_branch_slow_dec_deferred(&apic_hw_disabled);
c5cc421b 2549
e462755c 2550 if (!apic->sw_enabled)
6e4e3b4d 2551 static_branch_slow_dec_deferred(&apic_sw_disabled);
97222cc8 2552
f8c1ea10
GN
2553 if (apic->regs)
2554 free_page((unsigned long)apic->regs);
2555
2556 kfree(apic);
97222cc8
ED
2557}
2558
2559/*
2560 *----------------------------------------------------------------------
2561 * LAPIC interface
2562 *----------------------------------------------------------------------
2563 */
a3e06bbe
LJ
2564u64 kvm_get_lapic_tscdeadline_msr(struct kvm_vcpu *vcpu)
2565{
2566 struct kvm_lapic *apic = vcpu->arch.apic;
a3e06bbe 2567
a970e9b2 2568 if (!kvm_apic_present(vcpu) || !apic_lvtt_tscdeadline(apic))
a3e06bbe
LJ
2569 return 0;
2570
2571 return apic->lapic_timer.tscdeadline;
2572}
2573
2574void kvm_set_lapic_tscdeadline_msr(struct kvm_vcpu *vcpu, u64 data)
2575{
2576 struct kvm_lapic *apic = vcpu->arch.apic;
a3e06bbe 2577
27503833 2578 if (!kvm_apic_present(vcpu) || !apic_lvtt_tscdeadline(apic))
a3e06bbe
LJ
2579 return;
2580
2581 hrtimer_cancel(&apic->lapic_timer.timer);
2582 apic->lapic_timer.tscdeadline = data;
2583 start_apic_timer(apic);
2584}
2585
97222cc8
ED
2586void kvm_lapic_set_tpr(struct kvm_vcpu *vcpu, unsigned long cr8)
2587{
f66af9f2 2588 apic_set_tpr(vcpu->arch.apic, (cr8 & 0x0f) << 4);
97222cc8
ED
2589}
2590
2591u64 kvm_lapic_get_cr8(struct kvm_vcpu *vcpu)
2592{
97222cc8
ED
2593 u64 tpr;
2594
dfb95954 2595 tpr = (u64) kvm_lapic_get_reg(vcpu->arch.apic, APIC_TASKPRI);
97222cc8
ED
2596
2597 return (tpr & 0xf0) >> 4;
2598}
2599
7d1cb7ce 2600static void __kvm_apic_set_base(struct kvm_vcpu *vcpu, u64 value)
97222cc8 2601{
8d14695f 2602 u64 old_value = vcpu->arch.apic_base;
ad312c7c 2603 struct kvm_lapic *apic = vcpu->arch.apic;
97222cc8 2604
e66d2ae7
JK
2605 vcpu->arch.apic_base = value;
2606
c7dd15b3 2607 if ((old_value ^ value) & MSR_IA32_APICBASE_ENABLE)
93da6af3 2608 vcpu->arch.cpuid_dynamic_bits_dirty = true;
c7dd15b3
JM
2609
2610 if (!apic)
2611 return;
2612
c5cc421b 2613 /* update jump label if enable bit changes */
0dce7cd6 2614 if ((old_value ^ value) & MSR_IA32_APICBASE_ENABLE) {
49bd29ba
RK
2615 if (value & MSR_IA32_APICBASE_ENABLE) {
2616 kvm_apic_set_xapic_id(apic, vcpu->vcpu_id);
6e4e3b4d 2617 static_branch_slow_dec_deferred(&apic_hw_disabled);
2f15d027
VK
2618 /* Check if there are APF page ready requests pending */
2619 kvm_make_request(KVM_REQ_APF_READY, vcpu);
187ca84b 2620 } else {
6e4e3b4d 2621 static_branch_inc(&apic_hw_disabled.key);
44d52717 2622 atomic_set_release(&apic->vcpu->kvm->arch.apic_map_dirty, DIRTY);
187ca84b 2623 }
c5cc421b
GN
2624 }
2625
052c3b99
EGE
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 }
8d860bbe 2632
8fc9c7a3 2633 if ((old_value ^ value) & (MSR_IA32_APICBASE_ENABLE | X2APIC_ENABLE)) {
1459f5c6 2634 kvm_make_request(KVM_REQ_APICV_UPDATE, vcpu);
89604647 2635 kvm_x86_call(set_virtual_apic_mode)(vcpu);
8fc9c7a3 2636 }
8d14695f 2637
ad312c7c 2638 apic->base_address = apic->vcpu->arch.apic_base &
97222cc8
ED
2639 MSR_IA32_APICBASE_BASE;
2640
db324fe6 2641 if ((value & MSR_IA32_APICBASE_ENABLE) &&
3743c2f0
ML
2642 apic->base_address != APIC_DEFAULT_PHYS_BASE) {
2643 kvm_set_apicv_inhibit(apic->vcpu->kvm,
2644 APICV_INHIBIT_REASON_APIC_BASE_MODIFIED);
2645 }
97222cc8
ED
2646}
2647
c9155eb0 2648int kvm_apic_set_base(struct kvm_vcpu *vcpu, u64 value, bool host_initiated)
c9c9acfc
SC
2649{
2650 enum lapic_mode old_mode = kvm_get_apic_mode(vcpu);
c9155eb0 2651 enum lapic_mode new_mode = kvm_apic_mode(value);
a75b7bb4
SC
2652
2653 if (vcpu->arch.apic_base == value)
2654 return 0;
2655
c9c9acfc 2656 u64 reserved_bits = kvm_vcpu_reserved_gpa_bits_raw(vcpu) | 0x2ff |
8f2a2775 2657 (guest_cpu_cap_has(vcpu, X86_FEATURE_X2APIC) ? 0 : X2APIC_ENABLE);
c9c9acfc 2658
c9155eb0 2659 if ((value & reserved_bits) != 0 || new_mode == LAPIC_MODE_INVALID)
c9c9acfc 2660 return 1;
c9155eb0 2661 if (!host_initiated) {
c9c9acfc
SC
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
c9155eb0 2668 __kvm_apic_set_base(vcpu, value);
c9c9acfc
SC
2669 kvm_recalculate_apic_map(vcpu->kvm);
2670 return 0;
2671}
a50f673f 2672EXPORT_SYMBOL_GPL(kvm_apic_set_base);
c9c9acfc 2673
b26a695a
SS
2674void kvm_apic_update_apicv(struct kvm_vcpu *vcpu)
2675{
2676 struct kvm_lapic *apic = vcpu->arch.apic;
2677
d3ddef46
SC
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)
b26a695a 2694 apic->isr_count = 1;
d3ddef46 2695 else
b26a695a 2696 apic->isr_count = count_vectors(apic->regs + APIC_ISR);
d3ddef46 2697
97a71c44 2698 apic->highest_isr_cache = -1;
b26a695a 2699}
b26a695a 2700
c482f2ce
SC
2701int kvm_alloc_apic_access_page(struct kvm *kvm)
2702{
c482f2ce
SC
2703 void __user *hva;
2704 int ret = 0;
2705
2706 mutex_lock(&kvm->slots_lock);
2008fab3
SC
2707 if (kvm->arch.apic_access_memslot_enabled ||
2708 kvm->arch.apic_access_memslot_inhibited)
c482f2ce
SC
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
c482f2ce
SC
2718 kvm->arch.apic_access_memslot_enabled = true;
2719out:
2720 mutex_unlock(&kvm->slots_lock);
2721 return ret;
2722}
2723EXPORT_SYMBOL_GPL(kvm_alloc_apic_access_page);
2724
2008fab3
SC
2725void 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);
b26a695a 2758}
b26a695a 2759
d28bc9dd 2760void kvm_lapic_reset(struct kvm_vcpu *vcpu, bool init_event)
97222cc8 2761{
b7e31be3 2762 struct kvm_lapic *apic = vcpu->arch.apic;
f7d8a19f 2763 u64 msr_val;
97222cc8
ED
2764 int i;
2765
89604647 2766 kvm_x86_call(apicv_pre_state_restore)(vcpu);
9cfec6d0 2767
4547700a 2768 if (!init_event) {
f7d8a19f 2769 msr_val = APIC_DEFAULT_PHYS_BASE | MSR_IA32_APICBASE_ENABLE;
4547700a 2770 if (kvm_vcpu_is_reset_bsp(vcpu))
f7d8a19f 2771 msr_val |= MSR_IA32_APICBASE_BSP;
7d1cb7ce
SC
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);
4547700a
SC
2780 }
2781
b7e31be3
RK
2782 if (!apic)
2783 return;
97222cc8 2784
97222cc8 2785 /* Stop the timer in case it's a reset to an active apic */
d3c7b77d 2786 hrtimer_cancel(&apic->lapic_timer.timer);
97222cc8 2787
f7d8a19f
SC
2788 /* The xAPIC ID is set at RESET even if the APIC was already enabled. */
2789 if (!init_event)
a92e2543 2790 kvm_apic_set_xapic_id(apic, vcpu->vcpu_id);
fc61b800 2791 kvm_apic_set_version(apic->vcpu);
97222cc8 2792
4b903561 2793 for (i = 0; i < apic->nr_lvt_entries; i++)
987f625e 2794 kvm_lapic_set_reg(apic, APIC_LVTx(i), APIC_LVT_MASKED);
b6ac0695 2795 apic_update_lvtt(apic);
52b54190
JS
2796 if (kvm_vcpu_is_reset_bsp(vcpu) &&
2797 kvm_check_has_quirk(vcpu->kvm, KVM_X86_QUIRK_LINT0_REENABLED))
1e6e2755 2798 kvm_lapic_set_reg(apic, APIC_LVT0,
90de4a18 2799 SET_APIC_DELIVERY_MODE(0, APIC_MODE_EXTINT));
dfb95954 2800 apic_manage_nmi_watchdog(apic, kvm_lapic_get_reg(apic, APIC_LVT0));
97222cc8 2801
ae6f2496 2802 kvm_apic_set_dfr(apic, 0xffffffffU);
f8c1ea10 2803 apic_set_spiv(apic, 0xff);
1e6e2755 2804 kvm_lapic_set_reg(apic, APIC_TASKPRI, 0);
c028dd6b
RK
2805 if (!apic_x2apic_mode(apic))
2806 kvm_apic_set_ldr(apic, 0);
1e6e2755 2807 kvm_lapic_set_reg(apic, APIC_ESR, 0);
a57a3168
SC
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 }
1e6e2755
SS
2814 kvm_lapic_set_reg(apic, APIC_TDCR, 0);
2815 kvm_lapic_set_reg(apic, APIC_TMICT, 0);
97222cc8 2816 for (i = 0; i < 8; i++) {
1e6e2755
SS
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);
97222cc8 2820 }
b26a695a 2821 kvm_apic_update_apicv(vcpu);
b33ac88b 2822 update_divide_count(apic);
d3c7b77d 2823 atomic_set(&apic->lapic_timer.pending, 0);
549240e8 2824
ae7a2a3f 2825 vcpu->arch.pv_eoi.msr_val = 0;
97222cc8 2826 apic_update_ppr(apic);
ce0a58f4 2827 if (apic->apicv_active) {
89604647 2828 kvm_x86_call(apicv_post_state_restore)(vcpu);
76bce9f1 2829 kvm_x86_call(hwapic_isr_update)(vcpu, -1);
4191db26 2830 }
97222cc8 2831
e1035715 2832 vcpu->arch.apic_arb_prio = 0;
41383771 2833 vcpu->arch.apic_attention = 0;
4abaffce
WL
2834
2835 kvm_recalculate_apic_map(vcpu->kvm);
97222cc8
ED
2836}
2837
97222cc8
ED
2838/*
2839 *----------------------------------------------------------------------
2840 * timer interface
2841 *----------------------------------------------------------------------
2842 */
1b9778da 2843
2a6eac96 2844static bool lapic_is_periodic(struct kvm_lapic *apic)
97222cc8 2845{
d3c7b77d 2846 return apic_lvtt_period(apic);
97222cc8
ED
2847}
2848
3d80840d
MT
2849int apic_has_pending_timer(struct kvm_vcpu *vcpu)
2850{
54e9818f 2851 struct kvm_lapic *apic = vcpu->arch.apic;
3d80840d 2852
1e3161b4 2853 if (apic_enabled(apic) && apic_lvt_enabled(apic, APIC_LVTT))
54e9818f 2854 return atomic_read(&apic->lapic_timer.pending);
3d80840d
MT
2855
2856 return 0;
2857}
2858
89342082 2859int kvm_apic_local_deliver(struct kvm_lapic *apic, int lvt_type)
1b9778da 2860{
dfb95954 2861 u32 reg = kvm_lapic_get_reg(apic, lvt_type);
23930f95 2862 int vector, mode, trig_mode;
a16eb25b 2863 int r;
23930f95 2864
c48f1496 2865 if (kvm_apic_hw_enabled(apic) && !(reg & APIC_LVT_MASKED)) {
23930f95
JK
2866 vector = reg & APIC_VECTOR_MASK;
2867 mode = reg & APIC_MODE_MASK;
2868 trig_mode = reg & APIC_LVT_LEVEL_TRIGGER;
a16eb25b
JM
2869
2870 r = __apic_accept_irq(apic, mode, vector, 1, trig_mode, NULL);
49ff3b4a
SD
2871 if (r && lvt_type == APIC_LVTPC &&
2872 guest_cpuid_is_intel_compatible(apic->vcpu))
a16eb25b
JM
2873 kvm_lapic_set_reg(apic, APIC_LVTPC, reg | APIC_LVT_MASKED);
2874 return r;
23930f95
JK
2875 }
2876 return 0;
2877}
1b9778da 2878
8fdb2351 2879void kvm_apic_nmi_wd_deliver(struct kvm_vcpu *vcpu)
23930f95 2880{
8fdb2351
JK
2881 struct kvm_lapic *apic = vcpu->arch.apic;
2882
2883 if (apic)
2884 kvm_apic_local_deliver(apic, APIC_LVT0);
1b9778da
ED
2885}
2886
d76685c4
GH
2887static const struct kvm_io_device_ops apic_mmio_ops = {
2888 .read = apic_mmio_read,
2889 .write = apic_mmio_write,
d76685c4
GH
2890};
2891
e9d90d47
AK
2892static enum hrtimer_restart apic_timer_fn(struct hrtimer *data)
2893{
2894 struct kvm_timer *ktimer = container_of(data, struct kvm_timer, timer);
2a6eac96 2895 struct kvm_lapic *apic = container_of(ktimer, struct kvm_lapic, lapic_timer);
e9d90d47 2896
ae95f566 2897 apic_timer_expired(apic, true);
e9d90d47 2898
2a6eac96 2899 if (lapic_is_periodic(apic)) {
8003c9ae 2900 advance_periodic_target_expiration(apic);
e9d90d47
AK
2901 hrtimer_add_expires_ns(&ktimer->timer, ktimer->period);
2902 return HRTIMER_RESTART;
2903 } else
2904 return HRTIMER_NORESTART;
2905}
2906
89a58812 2907int kvm_create_lapic(struct kvm_vcpu *vcpu)
97222cc8
ED
2908{
2909 struct kvm_lapic *apic;
2910
2911 ASSERT(vcpu != NULL);
97222cc8 2912
a78d9046
SC
2913 if (!irqchip_in_kernel(vcpu->kvm)) {
2914 static_branch_inc(&kvm_has_noapic_vcpu);
2915 return 0;
2916 }
2917
254272ce 2918 apic = kzalloc(sizeof(*apic), GFP_KERNEL_ACCOUNT);
97222cc8
ED
2919 if (!apic)
2920 goto nomem;
2921
ad312c7c 2922 vcpu->arch.apic = apic;
97222cc8 2923
75253db4 2924 if (kvm_x86_ops.alloc_apic_backing_page)
89604647 2925 apic->regs = kvm_x86_call(alloc_apic_backing_page)(vcpu);
75253db4
BS
2926 else
2927 apic->regs = (void *)get_zeroed_page(GFP_KERNEL_ACCOUNT);
afc20184 2928 if (!apic->regs) {
97222cc8
ED
2929 printk(KERN_ERR "malloc apic regs error for vcpu %x\n",
2930 vcpu->vcpu_id);
d589444e 2931 goto nomem_free_apic;
97222cc8 2932 }
97222cc8
ED
2933 apic->vcpu = vcpu;
2934
03d84f96
SC
2935 apic->nr_lvt_entries = kvm_apic_calc_nr_lvt_entries(vcpu);
2936
7764b9dd
NC
2937 hrtimer_setup(&apic->lapic_timer.timer, apic_timer_fn, CLOCK_MONOTONIC,
2938 HRTIMER_MODE_ABS_HARD);
89a58812 2939 if (lapic_timer_advance)
a0f0037e 2940 apic->lapic_timer.timer_advance_ns = LAPIC_TIMER_ADVANCE_NS_INIT;
c3941d9e 2941
f7d8a19f
SC
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;
6e4e3b4d 2947 static_branch_inc(&apic_sw_disabled.key); /* sw disabled at reset */
d76685c4 2948 kvm_iodevice_init(&apic->dev, &apic_mmio_ops);
97222cc8 2949
a78d9046
SC
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
97222cc8 2965 return 0;
d589444e
RR
2966nomem_free_apic:
2967 kfree(apic);
a251fb90 2968 vcpu->arch.apic = NULL;
97222cc8 2969nomem:
97222cc8
ED
2970 return -ENOMEM;
2971}
97222cc8
ED
2972
2973int kvm_apic_has_interrupt(struct kvm_vcpu *vcpu)
2974{
ad312c7c 2975 struct kvm_lapic *apic = vcpu->arch.apic;
b3c045d3 2976 u32 ppr;
97222cc8 2977
72c3bcdc 2978 if (!kvm_apic_present(vcpu))
97222cc8
ED
2979 return -1;
2980
90cfe144
SC
2981 if (apic->guest_apic_protected)
2982 return -1;
2983
b3c045d3
PB
2984 __apic_update_ppr(apic, &ppr);
2985 return apic_has_interrupt_for_ppr(apic, ppr);
97222cc8 2986}
25bb2cf9 2987EXPORT_SYMBOL_GPL(kvm_apic_has_interrupt);
97222cc8 2988
40487c68
QH
2989int kvm_apic_accept_pic_intr(struct kvm_vcpu *vcpu)
2990{
dfb95954 2991 u32 lvt0 = kvm_lapic_get_reg(vcpu->arch.apic, APIC_LVT0);
40487c68 2992
c48f1496 2993 if (!kvm_apic_hw_enabled(vcpu->arch.apic))
3ce4dc17 2994 return 1;
e7dca5c0
CL
2995 if ((lvt0 & APIC_LVT_MASKED) == 0 &&
2996 GET_APIC_DELIVERY_MODE(lvt0) == APIC_MODE_EXTINT)
3ce4dc17
ML
2997 return 1;
2998 return 0;
40487c68
QH
2999}
3000
1b9778da
ED
3001void kvm_inject_apic_timer_irqs(struct kvm_vcpu *vcpu)
3002{
ad312c7c 3003 struct kvm_lapic *apic = vcpu->arch.apic;
1b9778da 3004
54e9818f 3005 if (atomic_read(&apic->lapic_timer.pending) > 0) {
0c5f81da 3006 kvm_apic_inject_pending_timer_irqs(apic);
f1ed0450 3007 atomic_set(&apic->lapic_timer.pending, 0);
1b9778da
ED
3008 }
3009}
3010
a194a3a1 3011void kvm_apic_ack_interrupt(struct kvm_vcpu *vcpu, int vector)
97222cc8 3012{
ad312c7c 3013 struct kvm_lapic *apic = vcpu->arch.apic;
4d82d12b 3014 u32 ppr;
97222cc8 3015
a194a3a1
SC
3016 if (WARN_ON_ONCE(vector < 0 || !apic))
3017 return;
97222cc8 3018
56cc2406
WL
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
97222cc8 3026 apic_clear_irr(vector, apic);
16e880bf 3027 if (kvm_hv_synic_auto_eoi_set(vcpu, vector)) {
4d82d12b
PB
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 */
5c919412 3033 apic_update_ppr(apic);
4d82d12b
PB
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);
5c919412
AS
3043 }
3044
97222cc8 3045}
a194a3a1 3046EXPORT_SYMBOL_GPL(kvm_apic_ack_interrupt);
96ad2cc6 3047
a92e2543
RK
3048static 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)) {
4b7c3f6d 3052 u32 x2apic_id = kvm_x2apic_id(vcpu->arch.apic);
a92e2543 3053 u32 *id = (u32 *)(s->regs + APIC_ID);
12806ba9 3054 u32 *ldr = (u32 *)(s->regs + APIC_LDR);
a57a3168 3055 u64 icr;
a92e2543 3056
37131313 3057 if (vcpu->kvm->arch.x2apic_format) {
4b7c3f6d 3058 if (*id != x2apic_id)
37131313
RK
3059 return -EINVAL;
3060 } else {
4b7c3f6d
SC
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 */
37131313 3070 if (set)
4b7c3f6d 3071 *id = x2apic_id;
37131313 3072 else
4b7c3f6d 3073 *id = x2apic_id << 24;
37131313 3074 }
12806ba9 3075
a57a3168
SC
3076 /*
3077 * In x2APIC mode, the LDR is fixed and based on the id. And
73b42dc6
SC
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.
a57a3168 3081 */
73b42dc6 3082 if (set)
4b7c3f6d 3083 *ldr = kvm_apic_calc_x2apic_ldr(x2apic_id);
a57a3168 3084
73b42dc6
SC
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 }
a57a3168 3094 }
a92e2543
RK
3095 }
3096
3097 return 0;
3098}
3099
3100int kvm_apic_get_state(struct kvm_vcpu *vcpu, struct kvm_lapic_state *s)
3101{
3102 memcpy(s->regs, vcpu->arch.apic->regs, sizeof(*s));
24647e0a
PS
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
a92e2543
RK
3111 return kvm_apic_state_fixup(vcpu, s, false);
3112}
3113
3114int kvm_apic_set_state(struct kvm_vcpu *vcpu, struct kvm_lapic_state *s)
96ad2cc6 3115{
ad312c7c 3116 struct kvm_lapic *apic = vcpu->arch.apic;
a92e2543
RK
3117 int r;
3118
89604647 3119 kvm_x86_call(apicv_pre_state_restore)(vcpu);
9cfec6d0 3120
64eb0620
GN
3121 /* set SPIV separately to get count of SW disabled APICs right */
3122 apic_set_spiv(apic, *((u32 *)(s->regs + APIC_SPIV)));
a92e2543
RK
3123
3124 r = kvm_apic_state_fixup(vcpu, s, true);
4abaffce
WL
3125 if (r) {
3126 kvm_recalculate_apic_map(vcpu->kvm);
a92e2543 3127 return r;
4abaffce 3128 }
0e96f31e 3129 memcpy(vcpu->arch.apic->regs, s->regs, sizeof(*s));
a92e2543 3130
44d52717 3131 atomic_set_release(&apic->vcpu->kvm->arch.apic_map_dirty, DIRTY);
4abaffce 3132 kvm_recalculate_apic_map(vcpu->kvm);
fc61b800
GN
3133 kvm_apic_set_version(vcpu);
3134
96ad2cc6 3135 apic_update_ppr(apic);
35fe7cfb 3136 cancel_apic_timer(apic);
35737d2d 3137 apic->lapic_timer.expired_tscdeadline = 0;
b6ac0695 3138 apic_update_lvtt(apic);
dfb95954 3139 apic_manage_nmi_watchdog(apic, kvm_lapic_get_reg(apic, APIC_LVT0));
96ad2cc6 3140 update_divide_count(apic);
24647e0a 3141 __start_apic_timer(apic, APIC_TMCCT);
2735886c 3142 kvm_lapic_set_reg(apic, APIC_TMCCT, 0);
b26a695a 3143 kvm_apic_update_apicv(vcpu);
ce0a58f4 3144 if (apic->apicv_active) {
89604647 3145 kvm_x86_call(apicv_post_state_restore)(vcpu);
76bce9f1 3146 kvm_x86_call(hwapic_isr_update)(vcpu, apic_find_highest_isr(apic));
d62caabb 3147 }
3842d135 3148 kvm_make_request(KVM_REQ_EVENT, vcpu);
49df6397
SR
3149 if (ioapic_in_kernel(vcpu->kvm))
3150 kvm_rtc_eoi_tracking_restore_one(vcpu);
0669a510
RK
3151
3152 vcpu->arch.apic_arb_prio = 0;
a92e2543
RK
3153
3154 return 0;
96ad2cc6 3155}
a3d7f85f 3156
2f52d58c 3157void __kvm_migrate_apic_timer(struct kvm_vcpu *vcpu)
a3d7f85f 3158{
a3d7f85f
ED
3159 struct hrtimer *timer;
3160
0c5f81da
WL
3161 if (!lapic_in_kernel(vcpu) ||
3162 kvm_can_post_timer_interrupt(vcpu))
a3d7f85f
ED
3163 return;
3164
54e9818f 3165 timer = &vcpu->arch.apic->lapic_timer.timer;
a3d7f85f 3166 if (hrtimer_cancel(timer))
2c0d278f 3167 hrtimer_start_expires(timer, HRTIMER_MODE_ABS_HARD);
a3d7f85f 3168}
b93463aa 3169
ae7a2a3f
MT
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 */
3177static void apic_sync_pv_eoi_from_guest(struct kvm_vcpu *vcpu,
3178 struct kvm_lapic *apic)
3179{
ae7a2a3f
MT
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));
51b1209c
LR
3193
3194 if (pv_eoi_test_and_clr_pending(vcpu))
ae7a2a3f
MT
3195 return;
3196 vector = apic_set_eoi(apic);
3197 trace_kvm_pv_eoi(apic, vector);
3198}
3199
b93463aa
AK
3200void kvm_lapic_sync_from_vapic(struct kvm_vcpu *vcpu)
3201{
3202 u32 data;
b93463aa 3203
ae7a2a3f
MT
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
41383771 3207 if (!test_bit(KVM_APIC_CHECK_VAPIC, &vcpu->arch.apic_attention))
b93463aa
AK
3208 return;
3209
4e335d9e
PB
3210 if (kvm_read_guest_cached(vcpu->kvm, &vcpu->arch.apic->vapic_cache, &data,
3211 sizeof(u32)))
603242a8 3212 return;
b93463aa
AK
3213
3214 apic_set_tpr(vcpu->arch.apic, data & 0xff);
3215}
3216
ae7a2a3f
MT
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 */
3223static 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. */
3bb345f3 3232 kvm_ioapic_handles_vector(apic, apic->highest_isr_cache)) {
ae7a2a3f
MT
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
b93463aa
AK
3243void kvm_lapic_sync_to_vapic(struct kvm_vcpu *vcpu)
3244{
3245 u32 data, tpr;
3246 int max_irr, max_isr;
ae7a2a3f 3247 struct kvm_lapic *apic = vcpu->arch.apic;
b93463aa 3248
ae7a2a3f
MT
3249 apic_sync_pv_eoi_to_guest(vcpu, apic);
3250
41383771 3251 if (!test_bit(KVM_APIC_CHECK_VAPIC, &vcpu->arch.apic_attention))
b93463aa
AK
3252 return;
3253
dfb95954 3254 tpr = kvm_lapic_get_reg(apic, APIC_TASKPRI) & 0xff;
b93463aa
AK
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
4e335d9e
PB
3263 kvm_write_guest_cached(vcpu->kvm, &vcpu->arch.apic->vapic_cache, &data,
3264 sizeof(u32));
b93463aa
AK
3265}
3266
fda4e2e8 3267int kvm_lapic_set_vapic_addr(struct kvm_vcpu *vcpu, gpa_t vapic_addr)
b93463aa 3268{
fda4e2e8 3269 if (vapic_addr) {
4e335d9e 3270 if (kvm_gfn_to_hva_cache_init(vcpu->kvm,
fda4e2e8
AH
3271 &vcpu->arch.apic->vapic_cache,
3272 vapic_addr, sizeof(u32)))
3273 return -EINVAL;
41383771 3274 __set_bit(KVM_APIC_CHECK_VAPIC, &vcpu->arch.apic_attention);
fda4e2e8 3275 } else {
41383771 3276 __clear_bit(KVM_APIC_CHECK_VAPIC, &vcpu->arch.apic_attention);
fda4e2e8
AH
3277 }
3278
3279 vcpu->arch.apic->vapic_addr = vapic_addr;
3280 return 0;
b93463aa 3281}
0105d1a5 3282
5429478d
SC
3283static int kvm_lapic_msr_read(struct kvm_lapic *apic, u32 reg, u64 *data)
3284{
a57a3168 3285 u32 low;
5429478d 3286
a57a3168 3287 if (reg == APIC_ICR) {
73b42dc6 3288 *data = kvm_x2apic_icr_read(apic);
a57a3168
SC
3289 return 0;
3290 }
5429478d 3291
a57a3168 3292 if (kvm_lapic_reg_read(apic, reg, 4, &low))
5429478d
SC
3293 return 1;
3294
a57a3168 3295 *data = low;
5429478d
SC
3296
3297 return 0;
3298}
3299
3300static int kvm_lapic_msr_write(struct kvm_lapic *apic, u32 reg, u64 data)
3301{
a57a3168 3302 /*
ab52be1b 3303 * ICR is a 64-bit register in x2APIC mode (and Hyper-V PV vAPIC) and
a57a3168
SC
3304 * can be written as such, all other registers remain accessible only
3305 * through 32-bit reads/writes.
3306 */
5429478d 3307 if (reg == APIC_ICR)
a57a3168
SC
3308 return kvm_x2apic_icr_write(apic, data);
3309
ab52be1b
SC
3310 /* Bits 63:32 are reserved in all other registers. */
3311 if (data >> 32)
3312 return 1;
3313
5429478d
SC
3314 return kvm_lapic_reg_write(apic, reg, (u32)data);
3315}
3316
0105d1a5
GN
3317int 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
35754c98 3322 if (!lapic_in_kernel(vcpu) || !apic_x2apic_mode(apic))
0105d1a5
GN
3323 return 1;
3324
5429478d 3325 return kvm_lapic_msr_write(apic, reg, data);
0105d1a5
GN
3326}
3327
3328int kvm_x2apic_msr_read(struct kvm_vcpu *vcpu, u32 msr, u64 *data)
3329{
3330 struct kvm_lapic *apic = vcpu->arch.apic;
5429478d 3331 u32 reg = (msr - APIC_BASE_MSR) << 4;
0105d1a5 3332
35754c98 3333 if (!lapic_in_kernel(vcpu) || !apic_x2apic_mode(apic))
0105d1a5
GN
3334 return 1;
3335
5429478d 3336 return kvm_lapic_msr_read(apic, reg, data);
0105d1a5 3337}
10388a07
GN
3338
3339int kvm_hv_vapic_msr_write(struct kvm_vcpu *vcpu, u32 reg, u64 data)
3340{
bce87cce 3341 if (!lapic_in_kernel(vcpu))
10388a07
GN
3342 return 1;
3343
5429478d 3344 return kvm_lapic_msr_write(vcpu->arch.apic, reg, data);
10388a07
GN
3345}
3346
3347int kvm_hv_vapic_msr_read(struct kvm_vcpu *vcpu, u32 reg, u64 *data)
3348{
bce87cce 3349 if (!lapic_in_kernel(vcpu))
10388a07
GN
3350 return 1;
3351
5429478d 3352 return kvm_lapic_msr_read(vcpu->arch.apic, reg, data);
10388a07 3353}
ae7a2a3f 3354
77c3323f 3355int kvm_lapic_set_pv_eoi(struct kvm_vcpu *vcpu, u64 data, unsigned long len)
ae7a2a3f
MT
3356{
3357 u64 addr = data & ~KVM_MSR_ENABLED;
a7c42bb6
VK
3358 struct gfn_to_hva_cache *ghc = &vcpu->arch.pv_eoi.data;
3359 unsigned long new_len;
afd67ee3 3360 int ret;
a7c42bb6 3361
ae7a2a3f
MT
3362 if (!IS_ALIGNED(addr, 4))
3363 return 1;
3364
afd67ee3
VK
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;
a7c42bb6 3370
afd67ee3
VK
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;
a7c42bb6 3377
afd67ee3 3378 return 0;
ae7a2a3f 3379}
c5cc421b 3380
4fe09bcf 3381int kvm_apic_accept_events(struct kvm_vcpu *vcpu)
66450a21
JK
3382{
3383 struct kvm_lapic *apic = vcpu->arch.apic;
2b4a273b 3384 u8 sipi_vector;
1c96dcce 3385 int r;
66450a21 3386
1e17a6f8 3387 if (!kvm_apic_has_pending_init_or_sipi(vcpu))
4fe09bcf 3388 return 0;
66450a21 3389
1c96dcce 3390 if (is_guest_mode(vcpu)) {
cb6a32c2 3391 r = kvm_check_nested_events(vcpu);
1c96dcce 3392 if (r < 0)
4fe09bcf 3393 return r == -EBUSY ? 0 : r;
1c96dcce 3394 /*
1e17a6f8
SC
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.
1c96dcce
PB
3398 */
3399 }
3400
cd7764fe 3401 /*
1e17a6f8
SC
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).
cd7764fe 3405 */
1b7a1b78 3406 if (!kvm_apic_init_sipi_allowed(vcpu)) {
cd7764fe 3407 WARN_ON_ONCE(vcpu->arch.mp_state == KVM_MP_STATE_INIT_RECEIVED);
1e17a6f8 3408 clear_bit(KVM_APIC_SIPI, &apic->pending_events);
4fe09bcf 3409 return 0;
cd7764fe 3410 }
299018f4 3411
1e17a6f8 3412 if (test_and_clear_bit(KVM_APIC_INIT, &apic->pending_events)) {
d28bc9dd 3413 kvm_vcpu_reset(vcpu, true);
66450a21 3414 if (kvm_vcpu_is_bsp(apic->vcpu))
c9e5f3fa 3415 kvm_set_mp_state(vcpu, KVM_MP_STATE_RUNNABLE);
66450a21 3416 else
c9e5f3fa 3417 kvm_set_mp_state(vcpu, KVM_MP_STATE_INIT_RECEIVED);
66450a21 3418 }
1e17a6f8 3419 if (test_and_clear_bit(KVM_APIC_SIPI, &apic->pending_events)) {
f57ad63a
ML
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;
89604647
WW
3424 kvm_x86_call(vcpu_deliver_sipi_vector)(vcpu,
3425 sipi_vector);
c9e5f3fa 3426 kvm_set_mp_state(vcpu, KVM_MP_STATE_RUNNABLE);
f57ad63a 3427 }
66450a21 3428 }
4fe09bcf 3429 return 0;
66450a21
JK
3430}
3431
cef84c30
DM
3432void kvm_lapic_exit(void)
3433{
3434 static_key_deferred_flush(&apic_hw_disabled);
9139a7a6 3435 WARN_ON(static_branch_unlikely(&apic_hw_disabled.key));
cef84c30 3436 static_key_deferred_flush(&apic_sw_disabled);
9139a7a6 3437 WARN_ON(static_branch_unlikely(&apic_sw_disabled.key));
cef84c30 3438}