mm: fix exec activate_mm vs TLB shootdown and lazy tlb switching race
[linux/fpc-iii.git] / arch / x86 / kvm / lapic.c
blobd4fdf0e5214409fb17274bbba2a9d4820cbdf5cd
2 /*
3 * Local APIC virtualization
5 * Copyright (C) 2006 Qumranet, Inc.
6 * Copyright (C) 2007 Novell
7 * Copyright (C) 2007 Intel
8 * Copyright 2009 Red Hat, Inc. and/or its affiliates.
10 * Authors:
11 * Dor Laor <dor.laor@qumranet.com>
12 * Gregory Haskins <ghaskins@novell.com>
13 * Yaozu (Eddie) Dong <eddie.dong@intel.com>
15 * Based on Xen 3.1 code, Copyright (c) 2004, Intel Corporation.
17 * This work is licensed under the terms of the GNU GPL, version 2. See
18 * the COPYING file in the top-level directory.
21 #include <linux/kvm_host.h>
22 #include <linux/kvm.h>
23 #include <linux/mm.h>
24 #include <linux/highmem.h>
25 #include <linux/smp.h>
26 #include <linux/hrtimer.h>
27 #include <linux/io.h>
28 #include <linux/export.h>
29 #include <linux/math64.h>
30 #include <linux/slab.h>
31 #include <asm/processor.h>
32 #include <asm/msr.h>
33 #include <asm/page.h>
34 #include <asm/current.h>
35 #include <asm/apicdef.h>
36 #include <asm/delay.h>
37 #include <linux/atomic.h>
38 #include <linux/jump_label.h>
39 #include "kvm_cache_regs.h"
40 #include "irq.h"
41 #include "trace.h"
42 #include "x86.h"
43 #include "cpuid.h"
44 #include "hyperv.h"
46 #ifndef CONFIG_X86_64
47 #define mod_64(x, y) ((x) - (y) * div64_u64(x, y))
48 #else
49 #define mod_64(x, y) ((x) % (y))
50 #endif
52 #define PRId64 "d"
53 #define PRIx64 "llx"
54 #define PRIu64 "u"
55 #define PRIo64 "o"
57 /* #define apic_debug(fmt,arg...) printk(KERN_WARNING fmt,##arg) */
58 #define apic_debug(fmt, arg...) do {} while (0)
60 /* 14 is the version for Xeon and Pentium 8.4.8*/
61 #define APIC_VERSION (0x14UL | ((KVM_APIC_LVT_NUM - 1) << 16))
62 #define LAPIC_MMIO_LENGTH (1 << 12)
63 /* followed define is not in apicdef.h */
64 #define APIC_SHORT_MASK 0xc0000
65 #define APIC_DEST_NOSHORT 0x0
66 #define APIC_DEST_MASK 0x800
67 #define MAX_APIC_VECTOR 256
68 #define APIC_VECTORS_PER_REG 32
70 #define APIC_BROADCAST 0xFF
71 #define X2APIC_BROADCAST 0xFFFFFFFFul
73 static inline int apic_test_vector(int vec, void *bitmap)
75 return test_bit(VEC_POS(vec), (bitmap) + REG_POS(vec));
78 bool kvm_apic_pending_eoi(struct kvm_vcpu *vcpu, int vector)
80 struct kvm_lapic *apic = vcpu->arch.apic;
82 return apic_test_vector(vector, apic->regs + APIC_ISR) ||
83 apic_test_vector(vector, apic->regs + APIC_IRR);
86 static inline void apic_clear_vector(int vec, void *bitmap)
88 clear_bit(VEC_POS(vec), (bitmap) + REG_POS(vec));
91 static inline int __apic_test_and_set_vector(int vec, void *bitmap)
93 return __test_and_set_bit(VEC_POS(vec), (bitmap) + REG_POS(vec));
96 static inline int __apic_test_and_clear_vector(int vec, void *bitmap)
98 return __test_and_clear_bit(VEC_POS(vec), (bitmap) + REG_POS(vec));
101 struct static_key_deferred apic_hw_disabled __read_mostly;
102 struct static_key_deferred apic_sw_disabled __read_mostly;
104 static inline int apic_enabled(struct kvm_lapic *apic)
106 return kvm_apic_sw_enabled(apic) && kvm_apic_hw_enabled(apic);
109 #define LVT_MASK \
110 (APIC_LVT_MASKED | APIC_SEND_PENDING | APIC_VECTOR_MASK)
112 #define LINT_MASK \
113 (LVT_MASK | APIC_MODE_MASK | APIC_INPUT_POLARITY | \
114 APIC_LVT_REMOTE_IRR | APIC_LVT_LEVEL_TRIGGER)
116 static inline u8 kvm_xapic_id(struct kvm_lapic *apic)
118 return kvm_lapic_get_reg(apic, APIC_ID) >> 24;
121 static inline u32 kvm_x2apic_id(struct kvm_lapic *apic)
123 return apic->vcpu->vcpu_id;
126 static inline bool kvm_apic_map_get_logical_dest(struct kvm_apic_map *map,
127 u32 dest_id, struct kvm_lapic ***cluster, u16 *mask) {
128 switch (map->mode) {
129 case KVM_APIC_MODE_X2APIC: {
130 u32 offset = (dest_id >> 16) * 16;
131 u32 max_apic_id = map->max_apic_id;
133 if (offset <= max_apic_id) {
134 u8 cluster_size = min(max_apic_id - offset + 1, 16U);
136 offset = array_index_nospec(offset, map->max_apic_id + 1);
137 *cluster = &map->phys_map[offset];
138 *mask = dest_id & (0xffff >> (16 - cluster_size));
139 } else {
140 *mask = 0;
143 return true;
145 case KVM_APIC_MODE_XAPIC_FLAT:
146 *cluster = map->xapic_flat_map;
147 *mask = dest_id & 0xff;
148 return true;
149 case KVM_APIC_MODE_XAPIC_CLUSTER:
150 *cluster = map->xapic_cluster_map[(dest_id >> 4) & 0xf];
151 *mask = dest_id & 0xf;
152 return true;
153 default:
154 /* Not optimized. */
155 return false;
159 static void kvm_apic_map_free(struct rcu_head *rcu)
161 struct kvm_apic_map *map = container_of(rcu, struct kvm_apic_map, rcu);
163 kvfree(map);
166 static void recalculate_apic_map(struct kvm *kvm)
168 struct kvm_apic_map *new, *old = NULL;
169 struct kvm_vcpu *vcpu;
170 int i;
171 u32 max_id = 255; /* enough space for any xAPIC ID */
173 mutex_lock(&kvm->arch.apic_map_lock);
175 kvm_for_each_vcpu(i, vcpu, kvm)
176 if (kvm_apic_present(vcpu))
177 max_id = max(max_id, kvm_x2apic_id(vcpu->arch.apic));
179 new = kvzalloc(sizeof(struct kvm_apic_map) +
180 sizeof(struct kvm_lapic *) * ((u64)max_id + 1), GFP_KERNEL);
182 if (!new)
183 goto out;
185 new->max_apic_id = max_id;
187 kvm_for_each_vcpu(i, vcpu, kvm) {
188 struct kvm_lapic *apic = vcpu->arch.apic;
189 struct kvm_lapic **cluster;
190 u16 mask;
191 u32 ldr;
192 u8 xapic_id;
193 u32 x2apic_id;
195 if (!kvm_apic_present(vcpu))
196 continue;
198 xapic_id = kvm_xapic_id(apic);
199 x2apic_id = kvm_x2apic_id(apic);
201 /* Hotplug hack: see kvm_apic_match_physical_addr(), ... */
202 if ((apic_x2apic_mode(apic) || x2apic_id > 0xff) &&
203 x2apic_id <= new->max_apic_id)
204 new->phys_map[x2apic_id] = apic;
206 * ... xAPIC ID of VCPUs with APIC ID > 0xff will wrap-around,
207 * prevent them from masking VCPUs with APIC ID <= 0xff.
209 if (!apic_x2apic_mode(apic) && !new->phys_map[xapic_id])
210 new->phys_map[xapic_id] = apic;
212 if (!kvm_apic_sw_enabled(apic))
213 continue;
215 ldr = kvm_lapic_get_reg(apic, APIC_LDR);
217 if (apic_x2apic_mode(apic)) {
218 new->mode |= KVM_APIC_MODE_X2APIC;
219 } else if (ldr) {
220 ldr = GET_APIC_LOGICAL_ID(ldr);
221 if (kvm_lapic_get_reg(apic, APIC_DFR) == APIC_DFR_FLAT)
222 new->mode |= KVM_APIC_MODE_XAPIC_FLAT;
223 else
224 new->mode |= KVM_APIC_MODE_XAPIC_CLUSTER;
227 if (!kvm_apic_map_get_logical_dest(new, ldr, &cluster, &mask))
228 continue;
230 if (mask)
231 cluster[ffs(mask) - 1] = apic;
233 out:
234 old = rcu_dereference_protected(kvm->arch.apic_map,
235 lockdep_is_held(&kvm->arch.apic_map_lock));
236 rcu_assign_pointer(kvm->arch.apic_map, new);
237 mutex_unlock(&kvm->arch.apic_map_lock);
239 if (old)
240 call_rcu(&old->rcu, kvm_apic_map_free);
242 kvm_make_scan_ioapic_request(kvm);
245 static inline void apic_set_spiv(struct kvm_lapic *apic, u32 val)
247 bool enabled = val & APIC_SPIV_APIC_ENABLED;
249 kvm_lapic_set_reg(apic, APIC_SPIV, val);
251 if (enabled != apic->sw_enabled) {
252 apic->sw_enabled = enabled;
253 if (enabled) {
254 static_key_slow_dec_deferred(&apic_sw_disabled);
255 recalculate_apic_map(apic->vcpu->kvm);
256 } else
257 static_key_slow_inc(&apic_sw_disabled.key);
259 recalculate_apic_map(apic->vcpu->kvm);
263 static inline void kvm_apic_set_xapic_id(struct kvm_lapic *apic, u8 id)
265 kvm_lapic_set_reg(apic, APIC_ID, id << 24);
266 recalculate_apic_map(apic->vcpu->kvm);
269 static inline void kvm_apic_set_ldr(struct kvm_lapic *apic, u32 id)
271 kvm_lapic_set_reg(apic, APIC_LDR, id);
272 recalculate_apic_map(apic->vcpu->kvm);
275 static inline u32 kvm_apic_calc_x2apic_ldr(u32 id)
277 return ((id >> 4) << 16) | (1 << (id & 0xf));
280 static inline void kvm_apic_set_x2apic_id(struct kvm_lapic *apic, u32 id)
282 u32 ldr = kvm_apic_calc_x2apic_ldr(id);
284 WARN_ON_ONCE(id != apic->vcpu->vcpu_id);
286 kvm_lapic_set_reg(apic, APIC_ID, id);
287 kvm_lapic_set_reg(apic, APIC_LDR, ldr);
288 recalculate_apic_map(apic->vcpu->kvm);
291 static inline int apic_lvt_enabled(struct kvm_lapic *apic, int lvt_type)
293 return !(kvm_lapic_get_reg(apic, lvt_type) & APIC_LVT_MASKED);
296 static inline int apic_lvt_vector(struct kvm_lapic *apic, int lvt_type)
298 return kvm_lapic_get_reg(apic, lvt_type) & APIC_VECTOR_MASK;
301 static inline int apic_lvtt_oneshot(struct kvm_lapic *apic)
303 return apic->lapic_timer.timer_mode == APIC_LVT_TIMER_ONESHOT;
306 static inline int apic_lvtt_period(struct kvm_lapic *apic)
308 return apic->lapic_timer.timer_mode == APIC_LVT_TIMER_PERIODIC;
311 static inline int apic_lvtt_tscdeadline(struct kvm_lapic *apic)
313 return apic->lapic_timer.timer_mode == APIC_LVT_TIMER_TSCDEADLINE;
316 static inline int apic_lvt_nmi_mode(u32 lvt_val)
318 return (lvt_val & (APIC_MODE_MASK | APIC_LVT_MASKED)) == APIC_DM_NMI;
321 void kvm_apic_set_version(struct kvm_vcpu *vcpu)
323 struct kvm_lapic *apic = vcpu->arch.apic;
324 struct kvm_cpuid_entry2 *feat;
325 u32 v = APIC_VERSION;
327 if (!lapic_in_kernel(vcpu))
328 return;
331 * KVM emulates 82093AA datasheet (with in-kernel IOAPIC implementation)
332 * which doesn't have EOI register; Some buggy OSes (e.g. Windows with
333 * Hyper-V role) disable EOI broadcast in lapic not checking for IOAPIC
334 * version first and level-triggered interrupts never get EOIed in
335 * IOAPIC.
337 feat = kvm_find_cpuid_entry(apic->vcpu, 0x1, 0);
338 if (feat && (feat->ecx & (1 << (X86_FEATURE_X2APIC & 31))) &&
339 !ioapic_in_kernel(vcpu->kvm))
340 v |= APIC_LVR_DIRECTED_EOI;
341 kvm_lapic_set_reg(apic, APIC_LVR, v);
344 static const unsigned int apic_lvt_mask[KVM_APIC_LVT_NUM] = {
345 LVT_MASK , /* part LVTT mask, timer mode mask added at runtime */
346 LVT_MASK | APIC_MODE_MASK, /* LVTTHMR */
347 LVT_MASK | APIC_MODE_MASK, /* LVTPC */
348 LINT_MASK, LINT_MASK, /* LVT0-1 */
349 LVT_MASK /* LVTERR */
352 static int find_highest_vector(void *bitmap)
354 int vec;
355 u32 *reg;
357 for (vec = MAX_APIC_VECTOR - APIC_VECTORS_PER_REG;
358 vec >= 0; vec -= APIC_VECTORS_PER_REG) {
359 reg = bitmap + REG_POS(vec);
360 if (*reg)
361 return __fls(*reg) + vec;
364 return -1;
367 static u8 count_vectors(void *bitmap)
369 int vec;
370 u32 *reg;
371 u8 count = 0;
373 for (vec = 0; vec < MAX_APIC_VECTOR; vec += APIC_VECTORS_PER_REG) {
374 reg = bitmap + REG_POS(vec);
375 count += hweight32(*reg);
378 return count;
381 int __kvm_apic_update_irr(u32 *pir, void *regs)
383 u32 i, vec;
384 u32 pir_val, irr_val;
385 int max_irr = -1;
387 for (i = vec = 0; i <= 7; i++, vec += 32) {
388 pir_val = READ_ONCE(pir[i]);
389 irr_val = *((u32 *)(regs + APIC_IRR + i * 0x10));
390 if (pir_val) {
391 irr_val |= xchg(&pir[i], 0);
392 *((u32 *)(regs + APIC_IRR + i * 0x10)) = irr_val;
394 if (irr_val)
395 max_irr = __fls(irr_val) + vec;
398 return max_irr;
400 EXPORT_SYMBOL_GPL(__kvm_apic_update_irr);
402 int kvm_apic_update_irr(struct kvm_vcpu *vcpu, u32 *pir)
404 struct kvm_lapic *apic = vcpu->arch.apic;
406 return __kvm_apic_update_irr(pir, apic->regs);
408 EXPORT_SYMBOL_GPL(kvm_apic_update_irr);
410 static inline int apic_search_irr(struct kvm_lapic *apic)
412 return find_highest_vector(apic->regs + APIC_IRR);
415 static inline int apic_find_highest_irr(struct kvm_lapic *apic)
417 int result;
420 * Note that irr_pending is just a hint. It will be always
421 * true with virtual interrupt delivery enabled.
423 if (!apic->irr_pending)
424 return -1;
426 result = apic_search_irr(apic);
427 ASSERT(result == -1 || result >= 16);
429 return result;
432 static inline void apic_clear_irr(int vec, struct kvm_lapic *apic)
434 struct kvm_vcpu *vcpu;
436 vcpu = apic->vcpu;
438 if (unlikely(vcpu->arch.apicv_active)) {
439 /* need to update RVI */
440 apic_clear_vector(vec, apic->regs + APIC_IRR);
441 kvm_x86_ops->hwapic_irr_update(vcpu,
442 apic_find_highest_irr(apic));
443 } else {
444 apic->irr_pending = false;
445 apic_clear_vector(vec, apic->regs + APIC_IRR);
446 if (apic_search_irr(apic) != -1)
447 apic->irr_pending = true;
451 static inline void apic_set_isr(int vec, struct kvm_lapic *apic)
453 struct kvm_vcpu *vcpu;
455 if (__apic_test_and_set_vector(vec, apic->regs + APIC_ISR))
456 return;
458 vcpu = apic->vcpu;
461 * With APIC virtualization enabled, all caching is disabled
462 * because the processor can modify ISR under the hood. Instead
463 * just set SVI.
465 if (unlikely(vcpu->arch.apicv_active))
466 kvm_x86_ops->hwapic_isr_update(vcpu, vec);
467 else {
468 ++apic->isr_count;
469 BUG_ON(apic->isr_count > MAX_APIC_VECTOR);
471 * ISR (in service register) bit is set when injecting an interrupt.
472 * The highest vector is injected. Thus the latest bit set matches
473 * the highest bit in ISR.
475 apic->highest_isr_cache = vec;
479 static inline int apic_find_highest_isr(struct kvm_lapic *apic)
481 int result;
484 * Note that isr_count is always 1, and highest_isr_cache
485 * is always -1, with APIC virtualization enabled.
487 if (!apic->isr_count)
488 return -1;
489 if (likely(apic->highest_isr_cache != -1))
490 return apic->highest_isr_cache;
492 result = find_highest_vector(apic->regs + APIC_ISR);
493 ASSERT(result == -1 || result >= 16);
495 return result;
498 static inline void apic_clear_isr(int vec, struct kvm_lapic *apic)
500 struct kvm_vcpu *vcpu;
501 if (!__apic_test_and_clear_vector(vec, apic->regs + APIC_ISR))
502 return;
504 vcpu = apic->vcpu;
507 * We do get here for APIC virtualization enabled if the guest
508 * uses the Hyper-V APIC enlightenment. In this case we may need
509 * to trigger a new interrupt delivery by writing the SVI field;
510 * on the other hand isr_count and highest_isr_cache are unused
511 * and must be left alone.
513 if (unlikely(vcpu->arch.apicv_active))
514 kvm_x86_ops->hwapic_isr_update(vcpu,
515 apic_find_highest_isr(apic));
516 else {
517 --apic->isr_count;
518 BUG_ON(apic->isr_count < 0);
519 apic->highest_isr_cache = -1;
523 int kvm_lapic_find_highest_irr(struct kvm_vcpu *vcpu)
525 /* This may race with setting of irr in __apic_accept_irq() and
526 * value returned may be wrong, but kvm_vcpu_kick() in __apic_accept_irq
527 * will cause vmexit immediately and the value will be recalculated
528 * on the next vmentry.
530 return apic_find_highest_irr(vcpu->arch.apic);
532 EXPORT_SYMBOL_GPL(kvm_lapic_find_highest_irr);
534 static int __apic_accept_irq(struct kvm_lapic *apic, int delivery_mode,
535 int vector, int level, int trig_mode,
536 struct dest_map *dest_map);
538 int kvm_apic_set_irq(struct kvm_vcpu *vcpu, struct kvm_lapic_irq *irq,
539 struct dest_map *dest_map)
541 struct kvm_lapic *apic = vcpu->arch.apic;
543 return __apic_accept_irq(apic, irq->delivery_mode, irq->vector,
544 irq->level, irq->trig_mode, dest_map);
547 static int pv_eoi_put_user(struct kvm_vcpu *vcpu, u8 val)
550 return kvm_write_guest_cached(vcpu->kvm, &vcpu->arch.pv_eoi.data, &val,
551 sizeof(val));
554 static int pv_eoi_get_user(struct kvm_vcpu *vcpu, u8 *val)
557 return kvm_read_guest_cached(vcpu->kvm, &vcpu->arch.pv_eoi.data, val,
558 sizeof(*val));
561 static inline bool pv_eoi_enabled(struct kvm_vcpu *vcpu)
563 return vcpu->arch.pv_eoi.msr_val & KVM_MSR_ENABLED;
566 static bool pv_eoi_get_pending(struct kvm_vcpu *vcpu)
568 u8 val;
569 if (pv_eoi_get_user(vcpu, &val) < 0) {
570 apic_debug("Can't read EOI MSR value: 0x%llx\n",
571 (unsigned long long)vcpu->arch.pv_eoi.msr_val);
572 return false;
574 return val & 0x1;
577 static void pv_eoi_set_pending(struct kvm_vcpu *vcpu)
579 if (pv_eoi_put_user(vcpu, KVM_PV_EOI_ENABLED) < 0) {
580 apic_debug("Can't set EOI MSR value: 0x%llx\n",
581 (unsigned long long)vcpu->arch.pv_eoi.msr_val);
582 return;
584 __set_bit(KVM_APIC_PV_EOI_PENDING, &vcpu->arch.apic_attention);
587 static void pv_eoi_clr_pending(struct kvm_vcpu *vcpu)
589 if (pv_eoi_put_user(vcpu, KVM_PV_EOI_DISABLED) < 0) {
590 apic_debug("Can't clear EOI MSR value: 0x%llx\n",
591 (unsigned long long)vcpu->arch.pv_eoi.msr_val);
592 return;
594 __clear_bit(KVM_APIC_PV_EOI_PENDING, &vcpu->arch.apic_attention);
597 static int apic_has_interrupt_for_ppr(struct kvm_lapic *apic, u32 ppr)
599 int highest_irr;
600 if (kvm_x86_ops->sync_pir_to_irr && apic->vcpu->arch.apicv_active)
601 highest_irr = kvm_x86_ops->sync_pir_to_irr(apic->vcpu);
602 else
603 highest_irr = apic_find_highest_irr(apic);
604 if (highest_irr == -1 || (highest_irr & 0xF0) <= ppr)
605 return -1;
606 return highest_irr;
609 static bool __apic_update_ppr(struct kvm_lapic *apic, u32 *new_ppr)
611 u32 tpr, isrv, ppr, old_ppr;
612 int isr;
614 old_ppr = kvm_lapic_get_reg(apic, APIC_PROCPRI);
615 tpr = kvm_lapic_get_reg(apic, APIC_TASKPRI);
616 isr = apic_find_highest_isr(apic);
617 isrv = (isr != -1) ? isr : 0;
619 if ((tpr & 0xf0) >= (isrv & 0xf0))
620 ppr = tpr & 0xff;
621 else
622 ppr = isrv & 0xf0;
624 apic_debug("vlapic %p, ppr 0x%x, isr 0x%x, isrv 0x%x",
625 apic, ppr, isr, isrv);
627 *new_ppr = ppr;
628 if (old_ppr != ppr)
629 kvm_lapic_set_reg(apic, APIC_PROCPRI, ppr);
631 return ppr < old_ppr;
634 static void apic_update_ppr(struct kvm_lapic *apic)
636 u32 ppr;
638 if (__apic_update_ppr(apic, &ppr) &&
639 apic_has_interrupt_for_ppr(apic, ppr) != -1)
640 kvm_make_request(KVM_REQ_EVENT, apic->vcpu);
643 void kvm_apic_update_ppr(struct kvm_vcpu *vcpu)
645 apic_update_ppr(vcpu->arch.apic);
647 EXPORT_SYMBOL_GPL(kvm_apic_update_ppr);
649 static void apic_set_tpr(struct kvm_lapic *apic, u32 tpr)
651 kvm_lapic_set_reg(apic, APIC_TASKPRI, tpr);
652 apic_update_ppr(apic);
655 static bool kvm_apic_broadcast(struct kvm_lapic *apic, u32 mda)
657 return mda == (apic_x2apic_mode(apic) ?
658 X2APIC_BROADCAST : APIC_BROADCAST);
661 static bool kvm_apic_match_physical_addr(struct kvm_lapic *apic, u32 mda)
663 if (kvm_apic_broadcast(apic, mda))
664 return true;
666 if (apic_x2apic_mode(apic))
667 return mda == kvm_x2apic_id(apic);
670 * Hotplug hack: Make LAPIC in xAPIC mode also accept interrupts as if
671 * it were in x2APIC mode. Hotplugged VCPUs start in xAPIC mode and
672 * this allows unique addressing of VCPUs with APIC ID over 0xff.
673 * The 0xff condition is needed because writeable xAPIC ID.
675 if (kvm_x2apic_id(apic) > 0xff && mda == kvm_x2apic_id(apic))
676 return true;
678 return mda == kvm_xapic_id(apic);
681 static bool kvm_apic_match_logical_addr(struct kvm_lapic *apic, u32 mda)
683 u32 logical_id;
685 if (kvm_apic_broadcast(apic, mda))
686 return true;
688 logical_id = kvm_lapic_get_reg(apic, APIC_LDR);
690 if (apic_x2apic_mode(apic))
691 return ((logical_id >> 16) == (mda >> 16))
692 && (logical_id & mda & 0xffff) != 0;
694 logical_id = GET_APIC_LOGICAL_ID(logical_id);
696 switch (kvm_lapic_get_reg(apic, APIC_DFR)) {
697 case APIC_DFR_FLAT:
698 return (logical_id & mda) != 0;
699 case APIC_DFR_CLUSTER:
700 return ((logical_id >> 4) == (mda >> 4))
701 && (logical_id & mda & 0xf) != 0;
702 default:
703 apic_debug("Bad DFR vcpu %d: %08x\n",
704 apic->vcpu->vcpu_id, kvm_lapic_get_reg(apic, APIC_DFR));
705 return false;
709 /* The KVM local APIC implementation has two quirks:
711 * - Real hardware delivers interrupts destined to x2APIC ID > 0xff to LAPICs
712 * in xAPIC mode if the "destination & 0xff" matches its xAPIC ID.
713 * KVM doesn't do that aliasing.
715 * - in-kernel IOAPIC messages have to be delivered directly to
716 * x2APIC, because the kernel does not support interrupt remapping.
717 * In order to support broadcast without interrupt remapping, x2APIC
718 * rewrites the destination of non-IPI messages from APIC_BROADCAST
719 * to X2APIC_BROADCAST.
721 * The broadcast quirk can be disabled with KVM_CAP_X2APIC_API. This is
722 * important when userspace wants to use x2APIC-format MSIs, because
723 * APIC_BROADCAST (0xff) is a legal route for "cluster 0, CPUs 0-7".
725 static u32 kvm_apic_mda(struct kvm_vcpu *vcpu, unsigned int dest_id,
726 struct kvm_lapic *source, struct kvm_lapic *target)
728 bool ipi = source != NULL;
730 if (!vcpu->kvm->arch.x2apic_broadcast_quirk_disabled &&
731 !ipi && dest_id == APIC_BROADCAST && apic_x2apic_mode(target))
732 return X2APIC_BROADCAST;
734 return dest_id;
737 bool kvm_apic_match_dest(struct kvm_vcpu *vcpu, struct kvm_lapic *source,
738 int short_hand, unsigned int dest, int dest_mode)
740 struct kvm_lapic *target = vcpu->arch.apic;
741 u32 mda = kvm_apic_mda(vcpu, dest, source, target);
743 apic_debug("target %p, source %p, dest 0x%x, "
744 "dest_mode 0x%x, short_hand 0x%x\n",
745 target, source, dest, dest_mode, short_hand);
747 ASSERT(target);
748 switch (short_hand) {
749 case APIC_DEST_NOSHORT:
750 if (dest_mode == APIC_DEST_PHYSICAL)
751 return kvm_apic_match_physical_addr(target, mda);
752 else
753 return kvm_apic_match_logical_addr(target, mda);
754 case APIC_DEST_SELF:
755 return target == source;
756 case APIC_DEST_ALLINC:
757 return true;
758 case APIC_DEST_ALLBUT:
759 return target != source;
760 default:
761 apic_debug("kvm: apic: Bad dest shorthand value %x\n",
762 short_hand);
763 return false;
766 EXPORT_SYMBOL_GPL(kvm_apic_match_dest);
768 int kvm_vector_to_index(u32 vector, u32 dest_vcpus,
769 const unsigned long *bitmap, u32 bitmap_size)
771 u32 mod;
772 int i, idx = -1;
774 mod = vector % dest_vcpus;
776 for (i = 0; i <= mod; i++) {
777 idx = find_next_bit(bitmap, bitmap_size, idx + 1);
778 BUG_ON(idx == bitmap_size);
781 return idx;
784 static void kvm_apic_disabled_lapic_found(struct kvm *kvm)
786 if (!kvm->arch.disabled_lapic_found) {
787 kvm->arch.disabled_lapic_found = true;
788 printk(KERN_INFO
789 "Disabled LAPIC found during irq injection\n");
793 static bool kvm_apic_is_broadcast_dest(struct kvm *kvm, struct kvm_lapic **src,
794 struct kvm_lapic_irq *irq, struct kvm_apic_map *map)
796 if (kvm->arch.x2apic_broadcast_quirk_disabled) {
797 if ((irq->dest_id == APIC_BROADCAST &&
798 map->mode != KVM_APIC_MODE_X2APIC))
799 return true;
800 if (irq->dest_id == X2APIC_BROADCAST)
801 return true;
802 } else {
803 bool x2apic_ipi = src && *src && apic_x2apic_mode(*src);
804 if (irq->dest_id == (x2apic_ipi ?
805 X2APIC_BROADCAST : APIC_BROADCAST))
806 return true;
809 return false;
812 /* Return true if the interrupt can be handled by using *bitmap as index mask
813 * for valid destinations in *dst array.
814 * Return false if kvm_apic_map_get_dest_lapic did nothing useful.
815 * Note: we may have zero kvm_lapic destinations when we return true, which
816 * means that the interrupt should be dropped. In this case, *bitmap would be
817 * zero and *dst undefined.
819 static inline bool kvm_apic_map_get_dest_lapic(struct kvm *kvm,
820 struct kvm_lapic **src, struct kvm_lapic_irq *irq,
821 struct kvm_apic_map *map, struct kvm_lapic ***dst,
822 unsigned long *bitmap)
824 int i, lowest;
826 if (irq->shorthand == APIC_DEST_SELF && src) {
827 *dst = src;
828 *bitmap = 1;
829 return true;
830 } else if (irq->shorthand)
831 return false;
833 if (!map || kvm_apic_is_broadcast_dest(kvm, src, irq, map))
834 return false;
836 if (irq->dest_mode == APIC_DEST_PHYSICAL) {
837 if (irq->dest_id > map->max_apic_id) {
838 *bitmap = 0;
839 } else {
840 u32 dest_id = array_index_nospec(irq->dest_id, map->max_apic_id + 1);
841 *dst = &map->phys_map[dest_id];
842 *bitmap = 1;
844 return true;
847 *bitmap = 0;
848 if (!kvm_apic_map_get_logical_dest(map, irq->dest_id, dst,
849 (u16 *)bitmap))
850 return false;
852 if (!kvm_lowest_prio_delivery(irq))
853 return true;
855 if (!kvm_vector_hashing_enabled()) {
856 lowest = -1;
857 for_each_set_bit(i, bitmap, 16) {
858 if (!(*dst)[i])
859 continue;
860 if (lowest < 0)
861 lowest = i;
862 else if (kvm_apic_compare_prio((*dst)[i]->vcpu,
863 (*dst)[lowest]->vcpu) < 0)
864 lowest = i;
866 } else {
867 if (!*bitmap)
868 return true;
870 lowest = kvm_vector_to_index(irq->vector, hweight16(*bitmap),
871 bitmap, 16);
873 if (!(*dst)[lowest]) {
874 kvm_apic_disabled_lapic_found(kvm);
875 *bitmap = 0;
876 return true;
880 *bitmap = (lowest >= 0) ? 1 << lowest : 0;
882 return true;
885 bool kvm_irq_delivery_to_apic_fast(struct kvm *kvm, struct kvm_lapic *src,
886 struct kvm_lapic_irq *irq, int *r, struct dest_map *dest_map)
888 struct kvm_apic_map *map;
889 unsigned long bitmap;
890 struct kvm_lapic **dst = NULL;
891 int i;
892 bool ret;
894 *r = -1;
896 if (irq->shorthand == APIC_DEST_SELF) {
897 *r = kvm_apic_set_irq(src->vcpu, irq, dest_map);
898 return true;
901 rcu_read_lock();
902 map = rcu_dereference(kvm->arch.apic_map);
904 ret = kvm_apic_map_get_dest_lapic(kvm, &src, irq, map, &dst, &bitmap);
905 if (ret)
906 for_each_set_bit(i, &bitmap, 16) {
907 if (!dst[i])
908 continue;
909 if (*r < 0)
910 *r = 0;
911 *r += kvm_apic_set_irq(dst[i]->vcpu, irq, dest_map);
914 rcu_read_unlock();
915 return ret;
919 * This routine tries to handler interrupts in posted mode, here is how
920 * it deals with different cases:
921 * - For single-destination interrupts, handle it in posted mode
922 * - Else if vector hashing is enabled and it is a lowest-priority
923 * interrupt, handle it in posted mode and use the following mechanism
924 * to find the destinaiton vCPU.
925 * 1. For lowest-priority interrupts, store all the possible
926 * destination vCPUs in an array.
927 * 2. Use "guest vector % max number of destination vCPUs" to find
928 * the right destination vCPU in the array for the lowest-priority
929 * interrupt.
930 * - Otherwise, use remapped mode to inject the interrupt.
932 bool kvm_intr_is_single_vcpu_fast(struct kvm *kvm, struct kvm_lapic_irq *irq,
933 struct kvm_vcpu **dest_vcpu)
935 struct kvm_apic_map *map;
936 unsigned long bitmap;
937 struct kvm_lapic **dst = NULL;
938 bool ret = false;
940 if (irq->shorthand)
941 return false;
943 rcu_read_lock();
944 map = rcu_dereference(kvm->arch.apic_map);
946 if (kvm_apic_map_get_dest_lapic(kvm, NULL, irq, map, &dst, &bitmap) &&
947 hweight16(bitmap) == 1) {
948 unsigned long i = find_first_bit(&bitmap, 16);
950 if (dst[i]) {
951 *dest_vcpu = dst[i]->vcpu;
952 ret = true;
956 rcu_read_unlock();
957 return ret;
961 * Add a pending IRQ into lapic.
962 * Return 1 if successfully added and 0 if discarded.
964 static int __apic_accept_irq(struct kvm_lapic *apic, int delivery_mode,
965 int vector, int level, int trig_mode,
966 struct dest_map *dest_map)
968 int result = 0;
969 struct kvm_vcpu *vcpu = apic->vcpu;
971 trace_kvm_apic_accept_irq(vcpu->vcpu_id, delivery_mode,
972 trig_mode, vector);
973 switch (delivery_mode) {
974 case APIC_DM_LOWEST:
975 vcpu->arch.apic_arb_prio++;
976 case APIC_DM_FIXED:
977 if (unlikely(trig_mode && !level))
978 break;
980 /* FIXME add logic for vcpu on reset */
981 if (unlikely(!apic_enabled(apic)))
982 break;
984 result = 1;
986 if (dest_map) {
987 __set_bit(vcpu->vcpu_id, dest_map->map);
988 dest_map->vectors[vcpu->vcpu_id] = vector;
991 if (apic_test_vector(vector, apic->regs + APIC_TMR) != !!trig_mode) {
992 if (trig_mode)
993 kvm_lapic_set_vector(vector, apic->regs + APIC_TMR);
994 else
995 apic_clear_vector(vector, apic->regs + APIC_TMR);
998 if (kvm_x86_ops->deliver_posted_interrupt(vcpu, vector)) {
999 kvm_lapic_set_irr(vector, apic);
1000 kvm_make_request(KVM_REQ_EVENT, vcpu);
1001 kvm_vcpu_kick(vcpu);
1003 break;
1005 case APIC_DM_REMRD:
1006 result = 1;
1007 vcpu->arch.pv.pv_unhalted = 1;
1008 kvm_make_request(KVM_REQ_EVENT, vcpu);
1009 kvm_vcpu_kick(vcpu);
1010 break;
1012 case APIC_DM_SMI:
1013 result = 1;
1014 kvm_make_request(KVM_REQ_SMI, vcpu);
1015 kvm_vcpu_kick(vcpu);
1016 break;
1018 case APIC_DM_NMI:
1019 result = 1;
1020 kvm_inject_nmi(vcpu);
1021 kvm_vcpu_kick(vcpu);
1022 break;
1024 case APIC_DM_INIT:
1025 if (!trig_mode || level) {
1026 result = 1;
1027 /* assumes that there are only KVM_APIC_INIT/SIPI */
1028 apic->pending_events = (1UL << KVM_APIC_INIT);
1029 /* make sure pending_events is visible before sending
1030 * the request */
1031 smp_wmb();
1032 kvm_make_request(KVM_REQ_EVENT, vcpu);
1033 kvm_vcpu_kick(vcpu);
1034 } else {
1035 apic_debug("Ignoring de-assert INIT to vcpu %d\n",
1036 vcpu->vcpu_id);
1038 break;
1040 case APIC_DM_STARTUP:
1041 apic_debug("SIPI to vcpu %d vector 0x%02x\n",
1042 vcpu->vcpu_id, vector);
1043 result = 1;
1044 apic->sipi_vector = vector;
1045 /* make sure sipi_vector is visible for the receiver */
1046 smp_wmb();
1047 set_bit(KVM_APIC_SIPI, &apic->pending_events);
1048 kvm_make_request(KVM_REQ_EVENT, vcpu);
1049 kvm_vcpu_kick(vcpu);
1050 break;
1052 case APIC_DM_EXTINT:
1054 * Should only be called by kvm_apic_local_deliver() with LVT0,
1055 * before NMI watchdog was enabled. Already handled by
1056 * kvm_apic_accept_pic_intr().
1058 break;
1060 default:
1061 printk(KERN_ERR "TODO: unsupported delivery mode %x\n",
1062 delivery_mode);
1063 break;
1065 return result;
1068 int kvm_apic_compare_prio(struct kvm_vcpu *vcpu1, struct kvm_vcpu *vcpu2)
1070 return vcpu1->arch.apic_arb_prio - vcpu2->arch.apic_arb_prio;
1073 static bool kvm_ioapic_handles_vector(struct kvm_lapic *apic, int vector)
1075 return test_bit(vector, apic->vcpu->arch.ioapic_handled_vectors);
1078 static void kvm_ioapic_send_eoi(struct kvm_lapic *apic, int vector)
1080 int trigger_mode;
1082 /* Eoi the ioapic only if the ioapic doesn't own the vector. */
1083 if (!kvm_ioapic_handles_vector(apic, vector))
1084 return;
1086 /* Request a KVM exit to inform the userspace IOAPIC. */
1087 if (irqchip_split(apic->vcpu->kvm)) {
1088 apic->vcpu->arch.pending_ioapic_eoi = vector;
1089 kvm_make_request(KVM_REQ_IOAPIC_EOI_EXIT, apic->vcpu);
1090 return;
1093 if (apic_test_vector(vector, apic->regs + APIC_TMR))
1094 trigger_mode = IOAPIC_LEVEL_TRIG;
1095 else
1096 trigger_mode = IOAPIC_EDGE_TRIG;
1098 kvm_ioapic_update_eoi(apic->vcpu, vector, trigger_mode);
1101 static int apic_set_eoi(struct kvm_lapic *apic)
1103 int vector = apic_find_highest_isr(apic);
1105 trace_kvm_eoi(apic, vector);
1108 * Not every write EOI will has corresponding ISR,
1109 * one example is when Kernel check timer on setup_IO_APIC
1111 if (vector == -1)
1112 return vector;
1114 apic_clear_isr(vector, apic);
1115 apic_update_ppr(apic);
1117 if (test_bit(vector, vcpu_to_synic(apic->vcpu)->vec_bitmap))
1118 kvm_hv_synic_send_eoi(apic->vcpu, vector);
1120 kvm_ioapic_send_eoi(apic, vector);
1121 kvm_make_request(KVM_REQ_EVENT, apic->vcpu);
1122 return vector;
1126 * this interface assumes a trap-like exit, which has already finished
1127 * desired side effect including vISR and vPPR update.
1129 void kvm_apic_set_eoi_accelerated(struct kvm_vcpu *vcpu, int vector)
1131 struct kvm_lapic *apic = vcpu->arch.apic;
1133 trace_kvm_eoi(apic, vector);
1135 kvm_ioapic_send_eoi(apic, vector);
1136 kvm_make_request(KVM_REQ_EVENT, apic->vcpu);
1138 EXPORT_SYMBOL_GPL(kvm_apic_set_eoi_accelerated);
1140 static void apic_send_ipi(struct kvm_lapic *apic)
1142 u32 icr_low = kvm_lapic_get_reg(apic, APIC_ICR);
1143 u32 icr_high = kvm_lapic_get_reg(apic, APIC_ICR2);
1144 struct kvm_lapic_irq irq;
1146 irq.vector = icr_low & APIC_VECTOR_MASK;
1147 irq.delivery_mode = icr_low & APIC_MODE_MASK;
1148 irq.dest_mode = icr_low & APIC_DEST_MASK;
1149 irq.level = (icr_low & APIC_INT_ASSERT) != 0;
1150 irq.trig_mode = icr_low & APIC_INT_LEVELTRIG;
1151 irq.shorthand = icr_low & APIC_SHORT_MASK;
1152 irq.msi_redir_hint = false;
1153 if (apic_x2apic_mode(apic))
1154 irq.dest_id = icr_high;
1155 else
1156 irq.dest_id = GET_APIC_DEST_FIELD(icr_high);
1158 trace_kvm_apic_ipi(icr_low, irq.dest_id);
1160 apic_debug("icr_high 0x%x, icr_low 0x%x, "
1161 "short_hand 0x%x, dest 0x%x, trig_mode 0x%x, level 0x%x, "
1162 "dest_mode 0x%x, delivery_mode 0x%x, vector 0x%x, "
1163 "msi_redir_hint 0x%x\n",
1164 icr_high, icr_low, irq.shorthand, irq.dest_id,
1165 irq.trig_mode, irq.level, irq.dest_mode, irq.delivery_mode,
1166 irq.vector, irq.msi_redir_hint);
1168 kvm_irq_delivery_to_apic(apic->vcpu->kvm, apic, &irq, NULL);
1171 static u32 apic_get_tmcct(struct kvm_lapic *apic)
1173 ktime_t remaining, now;
1174 s64 ns;
1175 u32 tmcct;
1177 ASSERT(apic != NULL);
1179 /* if initial count is 0, current count should also be 0 */
1180 if (kvm_lapic_get_reg(apic, APIC_TMICT) == 0 ||
1181 apic->lapic_timer.period == 0)
1182 return 0;
1184 now = ktime_get();
1185 remaining = ktime_sub(apic->lapic_timer.target_expiration, now);
1186 if (ktime_to_ns(remaining) < 0)
1187 remaining = 0;
1189 ns = mod_64(ktime_to_ns(remaining), apic->lapic_timer.period);
1190 tmcct = div64_u64(ns,
1191 (APIC_BUS_CYCLE_NS * apic->divide_count));
1193 return tmcct;
1196 static void __report_tpr_access(struct kvm_lapic *apic, bool write)
1198 struct kvm_vcpu *vcpu = apic->vcpu;
1199 struct kvm_run *run = vcpu->run;
1201 kvm_make_request(KVM_REQ_REPORT_TPR_ACCESS, vcpu);
1202 run->tpr_access.rip = kvm_rip_read(vcpu);
1203 run->tpr_access.is_write = write;
1206 static inline void report_tpr_access(struct kvm_lapic *apic, bool write)
1208 if (apic->vcpu->arch.tpr_access_reporting)
1209 __report_tpr_access(apic, write);
1212 static u32 __apic_read(struct kvm_lapic *apic, unsigned int offset)
1214 u32 val = 0;
1216 if (offset >= LAPIC_MMIO_LENGTH)
1217 return 0;
1219 switch (offset) {
1220 case APIC_ARBPRI:
1221 apic_debug("Access APIC ARBPRI register which is for P6\n");
1222 break;
1224 case APIC_TMCCT: /* Timer CCR */
1225 if (apic_lvtt_tscdeadline(apic))
1226 return 0;
1228 val = apic_get_tmcct(apic);
1229 break;
1230 case APIC_PROCPRI:
1231 apic_update_ppr(apic);
1232 val = kvm_lapic_get_reg(apic, offset);
1233 break;
1234 case APIC_TASKPRI:
1235 report_tpr_access(apic, false);
1236 /* fall thru */
1237 default:
1238 val = kvm_lapic_get_reg(apic, offset);
1239 break;
1242 return val;
1245 static inline struct kvm_lapic *to_lapic(struct kvm_io_device *dev)
1247 return container_of(dev, struct kvm_lapic, dev);
1250 int kvm_lapic_reg_read(struct kvm_lapic *apic, u32 offset, int len,
1251 void *data)
1253 unsigned char alignment = offset & 0xf;
1254 u32 result;
1255 /* this bitmask has a bit cleared for each reserved register */
1256 static const u64 rmask = 0x43ff01ffffffe70cULL;
1258 if ((alignment + len) > 4) {
1259 apic_debug("KVM_APIC_READ: alignment error %x %d\n",
1260 offset, len);
1261 return 1;
1264 if (offset > 0x3f0 || !(rmask & (1ULL << (offset >> 4)))) {
1265 apic_debug("KVM_APIC_READ: read reserved register %x\n",
1266 offset);
1267 return 1;
1270 result = __apic_read(apic, offset & ~0xf);
1272 trace_kvm_apic_read(offset, result);
1274 switch (len) {
1275 case 1:
1276 case 2:
1277 case 4:
1278 memcpy(data, (char *)&result + alignment, len);
1279 break;
1280 default:
1281 printk(KERN_ERR "Local APIC read with len = %x, "
1282 "should be 1,2, or 4 instead\n", len);
1283 break;
1285 return 0;
1287 EXPORT_SYMBOL_GPL(kvm_lapic_reg_read);
1289 static int apic_mmio_in_range(struct kvm_lapic *apic, gpa_t addr)
1291 return addr >= apic->base_address &&
1292 addr < apic->base_address + LAPIC_MMIO_LENGTH;
1295 static int apic_mmio_read(struct kvm_vcpu *vcpu, struct kvm_io_device *this,
1296 gpa_t address, int len, void *data)
1298 struct kvm_lapic *apic = to_lapic(this);
1299 u32 offset = address - apic->base_address;
1301 if (!apic_mmio_in_range(apic, address))
1302 return -EOPNOTSUPP;
1304 if (!kvm_apic_hw_enabled(apic) || apic_x2apic_mode(apic)) {
1305 if (!kvm_check_has_quirk(vcpu->kvm,
1306 KVM_X86_QUIRK_LAPIC_MMIO_HOLE))
1307 return -EOPNOTSUPP;
1309 memset(data, 0xff, len);
1310 return 0;
1313 kvm_lapic_reg_read(apic, offset, len, data);
1315 return 0;
1318 static void update_divide_count(struct kvm_lapic *apic)
1320 u32 tmp1, tmp2, tdcr;
1322 tdcr = kvm_lapic_get_reg(apic, APIC_TDCR);
1323 tmp1 = tdcr & 0xf;
1324 tmp2 = ((tmp1 & 0x3) | ((tmp1 & 0x8) >> 1)) + 1;
1325 apic->divide_count = 0x1 << (tmp2 & 0x7);
1327 apic_debug("timer divide count is 0x%x\n",
1328 apic->divide_count);
1331 static void apic_update_lvtt(struct kvm_lapic *apic)
1333 u32 timer_mode = kvm_lapic_get_reg(apic, APIC_LVTT) &
1334 apic->lapic_timer.timer_mode_mask;
1336 if (apic->lapic_timer.timer_mode != timer_mode) {
1337 apic->lapic_timer.timer_mode = timer_mode;
1338 hrtimer_cancel(&apic->lapic_timer.timer);
1342 static void apic_timer_expired(struct kvm_lapic *apic)
1344 struct kvm_vcpu *vcpu = apic->vcpu;
1345 struct swait_queue_head *q = &vcpu->wq;
1346 struct kvm_timer *ktimer = &apic->lapic_timer;
1348 if (atomic_read(&apic->lapic_timer.pending))
1349 return;
1351 atomic_inc(&apic->lapic_timer.pending);
1352 kvm_set_pending_timer(vcpu);
1355 * For x86, the atomic_inc() is serialized, thus
1356 * using swait_active() is safe.
1358 if (swait_active(q))
1359 swake_up(q);
1361 if (apic_lvtt_tscdeadline(apic))
1362 ktimer->expired_tscdeadline = ktimer->tscdeadline;
1366 * On APICv, this test will cause a busy wait
1367 * during a higher-priority task.
1370 static bool lapic_timer_int_injected(struct kvm_vcpu *vcpu)
1372 struct kvm_lapic *apic = vcpu->arch.apic;
1373 u32 reg = kvm_lapic_get_reg(apic, APIC_LVTT);
1375 if (kvm_apic_hw_enabled(apic)) {
1376 int vec = reg & APIC_VECTOR_MASK;
1377 void *bitmap = apic->regs + APIC_ISR;
1379 if (vcpu->arch.apicv_active)
1380 bitmap = apic->regs + APIC_IRR;
1382 if (apic_test_vector(vec, bitmap))
1383 return true;
1385 return false;
1388 void wait_lapic_expire(struct kvm_vcpu *vcpu)
1390 struct kvm_lapic *apic = vcpu->arch.apic;
1391 u64 guest_tsc, tsc_deadline;
1393 if (!lapic_in_kernel(vcpu))
1394 return;
1396 if (apic->lapic_timer.expired_tscdeadline == 0)
1397 return;
1399 if (!lapic_timer_int_injected(vcpu))
1400 return;
1402 tsc_deadline = apic->lapic_timer.expired_tscdeadline;
1403 apic->lapic_timer.expired_tscdeadline = 0;
1404 guest_tsc = kvm_read_l1_tsc(vcpu, rdtsc());
1405 trace_kvm_wait_lapic_expire(vcpu->vcpu_id, guest_tsc - tsc_deadline);
1407 /* __delay is delay_tsc whenever the hardware has TSC, thus always. */
1408 if (guest_tsc < tsc_deadline)
1409 __delay(min(tsc_deadline - guest_tsc,
1410 nsec_to_cycles(vcpu, lapic_timer_advance_ns)));
1413 static void start_sw_tscdeadline(struct kvm_lapic *apic)
1415 u64 guest_tsc, tscdeadline = apic->lapic_timer.tscdeadline;
1416 u64 ns = 0;
1417 ktime_t expire;
1418 struct kvm_vcpu *vcpu = apic->vcpu;
1419 unsigned long this_tsc_khz = vcpu->arch.virtual_tsc_khz;
1420 unsigned long flags;
1421 ktime_t now;
1423 if (unlikely(!tscdeadline || !this_tsc_khz))
1424 return;
1426 local_irq_save(flags);
1428 now = ktime_get();
1429 guest_tsc = kvm_read_l1_tsc(vcpu, rdtsc());
1430 if (likely(tscdeadline > guest_tsc)) {
1431 ns = (tscdeadline - guest_tsc) * 1000000ULL;
1432 do_div(ns, this_tsc_khz);
1433 expire = ktime_add_ns(now, ns);
1434 expire = ktime_sub_ns(expire, lapic_timer_advance_ns);
1435 hrtimer_start(&apic->lapic_timer.timer,
1436 expire, HRTIMER_MODE_ABS_PINNED);
1437 } else
1438 apic_timer_expired(apic);
1440 local_irq_restore(flags);
1443 static bool set_target_expiration(struct kvm_lapic *apic)
1445 ktime_t now;
1446 u64 tscl = rdtsc();
1448 now = ktime_get();
1449 apic->lapic_timer.period = (u64)kvm_lapic_get_reg(apic, APIC_TMICT)
1450 * APIC_BUS_CYCLE_NS * apic->divide_count;
1452 if (!apic->lapic_timer.period)
1453 return false;
1456 * Do not allow the guest to program periodic timers with small
1457 * interval, since the hrtimers are not throttled by the host
1458 * scheduler.
1460 if (apic_lvtt_period(apic)) {
1461 s64 min_period = min_timer_period_us * 1000LL;
1463 if (apic->lapic_timer.period < min_period) {
1464 pr_info_ratelimited(
1465 "kvm: vcpu %i: requested %lld ns "
1466 "lapic timer period limited to %lld ns\n",
1467 apic->vcpu->vcpu_id,
1468 apic->lapic_timer.period, min_period);
1469 apic->lapic_timer.period = min_period;
1473 apic_debug("%s: bus cycle is %" PRId64 "ns, now 0x%016"
1474 PRIx64 ", "
1475 "timer initial count 0x%x, period %lldns, "
1476 "expire @ 0x%016" PRIx64 ".\n", __func__,
1477 APIC_BUS_CYCLE_NS, ktime_to_ns(now),
1478 kvm_lapic_get_reg(apic, APIC_TMICT),
1479 apic->lapic_timer.period,
1480 ktime_to_ns(ktime_add_ns(now,
1481 apic->lapic_timer.period)));
1483 apic->lapic_timer.tscdeadline = kvm_read_l1_tsc(apic->vcpu, tscl) +
1484 nsec_to_cycles(apic->vcpu, apic->lapic_timer.period);
1485 apic->lapic_timer.target_expiration = ktime_add_ns(now, apic->lapic_timer.period);
1487 return true;
1490 static void advance_periodic_target_expiration(struct kvm_lapic *apic)
1492 ktime_t now = ktime_get();
1493 u64 tscl = rdtsc();
1494 ktime_t delta;
1497 * Synchronize both deadlines to the same time source or
1498 * differences in the periods (caused by differences in the
1499 * underlying clocks or numerical approximation errors) will
1500 * cause the two to drift apart over time as the errors
1501 * accumulate.
1503 apic->lapic_timer.target_expiration =
1504 ktime_add_ns(apic->lapic_timer.target_expiration,
1505 apic->lapic_timer.period);
1506 delta = ktime_sub(apic->lapic_timer.target_expiration, now);
1507 apic->lapic_timer.tscdeadline = kvm_read_l1_tsc(apic->vcpu, tscl) +
1508 nsec_to_cycles(apic->vcpu, delta);
1511 static void start_sw_period(struct kvm_lapic *apic)
1513 if (!apic->lapic_timer.period)
1514 return;
1516 if (ktime_after(ktime_get(),
1517 apic->lapic_timer.target_expiration)) {
1518 apic_timer_expired(apic);
1520 if (apic_lvtt_oneshot(apic))
1521 return;
1523 advance_periodic_target_expiration(apic);
1526 hrtimer_start(&apic->lapic_timer.timer,
1527 apic->lapic_timer.target_expiration,
1528 HRTIMER_MODE_ABS_PINNED);
1531 bool kvm_lapic_hv_timer_in_use(struct kvm_vcpu *vcpu)
1533 if (!lapic_in_kernel(vcpu))
1534 return false;
1536 return vcpu->arch.apic->lapic_timer.hv_timer_in_use;
1538 EXPORT_SYMBOL_GPL(kvm_lapic_hv_timer_in_use);
1540 static void cancel_hv_timer(struct kvm_lapic *apic)
1542 WARN_ON(preemptible());
1543 WARN_ON(!apic->lapic_timer.hv_timer_in_use);
1544 kvm_x86_ops->cancel_hv_timer(apic->vcpu);
1545 apic->lapic_timer.hv_timer_in_use = false;
1548 static bool start_hv_timer(struct kvm_lapic *apic)
1550 struct kvm_timer *ktimer = &apic->lapic_timer;
1551 int r;
1553 WARN_ON(preemptible());
1554 if (!kvm_x86_ops->set_hv_timer)
1555 return false;
1557 if (!apic_lvtt_period(apic) && atomic_read(&ktimer->pending))
1558 return false;
1560 r = kvm_x86_ops->set_hv_timer(apic->vcpu, ktimer->tscdeadline);
1561 if (r < 0)
1562 return false;
1564 ktimer->hv_timer_in_use = true;
1565 hrtimer_cancel(&ktimer->timer);
1568 * Also recheck ktimer->pending, in case the sw timer triggered in
1569 * the window. For periodic timer, leave the hv timer running for
1570 * simplicity, and the deadline will be recomputed on the next vmexit.
1572 if (!apic_lvtt_period(apic) && (r || atomic_read(&ktimer->pending))) {
1573 if (r)
1574 apic_timer_expired(apic);
1575 return false;
1578 trace_kvm_hv_timer_state(apic->vcpu->vcpu_id, true);
1579 return true;
1582 static void start_sw_timer(struct kvm_lapic *apic)
1584 struct kvm_timer *ktimer = &apic->lapic_timer;
1586 WARN_ON(preemptible());
1587 if (apic->lapic_timer.hv_timer_in_use)
1588 cancel_hv_timer(apic);
1589 if (!apic_lvtt_period(apic) && atomic_read(&ktimer->pending))
1590 return;
1592 if (apic_lvtt_period(apic) || apic_lvtt_oneshot(apic))
1593 start_sw_period(apic);
1594 else if (apic_lvtt_tscdeadline(apic))
1595 start_sw_tscdeadline(apic);
1596 trace_kvm_hv_timer_state(apic->vcpu->vcpu_id, false);
1599 static void restart_apic_timer(struct kvm_lapic *apic)
1601 preempt_disable();
1602 if (!start_hv_timer(apic))
1603 start_sw_timer(apic);
1604 preempt_enable();
1607 void kvm_lapic_expired_hv_timer(struct kvm_vcpu *vcpu)
1609 struct kvm_lapic *apic = vcpu->arch.apic;
1611 preempt_disable();
1612 /* If the preempt notifier has already run, it also called apic_timer_expired */
1613 if (!apic->lapic_timer.hv_timer_in_use)
1614 goto out;
1615 WARN_ON(swait_active(&vcpu->wq));
1616 cancel_hv_timer(apic);
1617 apic_timer_expired(apic);
1619 if (apic_lvtt_period(apic) && apic->lapic_timer.period) {
1620 advance_periodic_target_expiration(apic);
1621 restart_apic_timer(apic);
1623 out:
1624 preempt_enable();
1626 EXPORT_SYMBOL_GPL(kvm_lapic_expired_hv_timer);
1628 void kvm_lapic_switch_to_hv_timer(struct kvm_vcpu *vcpu)
1630 restart_apic_timer(vcpu->arch.apic);
1632 EXPORT_SYMBOL_GPL(kvm_lapic_switch_to_hv_timer);
1634 void kvm_lapic_switch_to_sw_timer(struct kvm_vcpu *vcpu)
1636 struct kvm_lapic *apic = vcpu->arch.apic;
1638 preempt_disable();
1639 /* Possibly the TSC deadline timer is not enabled yet */
1640 if (apic->lapic_timer.hv_timer_in_use)
1641 start_sw_timer(apic);
1642 preempt_enable();
1644 EXPORT_SYMBOL_GPL(kvm_lapic_switch_to_sw_timer);
1646 void kvm_lapic_restart_hv_timer(struct kvm_vcpu *vcpu)
1648 struct kvm_lapic *apic = vcpu->arch.apic;
1650 WARN_ON(!apic->lapic_timer.hv_timer_in_use);
1651 restart_apic_timer(apic);
1654 static void start_apic_timer(struct kvm_lapic *apic)
1656 atomic_set(&apic->lapic_timer.pending, 0);
1658 if ((apic_lvtt_period(apic) || apic_lvtt_oneshot(apic))
1659 && !set_target_expiration(apic))
1660 return;
1662 restart_apic_timer(apic);
1665 static void apic_manage_nmi_watchdog(struct kvm_lapic *apic, u32 lvt0_val)
1667 bool lvt0_in_nmi_mode = apic_lvt_nmi_mode(lvt0_val);
1669 if (apic->lvt0_in_nmi_mode != lvt0_in_nmi_mode) {
1670 apic->lvt0_in_nmi_mode = lvt0_in_nmi_mode;
1671 if (lvt0_in_nmi_mode) {
1672 apic_debug("Receive NMI setting on APIC_LVT0 "
1673 "for cpu %d\n", apic->vcpu->vcpu_id);
1674 atomic_inc(&apic->vcpu->kvm->arch.vapics_in_nmi_mode);
1675 } else
1676 atomic_dec(&apic->vcpu->kvm->arch.vapics_in_nmi_mode);
1680 int kvm_lapic_reg_write(struct kvm_lapic *apic, u32 reg, u32 val)
1682 int ret = 0;
1684 trace_kvm_apic_write(reg, val);
1686 switch (reg) {
1687 case APIC_ID: /* Local APIC ID */
1688 if (!apic_x2apic_mode(apic))
1689 kvm_apic_set_xapic_id(apic, val >> 24);
1690 else
1691 ret = 1;
1692 break;
1694 case APIC_TASKPRI:
1695 report_tpr_access(apic, true);
1696 apic_set_tpr(apic, val & 0xff);
1697 break;
1699 case APIC_EOI:
1700 apic_set_eoi(apic);
1701 break;
1703 case APIC_LDR:
1704 if (!apic_x2apic_mode(apic))
1705 kvm_apic_set_ldr(apic, val & APIC_LDR_MASK);
1706 else
1707 ret = 1;
1708 break;
1710 case APIC_DFR:
1711 if (!apic_x2apic_mode(apic)) {
1712 kvm_lapic_set_reg(apic, APIC_DFR, val | 0x0FFFFFFF);
1713 recalculate_apic_map(apic->vcpu->kvm);
1714 } else
1715 ret = 1;
1716 break;
1718 case APIC_SPIV: {
1719 u32 mask = 0x3ff;
1720 if (kvm_lapic_get_reg(apic, APIC_LVR) & APIC_LVR_DIRECTED_EOI)
1721 mask |= APIC_SPIV_DIRECTED_EOI;
1722 apic_set_spiv(apic, val & mask);
1723 if (!(val & APIC_SPIV_APIC_ENABLED)) {
1724 int i;
1725 u32 lvt_val;
1727 for (i = 0; i < KVM_APIC_LVT_NUM; i++) {
1728 lvt_val = kvm_lapic_get_reg(apic,
1729 APIC_LVTT + 0x10 * i);
1730 kvm_lapic_set_reg(apic, APIC_LVTT + 0x10 * i,
1731 lvt_val | APIC_LVT_MASKED);
1733 apic_update_lvtt(apic);
1734 atomic_set(&apic->lapic_timer.pending, 0);
1737 break;
1739 case APIC_ICR:
1740 /* No delay here, so we always clear the pending bit */
1741 kvm_lapic_set_reg(apic, APIC_ICR, val & ~(1 << 12));
1742 apic_send_ipi(apic);
1743 break;
1745 case APIC_ICR2:
1746 if (!apic_x2apic_mode(apic))
1747 val &= 0xff000000;
1748 kvm_lapic_set_reg(apic, APIC_ICR2, val);
1749 break;
1751 case APIC_LVT0:
1752 apic_manage_nmi_watchdog(apic, val);
1753 case APIC_LVTTHMR:
1754 case APIC_LVTPC:
1755 case APIC_LVT1:
1756 case APIC_LVTERR: {
1757 /* TODO: Check vector */
1758 size_t size;
1759 u32 index;
1761 if (!kvm_apic_sw_enabled(apic))
1762 val |= APIC_LVT_MASKED;
1763 size = ARRAY_SIZE(apic_lvt_mask);
1764 index = array_index_nospec(
1765 (reg - APIC_LVTT) >> 4, size);
1766 val &= apic_lvt_mask[index];
1767 kvm_lapic_set_reg(apic, reg, val);
1768 break;
1771 case APIC_LVTT:
1772 if (!kvm_apic_sw_enabled(apic))
1773 val |= APIC_LVT_MASKED;
1774 val &= (apic_lvt_mask[0] | apic->lapic_timer.timer_mode_mask);
1775 kvm_lapic_set_reg(apic, APIC_LVTT, val);
1776 apic_update_lvtt(apic);
1777 break;
1779 case APIC_TMICT:
1780 if (apic_lvtt_tscdeadline(apic))
1781 break;
1783 hrtimer_cancel(&apic->lapic_timer.timer);
1784 kvm_lapic_set_reg(apic, APIC_TMICT, val);
1785 start_apic_timer(apic);
1786 break;
1788 case APIC_TDCR:
1789 if (val & 4)
1790 apic_debug("KVM_WRITE:TDCR %x\n", val);
1791 kvm_lapic_set_reg(apic, APIC_TDCR, val);
1792 update_divide_count(apic);
1793 break;
1795 case APIC_ESR:
1796 if (apic_x2apic_mode(apic) && val != 0) {
1797 apic_debug("KVM_WRITE:ESR not zero %x\n", val);
1798 ret = 1;
1800 break;
1802 case APIC_SELF_IPI:
1803 if (apic_x2apic_mode(apic)) {
1804 kvm_lapic_reg_write(apic, APIC_ICR, 0x40000 | (val & 0xff));
1805 } else
1806 ret = 1;
1807 break;
1808 default:
1809 ret = 1;
1810 break;
1812 if (ret)
1813 apic_debug("Local APIC Write to read-only register %x\n", reg);
1814 return ret;
1816 EXPORT_SYMBOL_GPL(kvm_lapic_reg_write);
1818 static int apic_mmio_write(struct kvm_vcpu *vcpu, struct kvm_io_device *this,
1819 gpa_t address, int len, const void *data)
1821 struct kvm_lapic *apic = to_lapic(this);
1822 unsigned int offset = address - apic->base_address;
1823 u32 val;
1825 if (!apic_mmio_in_range(apic, address))
1826 return -EOPNOTSUPP;
1828 if (!kvm_apic_hw_enabled(apic) || apic_x2apic_mode(apic)) {
1829 if (!kvm_check_has_quirk(vcpu->kvm,
1830 KVM_X86_QUIRK_LAPIC_MMIO_HOLE))
1831 return -EOPNOTSUPP;
1833 return 0;
1837 * APIC register must be aligned on 128-bits boundary.
1838 * 32/64/128 bits registers must be accessed thru 32 bits.
1839 * Refer SDM 8.4.1
1841 if (len != 4 || (offset & 0xf)) {
1842 /* Don't shout loud, $infamous_os would cause only noise. */
1843 apic_debug("apic write: bad size=%d %lx\n", len, (long)address);
1844 return 0;
1847 val = *(u32*)data;
1849 /* too common printing */
1850 if (offset != APIC_EOI)
1851 apic_debug("%s: offset 0x%x with length 0x%x, and value is "
1852 "0x%x\n", __func__, offset, len, val);
1854 kvm_lapic_reg_write(apic, offset & 0xff0, val);
1856 return 0;
1859 void kvm_lapic_set_eoi(struct kvm_vcpu *vcpu)
1861 kvm_lapic_reg_write(vcpu->arch.apic, APIC_EOI, 0);
1863 EXPORT_SYMBOL_GPL(kvm_lapic_set_eoi);
1865 /* emulate APIC access in a trap manner */
1866 void kvm_apic_write_nodecode(struct kvm_vcpu *vcpu, u32 offset)
1868 u32 val = 0;
1870 /* hw has done the conditional check and inst decode */
1871 offset &= 0xff0;
1873 kvm_lapic_reg_read(vcpu->arch.apic, offset, 4, &val);
1875 /* TODO: optimize to just emulate side effect w/o one more write */
1876 kvm_lapic_reg_write(vcpu->arch.apic, offset, val);
1878 EXPORT_SYMBOL_GPL(kvm_apic_write_nodecode);
1880 void kvm_free_lapic(struct kvm_vcpu *vcpu)
1882 struct kvm_lapic *apic = vcpu->arch.apic;
1884 if (!vcpu->arch.apic)
1885 return;
1887 hrtimer_cancel(&apic->lapic_timer.timer);
1889 if (!(vcpu->arch.apic_base & MSR_IA32_APICBASE_ENABLE))
1890 static_key_slow_dec_deferred(&apic_hw_disabled);
1892 if (!apic->sw_enabled)
1893 static_key_slow_dec_deferred(&apic_sw_disabled);
1895 if (apic->regs)
1896 free_page((unsigned long)apic->regs);
1898 kfree(apic);
1902 *----------------------------------------------------------------------
1903 * LAPIC interface
1904 *----------------------------------------------------------------------
1906 u64 kvm_get_lapic_tscdeadline_msr(struct kvm_vcpu *vcpu)
1908 struct kvm_lapic *apic = vcpu->arch.apic;
1910 if (!lapic_in_kernel(vcpu) ||
1911 !apic_lvtt_tscdeadline(apic))
1912 return 0;
1914 return apic->lapic_timer.tscdeadline;
1917 void kvm_set_lapic_tscdeadline_msr(struct kvm_vcpu *vcpu, u64 data)
1919 struct kvm_lapic *apic = vcpu->arch.apic;
1921 if (!kvm_apic_present(vcpu) || apic_lvtt_oneshot(apic) ||
1922 apic_lvtt_period(apic))
1923 return;
1925 hrtimer_cancel(&apic->lapic_timer.timer);
1926 apic->lapic_timer.tscdeadline = data;
1927 start_apic_timer(apic);
1930 void kvm_lapic_set_tpr(struct kvm_vcpu *vcpu, unsigned long cr8)
1932 struct kvm_lapic *apic = vcpu->arch.apic;
1934 apic_set_tpr(apic, ((cr8 & 0x0f) << 4)
1935 | (kvm_lapic_get_reg(apic, APIC_TASKPRI) & 4));
1938 u64 kvm_lapic_get_cr8(struct kvm_vcpu *vcpu)
1940 u64 tpr;
1942 tpr = (u64) kvm_lapic_get_reg(vcpu->arch.apic, APIC_TASKPRI);
1944 return (tpr & 0xf0) >> 4;
1947 void kvm_lapic_set_base(struct kvm_vcpu *vcpu, u64 value)
1949 u64 old_value = vcpu->arch.apic_base;
1950 struct kvm_lapic *apic = vcpu->arch.apic;
1952 if (!apic)
1953 value |= MSR_IA32_APICBASE_BSP;
1955 vcpu->arch.apic_base = value;
1957 if ((old_value ^ value) & MSR_IA32_APICBASE_ENABLE)
1958 kvm_update_cpuid(vcpu);
1960 if (!apic)
1961 return;
1963 /* update jump label if enable bit changes */
1964 if ((old_value ^ value) & MSR_IA32_APICBASE_ENABLE) {
1965 if (value & MSR_IA32_APICBASE_ENABLE) {
1966 kvm_apic_set_xapic_id(apic, vcpu->vcpu_id);
1967 static_key_slow_dec_deferred(&apic_hw_disabled);
1968 } else {
1969 static_key_slow_inc(&apic_hw_disabled.key);
1970 recalculate_apic_map(vcpu->kvm);
1974 if (((old_value ^ value) & X2APIC_ENABLE) && (value & X2APIC_ENABLE))
1975 kvm_apic_set_x2apic_id(apic, vcpu->vcpu_id);
1977 if ((old_value ^ value) & (MSR_IA32_APICBASE_ENABLE | X2APIC_ENABLE))
1978 kvm_x86_ops->set_virtual_apic_mode(vcpu);
1980 apic->base_address = apic->vcpu->arch.apic_base &
1981 MSR_IA32_APICBASE_BASE;
1983 if ((value & MSR_IA32_APICBASE_ENABLE) &&
1984 apic->base_address != APIC_DEFAULT_PHYS_BASE)
1985 pr_warn_once("APIC base relocation is unsupported by KVM");
1987 /* with FSB delivery interrupt, we can restart APIC functionality */
1988 apic_debug("apic base msr is 0x%016" PRIx64 ", and base address is "
1989 "0x%lx.\n", apic->vcpu->arch.apic_base, apic->base_address);
1993 void kvm_lapic_reset(struct kvm_vcpu *vcpu, bool init_event)
1995 struct kvm_lapic *apic = vcpu->arch.apic;
1996 int i;
1998 if (!apic)
1999 return;
2001 apic_debug("%s\n", __func__);
2003 /* Stop the timer in case it's a reset to an active apic */
2004 hrtimer_cancel(&apic->lapic_timer.timer);
2006 if (!init_event) {
2007 kvm_lapic_set_base(vcpu, APIC_DEFAULT_PHYS_BASE |
2008 MSR_IA32_APICBASE_ENABLE);
2009 kvm_apic_set_xapic_id(apic, vcpu->vcpu_id);
2011 kvm_apic_set_version(apic->vcpu);
2013 for (i = 0; i < KVM_APIC_LVT_NUM; i++)
2014 kvm_lapic_set_reg(apic, APIC_LVTT + 0x10 * i, APIC_LVT_MASKED);
2015 apic_update_lvtt(apic);
2016 if (kvm_vcpu_is_reset_bsp(vcpu) &&
2017 kvm_check_has_quirk(vcpu->kvm, KVM_X86_QUIRK_LINT0_REENABLED))
2018 kvm_lapic_set_reg(apic, APIC_LVT0,
2019 SET_APIC_DELIVERY_MODE(0, APIC_MODE_EXTINT));
2020 apic_manage_nmi_watchdog(apic, kvm_lapic_get_reg(apic, APIC_LVT0));
2022 kvm_lapic_set_reg(apic, APIC_DFR, 0xffffffffU);
2023 apic_set_spiv(apic, 0xff);
2024 kvm_lapic_set_reg(apic, APIC_TASKPRI, 0);
2025 if (!apic_x2apic_mode(apic))
2026 kvm_apic_set_ldr(apic, 0);
2027 kvm_lapic_set_reg(apic, APIC_ESR, 0);
2028 kvm_lapic_set_reg(apic, APIC_ICR, 0);
2029 kvm_lapic_set_reg(apic, APIC_ICR2, 0);
2030 kvm_lapic_set_reg(apic, APIC_TDCR, 0);
2031 kvm_lapic_set_reg(apic, APIC_TMICT, 0);
2032 for (i = 0; i < 8; i++) {
2033 kvm_lapic_set_reg(apic, APIC_IRR + 0x10 * i, 0);
2034 kvm_lapic_set_reg(apic, APIC_ISR + 0x10 * i, 0);
2035 kvm_lapic_set_reg(apic, APIC_TMR + 0x10 * i, 0);
2037 apic->irr_pending = vcpu->arch.apicv_active;
2038 apic->isr_count = vcpu->arch.apicv_active ? 1 : 0;
2039 apic->highest_isr_cache = -1;
2040 update_divide_count(apic);
2041 atomic_set(&apic->lapic_timer.pending, 0);
2042 if (kvm_vcpu_is_bsp(vcpu))
2043 kvm_lapic_set_base(vcpu,
2044 vcpu->arch.apic_base | MSR_IA32_APICBASE_BSP);
2045 vcpu->arch.pv_eoi.msr_val = 0;
2046 apic_update_ppr(apic);
2047 if (vcpu->arch.apicv_active) {
2048 kvm_x86_ops->apicv_post_state_restore(vcpu);
2049 kvm_x86_ops->hwapic_irr_update(vcpu, -1);
2050 kvm_x86_ops->hwapic_isr_update(vcpu, -1);
2053 vcpu->arch.apic_arb_prio = 0;
2054 vcpu->arch.apic_attention = 0;
2056 apic_debug("%s: vcpu=%p, id=0x%x, base_msr="
2057 "0x%016" PRIx64 ", base_address=0x%0lx.\n", __func__,
2058 vcpu, kvm_lapic_get_reg(apic, APIC_ID),
2059 vcpu->arch.apic_base, apic->base_address);
2063 *----------------------------------------------------------------------
2064 * timer interface
2065 *----------------------------------------------------------------------
2068 static bool lapic_is_periodic(struct kvm_lapic *apic)
2070 return apic_lvtt_period(apic);
2073 int apic_has_pending_timer(struct kvm_vcpu *vcpu)
2075 struct kvm_lapic *apic = vcpu->arch.apic;
2077 if (apic_enabled(apic) && apic_lvt_enabled(apic, APIC_LVTT))
2078 return atomic_read(&apic->lapic_timer.pending);
2080 return 0;
2083 int kvm_apic_local_deliver(struct kvm_lapic *apic, int lvt_type)
2085 u32 reg = kvm_lapic_get_reg(apic, lvt_type);
2086 int vector, mode, trig_mode;
2088 if (kvm_apic_hw_enabled(apic) && !(reg & APIC_LVT_MASKED)) {
2089 vector = reg & APIC_VECTOR_MASK;
2090 mode = reg & APIC_MODE_MASK;
2091 trig_mode = reg & APIC_LVT_LEVEL_TRIGGER;
2092 return __apic_accept_irq(apic, mode, vector, 1, trig_mode,
2093 NULL);
2095 return 0;
2098 void kvm_apic_nmi_wd_deliver(struct kvm_vcpu *vcpu)
2100 struct kvm_lapic *apic = vcpu->arch.apic;
2102 if (apic)
2103 kvm_apic_local_deliver(apic, APIC_LVT0);
2106 static const struct kvm_io_device_ops apic_mmio_ops = {
2107 .read = apic_mmio_read,
2108 .write = apic_mmio_write,
2111 static enum hrtimer_restart apic_timer_fn(struct hrtimer *data)
2113 struct kvm_timer *ktimer = container_of(data, struct kvm_timer, timer);
2114 struct kvm_lapic *apic = container_of(ktimer, struct kvm_lapic, lapic_timer);
2116 apic_timer_expired(apic);
2118 if (lapic_is_periodic(apic)) {
2119 advance_periodic_target_expiration(apic);
2120 hrtimer_add_expires_ns(&ktimer->timer, ktimer->period);
2121 return HRTIMER_RESTART;
2122 } else
2123 return HRTIMER_NORESTART;
2126 int kvm_create_lapic(struct kvm_vcpu *vcpu)
2128 struct kvm_lapic *apic;
2130 ASSERT(vcpu != NULL);
2131 apic_debug("apic_init %d\n", vcpu->vcpu_id);
2133 apic = kzalloc(sizeof(*apic), GFP_KERNEL);
2134 if (!apic)
2135 goto nomem;
2137 vcpu->arch.apic = apic;
2139 apic->regs = (void *)get_zeroed_page(GFP_KERNEL);
2140 if (!apic->regs) {
2141 printk(KERN_ERR "malloc apic regs error for vcpu %x\n",
2142 vcpu->vcpu_id);
2143 goto nomem_free_apic;
2145 apic->vcpu = vcpu;
2147 hrtimer_init(&apic->lapic_timer.timer, CLOCK_MONOTONIC,
2148 HRTIMER_MODE_ABS_PINNED);
2149 apic->lapic_timer.timer.function = apic_timer_fn;
2152 * APIC is created enabled. This will prevent kvm_lapic_set_base from
2153 * thinking that APIC satet has changed.
2155 vcpu->arch.apic_base = MSR_IA32_APICBASE_ENABLE;
2156 static_key_slow_inc(&apic_sw_disabled.key); /* sw disabled at reset */
2157 kvm_iodevice_init(&apic->dev, &apic_mmio_ops);
2159 return 0;
2160 nomem_free_apic:
2161 kfree(apic);
2162 nomem:
2163 return -ENOMEM;
2166 int kvm_apic_has_interrupt(struct kvm_vcpu *vcpu)
2168 struct kvm_lapic *apic = vcpu->arch.apic;
2169 u32 ppr;
2171 if (!kvm_apic_hw_enabled(apic))
2172 return -1;
2174 __apic_update_ppr(apic, &ppr);
2175 return apic_has_interrupt_for_ppr(apic, ppr);
2178 int kvm_apic_accept_pic_intr(struct kvm_vcpu *vcpu)
2180 u32 lvt0 = kvm_lapic_get_reg(vcpu->arch.apic, APIC_LVT0);
2181 int r = 0;
2183 if (!kvm_apic_hw_enabled(vcpu->arch.apic))
2184 r = 1;
2185 if ((lvt0 & APIC_LVT_MASKED) == 0 &&
2186 GET_APIC_DELIVERY_MODE(lvt0) == APIC_MODE_EXTINT)
2187 r = 1;
2188 return r;
2191 void kvm_inject_apic_timer_irqs(struct kvm_vcpu *vcpu)
2193 struct kvm_lapic *apic = vcpu->arch.apic;
2195 if (atomic_read(&apic->lapic_timer.pending) > 0) {
2196 kvm_apic_local_deliver(apic, APIC_LVTT);
2197 if (apic_lvtt_tscdeadline(apic))
2198 apic->lapic_timer.tscdeadline = 0;
2199 if (apic_lvtt_oneshot(apic)) {
2200 apic->lapic_timer.tscdeadline = 0;
2201 apic->lapic_timer.target_expiration = 0;
2203 atomic_set(&apic->lapic_timer.pending, 0);
2207 int kvm_get_apic_interrupt(struct kvm_vcpu *vcpu)
2209 int vector = kvm_apic_has_interrupt(vcpu);
2210 struct kvm_lapic *apic = vcpu->arch.apic;
2211 u32 ppr;
2213 if (vector == -1)
2214 return -1;
2217 * We get here even with APIC virtualization enabled, if doing
2218 * nested virtualization and L1 runs with the "acknowledge interrupt
2219 * on exit" mode. Then we cannot inject the interrupt via RVI,
2220 * because the process would deliver it through the IDT.
2223 apic_clear_irr(vector, apic);
2224 if (test_bit(vector, vcpu_to_synic(vcpu)->auto_eoi_bitmap)) {
2226 * For auto-EOI interrupts, there might be another pending
2227 * interrupt above PPR, so check whether to raise another
2228 * KVM_REQ_EVENT.
2230 apic_update_ppr(apic);
2231 } else {
2233 * For normal interrupts, PPR has been raised and there cannot
2234 * be a higher-priority pending interrupt---except if there was
2235 * a concurrent interrupt injection, but that would have
2236 * triggered KVM_REQ_EVENT already.
2238 apic_set_isr(vector, apic);
2239 __apic_update_ppr(apic, &ppr);
2242 return vector;
2245 static int kvm_apic_state_fixup(struct kvm_vcpu *vcpu,
2246 struct kvm_lapic_state *s, bool set)
2248 if (apic_x2apic_mode(vcpu->arch.apic)) {
2249 u32 *id = (u32 *)(s->regs + APIC_ID);
2250 u32 *ldr = (u32 *)(s->regs + APIC_LDR);
2252 if (vcpu->kvm->arch.x2apic_format) {
2253 if (*id != vcpu->vcpu_id)
2254 return -EINVAL;
2255 } else {
2256 if (set)
2257 *id >>= 24;
2258 else
2259 *id <<= 24;
2262 /* In x2APIC mode, the LDR is fixed and based on the id */
2263 if (set)
2264 *ldr = kvm_apic_calc_x2apic_ldr(*id);
2267 return 0;
2270 int kvm_apic_get_state(struct kvm_vcpu *vcpu, struct kvm_lapic_state *s)
2272 memcpy(s->regs, vcpu->arch.apic->regs, sizeof(*s));
2273 return kvm_apic_state_fixup(vcpu, s, false);
2276 int kvm_apic_set_state(struct kvm_vcpu *vcpu, struct kvm_lapic_state *s)
2278 struct kvm_lapic *apic = vcpu->arch.apic;
2279 int r;
2282 kvm_lapic_set_base(vcpu, vcpu->arch.apic_base);
2283 /* set SPIV separately to get count of SW disabled APICs right */
2284 apic_set_spiv(apic, *((u32 *)(s->regs + APIC_SPIV)));
2286 r = kvm_apic_state_fixup(vcpu, s, true);
2287 if (r)
2288 return r;
2289 memcpy(vcpu->arch.apic->regs, s->regs, sizeof *s);
2291 recalculate_apic_map(vcpu->kvm);
2292 kvm_apic_set_version(vcpu);
2294 apic_update_ppr(apic);
2295 hrtimer_cancel(&apic->lapic_timer.timer);
2296 apic_update_lvtt(apic);
2297 apic_manage_nmi_watchdog(apic, kvm_lapic_get_reg(apic, APIC_LVT0));
2298 update_divide_count(apic);
2299 start_apic_timer(apic);
2300 apic->irr_pending = true;
2301 apic->isr_count = vcpu->arch.apicv_active ?
2302 1 : count_vectors(apic->regs + APIC_ISR);
2303 apic->highest_isr_cache = -1;
2304 if (vcpu->arch.apicv_active) {
2305 kvm_x86_ops->apicv_post_state_restore(vcpu);
2306 kvm_x86_ops->hwapic_irr_update(vcpu,
2307 apic_find_highest_irr(apic));
2308 kvm_x86_ops->hwapic_isr_update(vcpu,
2309 apic_find_highest_isr(apic));
2311 kvm_make_request(KVM_REQ_EVENT, vcpu);
2312 if (ioapic_in_kernel(vcpu->kvm))
2313 kvm_rtc_eoi_tracking_restore_one(vcpu);
2315 vcpu->arch.apic_arb_prio = 0;
2317 return 0;
2320 void __kvm_migrate_apic_timer(struct kvm_vcpu *vcpu)
2322 struct hrtimer *timer;
2324 if (!lapic_in_kernel(vcpu))
2325 return;
2327 timer = &vcpu->arch.apic->lapic_timer.timer;
2328 if (hrtimer_cancel(timer))
2329 hrtimer_start_expires(timer, HRTIMER_MODE_ABS_PINNED);
2333 * apic_sync_pv_eoi_from_guest - called on vmexit or cancel interrupt
2335 * Detect whether guest triggered PV EOI since the
2336 * last entry. If yes, set EOI on guests's behalf.
2337 * Clear PV EOI in guest memory in any case.
2339 static void apic_sync_pv_eoi_from_guest(struct kvm_vcpu *vcpu,
2340 struct kvm_lapic *apic)
2342 bool pending;
2343 int vector;
2345 * PV EOI state is derived from KVM_APIC_PV_EOI_PENDING in host
2346 * and KVM_PV_EOI_ENABLED in guest memory as follows:
2348 * KVM_APIC_PV_EOI_PENDING is unset:
2349 * -> host disabled PV EOI.
2350 * KVM_APIC_PV_EOI_PENDING is set, KVM_PV_EOI_ENABLED is set:
2351 * -> host enabled PV EOI, guest did not execute EOI yet.
2352 * KVM_APIC_PV_EOI_PENDING is set, KVM_PV_EOI_ENABLED is unset:
2353 * -> host enabled PV EOI, guest executed EOI.
2355 BUG_ON(!pv_eoi_enabled(vcpu));
2356 pending = pv_eoi_get_pending(vcpu);
2358 * Clear pending bit in any case: it will be set again on vmentry.
2359 * While this might not be ideal from performance point of view,
2360 * this makes sure pv eoi is only enabled when we know it's safe.
2362 pv_eoi_clr_pending(vcpu);
2363 if (pending)
2364 return;
2365 vector = apic_set_eoi(apic);
2366 trace_kvm_pv_eoi(apic, vector);
2369 void kvm_lapic_sync_from_vapic(struct kvm_vcpu *vcpu)
2371 u32 data;
2373 if (test_bit(KVM_APIC_PV_EOI_PENDING, &vcpu->arch.apic_attention))
2374 apic_sync_pv_eoi_from_guest(vcpu, vcpu->arch.apic);
2376 if (!test_bit(KVM_APIC_CHECK_VAPIC, &vcpu->arch.apic_attention))
2377 return;
2379 if (kvm_read_guest_cached(vcpu->kvm, &vcpu->arch.apic->vapic_cache, &data,
2380 sizeof(u32)))
2381 return;
2383 apic_set_tpr(vcpu->arch.apic, data & 0xff);
2387 * apic_sync_pv_eoi_to_guest - called before vmentry
2389 * Detect whether it's safe to enable PV EOI and
2390 * if yes do so.
2392 static void apic_sync_pv_eoi_to_guest(struct kvm_vcpu *vcpu,
2393 struct kvm_lapic *apic)
2395 if (!pv_eoi_enabled(vcpu) ||
2396 /* IRR set or many bits in ISR: could be nested. */
2397 apic->irr_pending ||
2398 /* Cache not set: could be safe but we don't bother. */
2399 apic->highest_isr_cache == -1 ||
2400 /* Need EOI to update ioapic. */
2401 kvm_ioapic_handles_vector(apic, apic->highest_isr_cache)) {
2403 * PV EOI was disabled by apic_sync_pv_eoi_from_guest
2404 * so we need not do anything here.
2406 return;
2409 pv_eoi_set_pending(apic->vcpu);
2412 void kvm_lapic_sync_to_vapic(struct kvm_vcpu *vcpu)
2414 u32 data, tpr;
2415 int max_irr, max_isr;
2416 struct kvm_lapic *apic = vcpu->arch.apic;
2418 apic_sync_pv_eoi_to_guest(vcpu, apic);
2420 if (!test_bit(KVM_APIC_CHECK_VAPIC, &vcpu->arch.apic_attention))
2421 return;
2423 tpr = kvm_lapic_get_reg(apic, APIC_TASKPRI) & 0xff;
2424 max_irr = apic_find_highest_irr(apic);
2425 if (max_irr < 0)
2426 max_irr = 0;
2427 max_isr = apic_find_highest_isr(apic);
2428 if (max_isr < 0)
2429 max_isr = 0;
2430 data = (tpr & 0xff) | ((max_isr & 0xf0) << 8) | (max_irr << 24);
2432 kvm_write_guest_cached(vcpu->kvm, &vcpu->arch.apic->vapic_cache, &data,
2433 sizeof(u32));
2436 int kvm_lapic_set_vapic_addr(struct kvm_vcpu *vcpu, gpa_t vapic_addr)
2438 if (vapic_addr) {
2439 if (kvm_gfn_to_hva_cache_init(vcpu->kvm,
2440 &vcpu->arch.apic->vapic_cache,
2441 vapic_addr, sizeof(u32)))
2442 return -EINVAL;
2443 __set_bit(KVM_APIC_CHECK_VAPIC, &vcpu->arch.apic_attention);
2444 } else {
2445 __clear_bit(KVM_APIC_CHECK_VAPIC, &vcpu->arch.apic_attention);
2448 vcpu->arch.apic->vapic_addr = vapic_addr;
2449 return 0;
2452 int kvm_x2apic_msr_write(struct kvm_vcpu *vcpu, u32 msr, u64 data)
2454 struct kvm_lapic *apic = vcpu->arch.apic;
2455 u32 reg = (msr - APIC_BASE_MSR) << 4;
2457 if (!lapic_in_kernel(vcpu) || !apic_x2apic_mode(apic))
2458 return 1;
2460 if (reg == APIC_ICR2)
2461 return 1;
2463 /* if this is ICR write vector before command */
2464 if (reg == APIC_ICR)
2465 kvm_lapic_reg_write(apic, APIC_ICR2, (u32)(data >> 32));
2466 return kvm_lapic_reg_write(apic, reg, (u32)data);
2469 int kvm_x2apic_msr_read(struct kvm_vcpu *vcpu, u32 msr, u64 *data)
2471 struct kvm_lapic *apic = vcpu->arch.apic;
2472 u32 reg = (msr - APIC_BASE_MSR) << 4, low, high = 0;
2474 if (!lapic_in_kernel(vcpu) || !apic_x2apic_mode(apic))
2475 return 1;
2477 if (reg == APIC_DFR || reg == APIC_ICR2) {
2478 apic_debug("KVM_APIC_READ: read x2apic reserved register %x\n",
2479 reg);
2480 return 1;
2483 if (kvm_lapic_reg_read(apic, reg, 4, &low))
2484 return 1;
2485 if (reg == APIC_ICR)
2486 kvm_lapic_reg_read(apic, APIC_ICR2, 4, &high);
2488 *data = (((u64)high) << 32) | low;
2490 return 0;
2493 int kvm_hv_vapic_msr_write(struct kvm_vcpu *vcpu, u32 reg, u64 data)
2495 struct kvm_lapic *apic = vcpu->arch.apic;
2497 if (!lapic_in_kernel(vcpu))
2498 return 1;
2500 /* if this is ICR write vector before command */
2501 if (reg == APIC_ICR)
2502 kvm_lapic_reg_write(apic, APIC_ICR2, (u32)(data >> 32));
2503 return kvm_lapic_reg_write(apic, reg, (u32)data);
2506 int kvm_hv_vapic_msr_read(struct kvm_vcpu *vcpu, u32 reg, u64 *data)
2508 struct kvm_lapic *apic = vcpu->arch.apic;
2509 u32 low, high = 0;
2511 if (!lapic_in_kernel(vcpu))
2512 return 1;
2514 if (kvm_lapic_reg_read(apic, reg, 4, &low))
2515 return 1;
2516 if (reg == APIC_ICR)
2517 kvm_lapic_reg_read(apic, APIC_ICR2, 4, &high);
2519 *data = (((u64)high) << 32) | low;
2521 return 0;
2524 int kvm_lapic_enable_pv_eoi(struct kvm_vcpu *vcpu, u64 data)
2526 u64 addr = data & ~KVM_MSR_ENABLED;
2527 if (!IS_ALIGNED(addr, 4))
2528 return 1;
2530 vcpu->arch.pv_eoi.msr_val = data;
2531 if (!pv_eoi_enabled(vcpu))
2532 return 0;
2533 return kvm_gfn_to_hva_cache_init(vcpu->kvm, &vcpu->arch.pv_eoi.data,
2534 addr, sizeof(u8));
2537 void kvm_apic_accept_events(struct kvm_vcpu *vcpu)
2539 struct kvm_lapic *apic = vcpu->arch.apic;
2540 u8 sipi_vector;
2541 unsigned long pe;
2543 if (!lapic_in_kernel(vcpu) || !apic->pending_events)
2544 return;
2547 * INITs are latched while in SMM. Because an SMM CPU cannot
2548 * be in KVM_MP_STATE_INIT_RECEIVED state, just eat SIPIs
2549 * and delay processing of INIT until the next RSM.
2551 if (is_smm(vcpu)) {
2552 WARN_ON_ONCE(vcpu->arch.mp_state == KVM_MP_STATE_INIT_RECEIVED);
2553 if (test_bit(KVM_APIC_SIPI, &apic->pending_events))
2554 clear_bit(KVM_APIC_SIPI, &apic->pending_events);
2555 return;
2558 pe = xchg(&apic->pending_events, 0);
2559 if (test_bit(KVM_APIC_INIT, &pe)) {
2560 kvm_vcpu_reset(vcpu, true);
2561 if (kvm_vcpu_is_bsp(apic->vcpu))
2562 vcpu->arch.mp_state = KVM_MP_STATE_RUNNABLE;
2563 else
2564 vcpu->arch.mp_state = KVM_MP_STATE_INIT_RECEIVED;
2566 if (test_bit(KVM_APIC_SIPI, &pe) &&
2567 vcpu->arch.mp_state == KVM_MP_STATE_INIT_RECEIVED) {
2568 /* evaluate pending_events before reading the vector */
2569 smp_rmb();
2570 sipi_vector = apic->sipi_vector;
2571 apic_debug("vcpu %d received sipi with vector # %x\n",
2572 vcpu->vcpu_id, sipi_vector);
2573 kvm_vcpu_deliver_sipi_vector(vcpu, sipi_vector);
2574 vcpu->arch.mp_state = KVM_MP_STATE_RUNNABLE;
2578 void kvm_lapic_init(void)
2580 /* do not patch jump label more than once per second */
2581 jump_label_rate_limit(&apic_hw_disabled, HZ);
2582 jump_label_rate_limit(&apic_sw_disabled, HZ);
2585 void kvm_lapic_exit(void)
2587 static_key_deferred_flush(&apic_hw_disabled);
2588 static_key_deferred_flush(&apic_sw_disabled);