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