1 // SPDX-License-Identifier: GPL-2.0-only
4 * Local APIC virtualization
6 * Copyright (C) 2006 Qumranet, Inc.
7 * Copyright (C) 2007 Novell
8 * Copyright (C) 2007 Intel
9 * Copyright 2009 Red Hat, Inc. and/or its affiliates.
12 * Dor Laor <dor.laor@qumranet.com>
13 * Gregory Haskins <ghaskins@novell.com>
14 * Yaozu (Eddie) Dong <eddie.dong@intel.com>
16 * Based on Xen 3.1 code, Copyright (c) 2004, Intel Corporation.
19 #include <linux/kvm_host.h>
20 #include <linux/kvm.h>
22 #include <linux/highmem.h>
23 #include <linux/smp.h>
24 #include <linux/hrtimer.h>
26 #include <linux/export.h>
27 #include <linux/math64.h>
28 #include <linux/slab.h>
29 #include <asm/processor.h>
32 #include <asm/current.h>
33 #include <asm/apicdef.h>
34 #include <asm/delay.h>
35 #include <linux/atomic.h>
36 #include <linux/jump_label.h>
37 #include "kvm_cache_regs.h"
45 #define mod_64(x, y) ((x) - (y) * div64_u64(x, y))
47 #define mod_64(x, y) ((x) % (y))
55 /* 14 is the version for Xeon and Pentium 8.4.8*/
56 #define APIC_VERSION (0x14UL | ((KVM_APIC_LVT_NUM - 1) << 16))
57 #define LAPIC_MMIO_LENGTH (1 << 12)
58 /* followed define is not in apicdef.h */
59 #define MAX_APIC_VECTOR 256
60 #define APIC_VECTORS_PER_REG 32
62 static bool lapic_timer_advance_dynamic __read_mostly;
63 #define LAPIC_TIMER_ADVANCE_ADJUST_MIN 100 /* clock cycles */
64 #define LAPIC_TIMER_ADVANCE_ADJUST_MAX 10000 /* clock cycles */
65 #define LAPIC_TIMER_ADVANCE_NS_INIT 1000
66 #define LAPIC_TIMER_ADVANCE_NS_MAX 5000
67 /* step-by-step approximation to mitigate fluctuation */
68 #define LAPIC_TIMER_ADVANCE_ADJUST_STEP 8
70 static inline int apic_test_vector(int vec, void *bitmap)
72 return test_bit(VEC_POS(vec), (bitmap) + REG_POS(vec));
75 bool kvm_apic_pending_eoi(struct kvm_vcpu *vcpu, int vector)
77 struct kvm_lapic *apic = vcpu->arch.apic;
79 return apic_test_vector(vector, apic->regs + APIC_ISR) ||
80 apic_test_vector(vector, apic->regs + APIC_IRR);
83 static inline int __apic_test_and_set_vector(int vec, void *bitmap)
85 return __test_and_set_bit(VEC_POS(vec), (bitmap) + REG_POS(vec));
88 static inline int __apic_test_and_clear_vector(int vec, void *bitmap)
90 return __test_and_clear_bit(VEC_POS(vec), (bitmap) + REG_POS(vec));
93 struct static_key_deferred apic_hw_disabled __read_mostly;
94 struct static_key_deferred apic_sw_disabled __read_mostly;
96 static inline int apic_enabled(struct kvm_lapic *apic)
98 return kvm_apic_sw_enabled(apic) && kvm_apic_hw_enabled(apic);
102 (APIC_LVT_MASKED | APIC_SEND_PENDING | APIC_VECTOR_MASK)
105 (LVT_MASK | APIC_MODE_MASK | APIC_INPUT_POLARITY | \
106 APIC_LVT_REMOTE_IRR | APIC_LVT_LEVEL_TRIGGER)
108 static inline u32 kvm_x2apic_id(struct kvm_lapic *apic)
110 return apic->vcpu->vcpu_id;
113 bool kvm_can_post_timer_interrupt(struct kvm_vcpu *vcpu)
115 return pi_inject_timer && kvm_vcpu_apicv_active(vcpu);
117 EXPORT_SYMBOL_GPL(kvm_can_post_timer_interrupt);
119 static bool kvm_use_posted_timer_interrupt(struct kvm_vcpu *vcpu)
121 return kvm_can_post_timer_interrupt(vcpu) && vcpu->mode == IN_GUEST_MODE;
124 static inline bool kvm_apic_map_get_logical_dest(struct kvm_apic_map *map,
125 u32 dest_id, struct kvm_lapic ***cluster, u16 *mask) {
127 case KVM_APIC_MODE_X2APIC: {
128 u32 offset = (dest_id >> 16) * 16;
129 u32 max_apic_id = map->max_apic_id;
131 if (offset <= max_apic_id) {
132 u8 cluster_size = min(max_apic_id - offset + 1, 16U);
134 offset = array_index_nospec(offset, map->max_apic_id + 1);
135 *cluster = &map->phys_map[offset];
136 *mask = dest_id & (0xffff >> (16 - cluster_size));
143 case KVM_APIC_MODE_XAPIC_FLAT:
144 *cluster = map->xapic_flat_map;
145 *mask = dest_id & 0xff;
147 case KVM_APIC_MODE_XAPIC_CLUSTER:
148 *cluster = map->xapic_cluster_map[(dest_id >> 4) & 0xf];
149 *mask = dest_id & 0xf;
157 static void kvm_apic_map_free(struct rcu_head *rcu)
159 struct kvm_apic_map *map = container_of(rcu, struct kvm_apic_map, rcu);
164 void kvm_recalculate_apic_map(struct kvm *kvm)
166 struct kvm_apic_map *new, *old = NULL;
167 struct kvm_vcpu *vcpu;
169 u32 max_id = 255; /* enough space for any xAPIC ID */
171 if (!kvm->arch.apic_map_dirty) {
173 * Read kvm->arch.apic_map_dirty before
180 mutex_lock(&kvm->arch.apic_map_lock);
181 if (!kvm->arch.apic_map_dirty) {
182 /* Someone else has updated the map. */
183 mutex_unlock(&kvm->arch.apic_map_lock);
187 kvm_for_each_vcpu(i, vcpu, kvm)
188 if (kvm_apic_present(vcpu))
189 max_id = max(max_id, kvm_x2apic_id(vcpu->arch.apic));
191 new = kvzalloc(sizeof(struct kvm_apic_map) +
192 sizeof(struct kvm_lapic *) * ((u64)max_id + 1),
198 new->max_apic_id = max_id;
200 kvm_for_each_vcpu(i, vcpu, kvm) {
201 struct kvm_lapic *apic = vcpu->arch.apic;
202 struct kvm_lapic **cluster;
208 if (!kvm_apic_present(vcpu))
211 xapic_id = kvm_xapic_id(apic);
212 x2apic_id = kvm_x2apic_id(apic);
214 /* Hotplug hack: see kvm_apic_match_physical_addr(), ... */
215 if ((apic_x2apic_mode(apic) || x2apic_id > 0xff) &&
216 x2apic_id <= new->max_apic_id)
217 new->phys_map[x2apic_id] = apic;
219 * ... xAPIC ID of VCPUs with APIC ID > 0xff will wrap-around,
220 * prevent them from masking VCPUs with APIC ID <= 0xff.
222 if (!apic_x2apic_mode(apic) && !new->phys_map[xapic_id])
223 new->phys_map[xapic_id] = apic;
225 if (!kvm_apic_sw_enabled(apic))
228 ldr = kvm_lapic_get_reg(apic, APIC_LDR);
230 if (apic_x2apic_mode(apic)) {
231 new->mode |= KVM_APIC_MODE_X2APIC;
233 ldr = GET_APIC_LOGICAL_ID(ldr);
234 if (kvm_lapic_get_reg(apic, APIC_DFR) == APIC_DFR_FLAT)
235 new->mode |= KVM_APIC_MODE_XAPIC_FLAT;
237 new->mode |= KVM_APIC_MODE_XAPIC_CLUSTER;
240 if (!kvm_apic_map_get_logical_dest(new, ldr, &cluster, &mask))
244 cluster[ffs(mask) - 1] = apic;
247 old = rcu_dereference_protected(kvm->arch.apic_map,
248 lockdep_is_held(&kvm->arch.apic_map_lock));
249 rcu_assign_pointer(kvm->arch.apic_map, new);
251 * Write kvm->arch.apic_map before
252 * clearing apic->apic_map_dirty
255 kvm->arch.apic_map_dirty = false;
256 mutex_unlock(&kvm->arch.apic_map_lock);
259 call_rcu(&old->rcu, kvm_apic_map_free);
261 kvm_make_scan_ioapic_request(kvm);
264 static inline void apic_set_spiv(struct kvm_lapic *apic, u32 val)
266 bool enabled = val & APIC_SPIV_APIC_ENABLED;
268 kvm_lapic_set_reg(apic, APIC_SPIV, val);
270 if (enabled != apic->sw_enabled) {
271 apic->sw_enabled = enabled;
273 static_key_slow_dec_deferred(&apic_sw_disabled);
275 static_key_slow_inc(&apic_sw_disabled.key);
277 apic->vcpu->kvm->arch.apic_map_dirty = true;
281 static inline void kvm_apic_set_xapic_id(struct kvm_lapic *apic, u8 id)
283 kvm_lapic_set_reg(apic, APIC_ID, id << 24);
284 apic->vcpu->kvm->arch.apic_map_dirty = true;
287 static inline void kvm_apic_set_ldr(struct kvm_lapic *apic, u32 id)
289 kvm_lapic_set_reg(apic, APIC_LDR, id);
290 apic->vcpu->kvm->arch.apic_map_dirty = true;
293 static inline u32 kvm_apic_calc_x2apic_ldr(u32 id)
295 return ((id >> 4) << 16) | (1 << (id & 0xf));
298 static inline void kvm_apic_set_x2apic_id(struct kvm_lapic *apic, u32 id)
300 u32 ldr = kvm_apic_calc_x2apic_ldr(id);
302 WARN_ON_ONCE(id != apic->vcpu->vcpu_id);
304 kvm_lapic_set_reg(apic, APIC_ID, id);
305 kvm_lapic_set_reg(apic, APIC_LDR, ldr);
306 apic->vcpu->kvm->arch.apic_map_dirty = true;
309 static inline int apic_lvt_enabled(struct kvm_lapic *apic, int lvt_type)
311 return !(kvm_lapic_get_reg(apic, lvt_type) & APIC_LVT_MASKED);
314 static inline int apic_lvtt_oneshot(struct kvm_lapic *apic)
316 return apic->lapic_timer.timer_mode == APIC_LVT_TIMER_ONESHOT;
319 static inline int apic_lvtt_period(struct kvm_lapic *apic)
321 return apic->lapic_timer.timer_mode == APIC_LVT_TIMER_PERIODIC;
324 static inline int apic_lvtt_tscdeadline(struct kvm_lapic *apic)
326 return apic->lapic_timer.timer_mode == APIC_LVT_TIMER_TSCDEADLINE;
329 static inline int apic_lvt_nmi_mode(u32 lvt_val)
331 return (lvt_val & (APIC_MODE_MASK | APIC_LVT_MASKED)) == APIC_DM_NMI;
334 void kvm_apic_set_version(struct kvm_vcpu *vcpu)
336 struct kvm_lapic *apic = vcpu->arch.apic;
337 struct kvm_cpuid_entry2 *feat;
338 u32 v = APIC_VERSION;
340 if (!lapic_in_kernel(vcpu))
344 * KVM emulates 82093AA datasheet (with in-kernel IOAPIC implementation)
345 * which doesn't have EOI register; Some buggy OSes (e.g. Windows with
346 * Hyper-V role) disable EOI broadcast in lapic not checking for IOAPIC
347 * version first and level-triggered interrupts never get EOIed in
350 feat = kvm_find_cpuid_entry(apic->vcpu, 0x1, 0);
351 if (feat && (feat->ecx & (1 << (X86_FEATURE_X2APIC & 31))) &&
352 !ioapic_in_kernel(vcpu->kvm))
353 v |= APIC_LVR_DIRECTED_EOI;
354 kvm_lapic_set_reg(apic, APIC_LVR, v);
357 static const unsigned int apic_lvt_mask[KVM_APIC_LVT_NUM] = {
358 LVT_MASK , /* part LVTT mask, timer mode mask added at runtime */
359 LVT_MASK | APIC_MODE_MASK, /* LVTTHMR */
360 LVT_MASK | APIC_MODE_MASK, /* LVTPC */
361 LINT_MASK, LINT_MASK, /* LVT0-1 */
362 LVT_MASK /* LVTERR */
365 static int find_highest_vector(void *bitmap)
370 for (vec = MAX_APIC_VECTOR - APIC_VECTORS_PER_REG;
371 vec >= 0; vec -= APIC_VECTORS_PER_REG) {
372 reg = bitmap + REG_POS(vec);
374 return __fls(*reg) + vec;
380 static u8 count_vectors(void *bitmap)
386 for (vec = 0; vec < MAX_APIC_VECTOR; vec += APIC_VECTORS_PER_REG) {
387 reg = bitmap + REG_POS(vec);
388 count += hweight32(*reg);
394 bool __kvm_apic_update_irr(u32 *pir, void *regs, int *max_irr)
397 u32 pir_val, irr_val, prev_irr_val;
400 max_updated_irr = -1;
403 for (i = vec = 0; i <= 7; i++, vec += 32) {
404 pir_val = READ_ONCE(pir[i]);
405 irr_val = *((u32 *)(regs + APIC_IRR + i * 0x10));
407 prev_irr_val = irr_val;
408 irr_val |= xchg(&pir[i], 0);
409 *((u32 *)(regs + APIC_IRR + i * 0x10)) = irr_val;
410 if (prev_irr_val != irr_val) {
412 __fls(irr_val ^ prev_irr_val) + vec;
416 *max_irr = __fls(irr_val) + vec;
419 return ((max_updated_irr != -1) &&
420 (max_updated_irr == *max_irr));
422 EXPORT_SYMBOL_GPL(__kvm_apic_update_irr);
424 bool kvm_apic_update_irr(struct kvm_vcpu *vcpu, u32 *pir, int *max_irr)
426 struct kvm_lapic *apic = vcpu->arch.apic;
428 return __kvm_apic_update_irr(pir, apic->regs, max_irr);
430 EXPORT_SYMBOL_GPL(kvm_apic_update_irr);
432 static inline int apic_search_irr(struct kvm_lapic *apic)
434 return find_highest_vector(apic->regs + APIC_IRR);
437 static inline int apic_find_highest_irr(struct kvm_lapic *apic)
442 * Note that irr_pending is just a hint. It will be always
443 * true with virtual interrupt delivery enabled.
445 if (!apic->irr_pending)
448 result = apic_search_irr(apic);
449 ASSERT(result == -1 || result >= 16);
454 static inline void apic_clear_irr(int vec, struct kvm_lapic *apic)
456 struct kvm_vcpu *vcpu;
460 if (unlikely(vcpu->arch.apicv_active)) {
461 /* need to update RVI */
462 kvm_lapic_clear_vector(vec, apic->regs + APIC_IRR);
463 kvm_x86_ops.hwapic_irr_update(vcpu,
464 apic_find_highest_irr(apic));
466 apic->irr_pending = false;
467 kvm_lapic_clear_vector(vec, apic->regs + APIC_IRR);
468 if (apic_search_irr(apic) != -1)
469 apic->irr_pending = true;
473 static inline void apic_set_isr(int vec, struct kvm_lapic *apic)
475 struct kvm_vcpu *vcpu;
477 if (__apic_test_and_set_vector(vec, apic->regs + APIC_ISR))
483 * With APIC virtualization enabled, all caching is disabled
484 * because the processor can modify ISR under the hood. Instead
487 if (unlikely(vcpu->arch.apicv_active))
488 kvm_x86_ops.hwapic_isr_update(vcpu, vec);
491 BUG_ON(apic->isr_count > MAX_APIC_VECTOR);
493 * ISR (in service register) bit is set when injecting an interrupt.
494 * The highest vector is injected. Thus the latest bit set matches
495 * the highest bit in ISR.
497 apic->highest_isr_cache = vec;
501 static inline int apic_find_highest_isr(struct kvm_lapic *apic)
506 * Note that isr_count is always 1, and highest_isr_cache
507 * is always -1, with APIC virtualization enabled.
509 if (!apic->isr_count)
511 if (likely(apic->highest_isr_cache != -1))
512 return apic->highest_isr_cache;
514 result = find_highest_vector(apic->regs + APIC_ISR);
515 ASSERT(result == -1 || result >= 16);
520 static inline void apic_clear_isr(int vec, struct kvm_lapic *apic)
522 struct kvm_vcpu *vcpu;
523 if (!__apic_test_and_clear_vector(vec, apic->regs + APIC_ISR))
529 * We do get here for APIC virtualization enabled if the guest
530 * uses the Hyper-V APIC enlightenment. In this case we may need
531 * to trigger a new interrupt delivery by writing the SVI field;
532 * on the other hand isr_count and highest_isr_cache are unused
533 * and must be left alone.
535 if (unlikely(vcpu->arch.apicv_active))
536 kvm_x86_ops.hwapic_isr_update(vcpu,
537 apic_find_highest_isr(apic));
540 BUG_ON(apic->isr_count < 0);
541 apic->highest_isr_cache = -1;
545 int kvm_lapic_find_highest_irr(struct kvm_vcpu *vcpu)
547 /* This may race with setting of irr in __apic_accept_irq() and
548 * value returned may be wrong, but kvm_vcpu_kick() in __apic_accept_irq
549 * will cause vmexit immediately and the value will be recalculated
550 * on the next vmentry.
552 return apic_find_highest_irr(vcpu->arch.apic);
554 EXPORT_SYMBOL_GPL(kvm_lapic_find_highest_irr);
556 static int __apic_accept_irq(struct kvm_lapic *apic, int delivery_mode,
557 int vector, int level, int trig_mode,
558 struct dest_map *dest_map);
560 int kvm_apic_set_irq(struct kvm_vcpu *vcpu, struct kvm_lapic_irq *irq,
561 struct dest_map *dest_map)
563 struct kvm_lapic *apic = vcpu->arch.apic;
565 return __apic_accept_irq(apic, irq->delivery_mode, irq->vector,
566 irq->level, irq->trig_mode, dest_map);
569 static int __pv_send_ipi(unsigned long *ipi_bitmap, struct kvm_apic_map *map,
570 struct kvm_lapic_irq *irq, u32 min)
573 struct kvm_vcpu *vcpu;
575 if (min > map->max_apic_id)
578 for_each_set_bit(i, ipi_bitmap,
579 min((u32)BITS_PER_LONG, (map->max_apic_id - min + 1))) {
580 if (map->phys_map[min + i]) {
581 vcpu = map->phys_map[min + i]->vcpu;
582 count += kvm_apic_set_irq(vcpu, irq, NULL);
589 int kvm_pv_send_ipi(struct kvm *kvm, unsigned long ipi_bitmap_low,
590 unsigned long ipi_bitmap_high, u32 min,
591 unsigned long icr, int op_64_bit)
593 struct kvm_apic_map *map;
594 struct kvm_lapic_irq irq = {0};
595 int cluster_size = op_64_bit ? 64 : 32;
598 if (icr & (APIC_DEST_MASK | APIC_SHORT_MASK))
601 irq.vector = icr & APIC_VECTOR_MASK;
602 irq.delivery_mode = icr & APIC_MODE_MASK;
603 irq.level = (icr & APIC_INT_ASSERT) != 0;
604 irq.trig_mode = icr & APIC_INT_LEVELTRIG;
607 map = rcu_dereference(kvm->arch.apic_map);
611 count = __pv_send_ipi(&ipi_bitmap_low, map, &irq, min);
613 count += __pv_send_ipi(&ipi_bitmap_high, map, &irq, min);
620 static int pv_eoi_put_user(struct kvm_vcpu *vcpu, u8 val)
623 return kvm_write_guest_cached(vcpu->kvm, &vcpu->arch.pv_eoi.data, &val,
627 static int pv_eoi_get_user(struct kvm_vcpu *vcpu, u8 *val)
630 return kvm_read_guest_cached(vcpu->kvm, &vcpu->arch.pv_eoi.data, val,
634 static inline bool pv_eoi_enabled(struct kvm_vcpu *vcpu)
636 return vcpu->arch.pv_eoi.msr_val & KVM_MSR_ENABLED;
639 static bool pv_eoi_get_pending(struct kvm_vcpu *vcpu)
642 if (pv_eoi_get_user(vcpu, &val) < 0) {
643 printk(KERN_WARNING "Can't read EOI MSR value: 0x%llx\n",
644 (unsigned long long)vcpu->arch.pv_eoi.msr_val);
650 static void pv_eoi_set_pending(struct kvm_vcpu *vcpu)
652 if (pv_eoi_put_user(vcpu, KVM_PV_EOI_ENABLED) < 0) {
653 printk(KERN_WARNING "Can't set EOI MSR value: 0x%llx\n",
654 (unsigned long long)vcpu->arch.pv_eoi.msr_val);
657 __set_bit(KVM_APIC_PV_EOI_PENDING, &vcpu->arch.apic_attention);
660 static void pv_eoi_clr_pending(struct kvm_vcpu *vcpu)
662 if (pv_eoi_put_user(vcpu, KVM_PV_EOI_DISABLED) < 0) {
663 printk(KERN_WARNING "Can't clear EOI MSR value: 0x%llx\n",
664 (unsigned long long)vcpu->arch.pv_eoi.msr_val);
667 __clear_bit(KVM_APIC_PV_EOI_PENDING, &vcpu->arch.apic_attention);
670 static int apic_has_interrupt_for_ppr(struct kvm_lapic *apic, u32 ppr)
673 if (apic->vcpu->arch.apicv_active)
674 highest_irr = kvm_x86_ops.sync_pir_to_irr(apic->vcpu);
676 highest_irr = apic_find_highest_irr(apic);
677 if (highest_irr == -1 || (highest_irr & 0xF0) <= ppr)
682 static bool __apic_update_ppr(struct kvm_lapic *apic, u32 *new_ppr)
684 u32 tpr, isrv, ppr, old_ppr;
687 old_ppr = kvm_lapic_get_reg(apic, APIC_PROCPRI);
688 tpr = kvm_lapic_get_reg(apic, APIC_TASKPRI);
689 isr = apic_find_highest_isr(apic);
690 isrv = (isr != -1) ? isr : 0;
692 if ((tpr & 0xf0) >= (isrv & 0xf0))
699 kvm_lapic_set_reg(apic, APIC_PROCPRI, ppr);
701 return ppr < old_ppr;
704 static void apic_update_ppr(struct kvm_lapic *apic)
708 if (__apic_update_ppr(apic, &ppr) &&
709 apic_has_interrupt_for_ppr(apic, ppr) != -1)
710 kvm_make_request(KVM_REQ_EVENT, apic->vcpu);
713 void kvm_apic_update_ppr(struct kvm_vcpu *vcpu)
715 apic_update_ppr(vcpu->arch.apic);
717 EXPORT_SYMBOL_GPL(kvm_apic_update_ppr);
719 static void apic_set_tpr(struct kvm_lapic *apic, u32 tpr)
721 kvm_lapic_set_reg(apic, APIC_TASKPRI, tpr);
722 apic_update_ppr(apic);
725 static bool kvm_apic_broadcast(struct kvm_lapic *apic, u32 mda)
727 return mda == (apic_x2apic_mode(apic) ?
728 X2APIC_BROADCAST : APIC_BROADCAST);
731 static bool kvm_apic_match_physical_addr(struct kvm_lapic *apic, u32 mda)
733 if (kvm_apic_broadcast(apic, mda))
736 if (apic_x2apic_mode(apic))
737 return mda == kvm_x2apic_id(apic);
740 * Hotplug hack: Make LAPIC in xAPIC mode also accept interrupts as if
741 * it were in x2APIC mode. Hotplugged VCPUs start in xAPIC mode and
742 * this allows unique addressing of VCPUs with APIC ID over 0xff.
743 * The 0xff condition is needed because writeable xAPIC ID.
745 if (kvm_x2apic_id(apic) > 0xff && mda == kvm_x2apic_id(apic))
748 return mda == kvm_xapic_id(apic);
751 static bool kvm_apic_match_logical_addr(struct kvm_lapic *apic, u32 mda)
755 if (kvm_apic_broadcast(apic, mda))
758 logical_id = kvm_lapic_get_reg(apic, APIC_LDR);
760 if (apic_x2apic_mode(apic))
761 return ((logical_id >> 16) == (mda >> 16))
762 && (logical_id & mda & 0xffff) != 0;
764 logical_id = GET_APIC_LOGICAL_ID(logical_id);
766 switch (kvm_lapic_get_reg(apic, APIC_DFR)) {
768 return (logical_id & mda) != 0;
769 case APIC_DFR_CLUSTER:
770 return ((logical_id >> 4) == (mda >> 4))
771 && (logical_id & mda & 0xf) != 0;
777 /* The KVM local APIC implementation has two quirks:
779 * - Real hardware delivers interrupts destined to x2APIC ID > 0xff to LAPICs
780 * in xAPIC mode if the "destination & 0xff" matches its xAPIC ID.
781 * KVM doesn't do that aliasing.
783 * - in-kernel IOAPIC messages have to be delivered directly to
784 * x2APIC, because the kernel does not support interrupt remapping.
785 * In order to support broadcast without interrupt remapping, x2APIC
786 * rewrites the destination of non-IPI messages from APIC_BROADCAST
787 * to X2APIC_BROADCAST.
789 * The broadcast quirk can be disabled with KVM_CAP_X2APIC_API. This is
790 * important when userspace wants to use x2APIC-format MSIs, because
791 * APIC_BROADCAST (0xff) is a legal route for "cluster 0, CPUs 0-7".
793 static u32 kvm_apic_mda(struct kvm_vcpu *vcpu, unsigned int dest_id,
794 struct kvm_lapic *source, struct kvm_lapic *target)
796 bool ipi = source != NULL;
798 if (!vcpu->kvm->arch.x2apic_broadcast_quirk_disabled &&
799 !ipi && dest_id == APIC_BROADCAST && apic_x2apic_mode(target))
800 return X2APIC_BROADCAST;
805 bool kvm_apic_match_dest(struct kvm_vcpu *vcpu, struct kvm_lapic *source,
806 int shorthand, unsigned int dest, int dest_mode)
808 struct kvm_lapic *target = vcpu->arch.apic;
809 u32 mda = kvm_apic_mda(vcpu, dest, source, target);
813 case APIC_DEST_NOSHORT:
814 if (dest_mode == APIC_DEST_PHYSICAL)
815 return kvm_apic_match_physical_addr(target, mda);
817 return kvm_apic_match_logical_addr(target, mda);
819 return target == source;
820 case APIC_DEST_ALLINC:
822 case APIC_DEST_ALLBUT:
823 return target != source;
828 EXPORT_SYMBOL_GPL(kvm_apic_match_dest);
830 int kvm_vector_to_index(u32 vector, u32 dest_vcpus,
831 const unsigned long *bitmap, u32 bitmap_size)
836 mod = vector % dest_vcpus;
838 for (i = 0; i <= mod; i++) {
839 idx = find_next_bit(bitmap, bitmap_size, idx + 1);
840 BUG_ON(idx == bitmap_size);
846 static void kvm_apic_disabled_lapic_found(struct kvm *kvm)
848 if (!kvm->arch.disabled_lapic_found) {
849 kvm->arch.disabled_lapic_found = true;
851 "Disabled LAPIC found during irq injection\n");
855 static bool kvm_apic_is_broadcast_dest(struct kvm *kvm, struct kvm_lapic **src,
856 struct kvm_lapic_irq *irq, struct kvm_apic_map *map)
858 if (kvm->arch.x2apic_broadcast_quirk_disabled) {
859 if ((irq->dest_id == APIC_BROADCAST &&
860 map->mode != KVM_APIC_MODE_X2APIC))
862 if (irq->dest_id == X2APIC_BROADCAST)
865 bool x2apic_ipi = src && *src && apic_x2apic_mode(*src);
866 if (irq->dest_id == (x2apic_ipi ?
867 X2APIC_BROADCAST : APIC_BROADCAST))
874 /* Return true if the interrupt can be handled by using *bitmap as index mask
875 * for valid destinations in *dst array.
876 * Return false if kvm_apic_map_get_dest_lapic did nothing useful.
877 * Note: we may have zero kvm_lapic destinations when we return true, which
878 * means that the interrupt should be dropped. In this case, *bitmap would be
879 * zero and *dst undefined.
881 static inline bool kvm_apic_map_get_dest_lapic(struct kvm *kvm,
882 struct kvm_lapic **src, struct kvm_lapic_irq *irq,
883 struct kvm_apic_map *map, struct kvm_lapic ***dst,
884 unsigned long *bitmap)
888 if (irq->shorthand == APIC_DEST_SELF && src) {
892 } else if (irq->shorthand)
895 if (!map || kvm_apic_is_broadcast_dest(kvm, src, irq, map))
898 if (irq->dest_mode == APIC_DEST_PHYSICAL) {
899 if (irq->dest_id > map->max_apic_id) {
902 u32 dest_id = array_index_nospec(irq->dest_id, map->max_apic_id + 1);
903 *dst = &map->phys_map[dest_id];
910 if (!kvm_apic_map_get_logical_dest(map, irq->dest_id, dst,
914 if (!kvm_lowest_prio_delivery(irq))
917 if (!kvm_vector_hashing_enabled()) {
919 for_each_set_bit(i, bitmap, 16) {
924 else if (kvm_apic_compare_prio((*dst)[i]->vcpu,
925 (*dst)[lowest]->vcpu) < 0)
932 lowest = kvm_vector_to_index(irq->vector, hweight16(*bitmap),
935 if (!(*dst)[lowest]) {
936 kvm_apic_disabled_lapic_found(kvm);
942 *bitmap = (lowest >= 0) ? 1 << lowest : 0;
947 bool kvm_irq_delivery_to_apic_fast(struct kvm *kvm, struct kvm_lapic *src,
948 struct kvm_lapic_irq *irq, int *r, struct dest_map *dest_map)
950 struct kvm_apic_map *map;
951 unsigned long bitmap;
952 struct kvm_lapic **dst = NULL;
958 if (irq->shorthand == APIC_DEST_SELF) {
959 *r = kvm_apic_set_irq(src->vcpu, irq, dest_map);
964 map = rcu_dereference(kvm->arch.apic_map);
966 ret = kvm_apic_map_get_dest_lapic(kvm, &src, irq, map, &dst, &bitmap);
969 for_each_set_bit(i, &bitmap, 16) {
972 *r += kvm_apic_set_irq(dst[i]->vcpu, irq, dest_map);
981 * This routine tries to handle interrupts in posted mode, here is how
982 * it deals with different cases:
983 * - For single-destination interrupts, handle it in posted mode
984 * - Else if vector hashing is enabled and it is a lowest-priority
985 * interrupt, handle it in posted mode and use the following mechanism
986 * to find the destination vCPU.
987 * 1. For lowest-priority interrupts, store all the possible
988 * destination vCPUs in an array.
989 * 2. Use "guest vector % max number of destination vCPUs" to find
990 * the right destination vCPU in the array for the lowest-priority
992 * - Otherwise, use remapped mode to inject the interrupt.
994 bool kvm_intr_is_single_vcpu_fast(struct kvm *kvm, struct kvm_lapic_irq *irq,
995 struct kvm_vcpu **dest_vcpu)
997 struct kvm_apic_map *map;
998 unsigned long bitmap;
999 struct kvm_lapic **dst = NULL;
1006 map = rcu_dereference(kvm->arch.apic_map);
1008 if (kvm_apic_map_get_dest_lapic(kvm, NULL, irq, map, &dst, &bitmap) &&
1009 hweight16(bitmap) == 1) {
1010 unsigned long i = find_first_bit(&bitmap, 16);
1013 *dest_vcpu = dst[i]->vcpu;
1023 * Add a pending IRQ into lapic.
1024 * Return 1 if successfully added and 0 if discarded.
1026 static int __apic_accept_irq(struct kvm_lapic *apic, int delivery_mode,
1027 int vector, int level, int trig_mode,
1028 struct dest_map *dest_map)
1031 struct kvm_vcpu *vcpu = apic->vcpu;
1033 trace_kvm_apic_accept_irq(vcpu->vcpu_id, delivery_mode,
1035 switch (delivery_mode) {
1036 case APIC_DM_LOWEST:
1037 vcpu->arch.apic_arb_prio++;
1040 if (unlikely(trig_mode && !level))
1043 /* FIXME add logic for vcpu on reset */
1044 if (unlikely(!apic_enabled(apic)))
1050 __set_bit(vcpu->vcpu_id, dest_map->map);
1051 dest_map->vectors[vcpu->vcpu_id] = vector;
1054 if (apic_test_vector(vector, apic->regs + APIC_TMR) != !!trig_mode) {
1056 kvm_lapic_set_vector(vector,
1057 apic->regs + APIC_TMR);
1059 kvm_lapic_clear_vector(vector,
1060 apic->regs + APIC_TMR);
1063 if (kvm_x86_ops.deliver_posted_interrupt(vcpu, vector)) {
1064 kvm_lapic_set_irr(vector, apic);
1065 kvm_make_request(KVM_REQ_EVENT, vcpu);
1066 kvm_vcpu_kick(vcpu);
1072 vcpu->arch.pv.pv_unhalted = 1;
1073 kvm_make_request(KVM_REQ_EVENT, vcpu);
1074 kvm_vcpu_kick(vcpu);
1079 kvm_make_request(KVM_REQ_SMI, vcpu);
1080 kvm_vcpu_kick(vcpu);
1085 kvm_inject_nmi(vcpu);
1086 kvm_vcpu_kick(vcpu);
1090 if (!trig_mode || level) {
1092 /* assumes that there are only KVM_APIC_INIT/SIPI */
1093 apic->pending_events = (1UL << KVM_APIC_INIT);
1094 kvm_make_request(KVM_REQ_EVENT, vcpu);
1095 kvm_vcpu_kick(vcpu);
1099 case APIC_DM_STARTUP:
1101 apic->sipi_vector = vector;
1102 /* make sure sipi_vector is visible for the receiver */
1104 set_bit(KVM_APIC_SIPI, &apic->pending_events);
1105 kvm_make_request(KVM_REQ_EVENT, vcpu);
1106 kvm_vcpu_kick(vcpu);
1109 case APIC_DM_EXTINT:
1111 * Should only be called by kvm_apic_local_deliver() with LVT0,
1112 * before NMI watchdog was enabled. Already handled by
1113 * kvm_apic_accept_pic_intr().
1118 printk(KERN_ERR "TODO: unsupported delivery mode %x\n",
1126 * This routine identifies the destination vcpus mask meant to receive the
1127 * IOAPIC interrupts. It either uses kvm_apic_map_get_dest_lapic() to find
1128 * out the destination vcpus array and set the bitmap or it traverses to
1129 * each available vcpu to identify the same.
1131 void kvm_bitmap_or_dest_vcpus(struct kvm *kvm, struct kvm_lapic_irq *irq,
1132 unsigned long *vcpu_bitmap)
1134 struct kvm_lapic **dest_vcpu = NULL;
1135 struct kvm_lapic *src = NULL;
1136 struct kvm_apic_map *map;
1137 struct kvm_vcpu *vcpu;
1138 unsigned long bitmap;
1143 map = rcu_dereference(kvm->arch.apic_map);
1145 ret = kvm_apic_map_get_dest_lapic(kvm, &src, irq, map, &dest_vcpu,
1148 for_each_set_bit(i, &bitmap, 16) {
1151 vcpu_idx = dest_vcpu[i]->vcpu->vcpu_idx;
1152 __set_bit(vcpu_idx, vcpu_bitmap);
1155 kvm_for_each_vcpu(i, vcpu, kvm) {
1156 if (!kvm_apic_present(vcpu))
1158 if (!kvm_apic_match_dest(vcpu, NULL,
1163 __set_bit(i, vcpu_bitmap);
1169 int kvm_apic_compare_prio(struct kvm_vcpu *vcpu1, struct kvm_vcpu *vcpu2)
1171 return vcpu1->arch.apic_arb_prio - vcpu2->arch.apic_arb_prio;
1174 static bool kvm_ioapic_handles_vector(struct kvm_lapic *apic, int vector)
1176 return test_bit(vector, apic->vcpu->arch.ioapic_handled_vectors);
1179 static void kvm_ioapic_send_eoi(struct kvm_lapic *apic, int vector)
1183 /* Eoi the ioapic only if the ioapic doesn't own the vector. */
1184 if (!kvm_ioapic_handles_vector(apic, vector))
1187 /* Request a KVM exit to inform the userspace IOAPIC. */
1188 if (irqchip_split(apic->vcpu->kvm)) {
1189 apic->vcpu->arch.pending_ioapic_eoi = vector;
1190 kvm_make_request(KVM_REQ_IOAPIC_EOI_EXIT, apic->vcpu);
1194 if (apic_test_vector(vector, apic->regs + APIC_TMR))
1195 trigger_mode = IOAPIC_LEVEL_TRIG;
1197 trigger_mode = IOAPIC_EDGE_TRIG;
1199 kvm_ioapic_update_eoi(apic->vcpu, vector, trigger_mode);
1202 static int apic_set_eoi(struct kvm_lapic *apic)
1204 int vector = apic_find_highest_isr(apic);
1206 trace_kvm_eoi(apic, vector);
1209 * Not every write EOI will has corresponding ISR,
1210 * one example is when Kernel check timer on setup_IO_APIC
1215 apic_clear_isr(vector, apic);
1216 apic_update_ppr(apic);
1218 if (test_bit(vector, vcpu_to_synic(apic->vcpu)->vec_bitmap))
1219 kvm_hv_synic_send_eoi(apic->vcpu, vector);
1221 kvm_ioapic_send_eoi(apic, vector);
1222 kvm_make_request(KVM_REQ_EVENT, apic->vcpu);
1227 * this interface assumes a trap-like exit, which has already finished
1228 * desired side effect including vISR and vPPR update.
1230 void kvm_apic_set_eoi_accelerated(struct kvm_vcpu *vcpu, int vector)
1232 struct kvm_lapic *apic = vcpu->arch.apic;
1234 trace_kvm_eoi(apic, vector);
1236 kvm_ioapic_send_eoi(apic, vector);
1237 kvm_make_request(KVM_REQ_EVENT, apic->vcpu);
1239 EXPORT_SYMBOL_GPL(kvm_apic_set_eoi_accelerated);
1241 void kvm_apic_send_ipi(struct kvm_lapic *apic, u32 icr_low, u32 icr_high)
1243 struct kvm_lapic_irq irq;
1245 irq.vector = icr_low & APIC_VECTOR_MASK;
1246 irq.delivery_mode = icr_low & APIC_MODE_MASK;
1247 irq.dest_mode = icr_low & APIC_DEST_MASK;
1248 irq.level = (icr_low & APIC_INT_ASSERT) != 0;
1249 irq.trig_mode = icr_low & APIC_INT_LEVELTRIG;
1250 irq.shorthand = icr_low & APIC_SHORT_MASK;
1251 irq.msi_redir_hint = false;
1252 if (apic_x2apic_mode(apic))
1253 irq.dest_id = icr_high;
1255 irq.dest_id = GET_APIC_DEST_FIELD(icr_high);
1257 trace_kvm_apic_ipi(icr_low, irq.dest_id);
1259 kvm_irq_delivery_to_apic(apic->vcpu->kvm, apic, &irq, NULL);
1262 static u32 apic_get_tmcct(struct kvm_lapic *apic)
1264 ktime_t remaining, now;
1268 ASSERT(apic != NULL);
1270 /* if initial count is 0, current count should also be 0 */
1271 if (kvm_lapic_get_reg(apic, APIC_TMICT) == 0 ||
1272 apic->lapic_timer.period == 0)
1276 remaining = ktime_sub(apic->lapic_timer.target_expiration, now);
1277 if (ktime_to_ns(remaining) < 0)
1280 ns = mod_64(ktime_to_ns(remaining), apic->lapic_timer.period);
1281 tmcct = div64_u64(ns,
1282 (APIC_BUS_CYCLE_NS * apic->divide_count));
1287 static void __report_tpr_access(struct kvm_lapic *apic, bool write)
1289 struct kvm_vcpu *vcpu = apic->vcpu;
1290 struct kvm_run *run = vcpu->run;
1292 kvm_make_request(KVM_REQ_REPORT_TPR_ACCESS, vcpu);
1293 run->tpr_access.rip = kvm_rip_read(vcpu);
1294 run->tpr_access.is_write = write;
1297 static inline void report_tpr_access(struct kvm_lapic *apic, bool write)
1299 if (apic->vcpu->arch.tpr_access_reporting)
1300 __report_tpr_access(apic, write);
1303 static u32 __apic_read(struct kvm_lapic *apic, unsigned int offset)
1307 if (offset >= LAPIC_MMIO_LENGTH)
1314 case APIC_TMCCT: /* Timer CCR */
1315 if (apic_lvtt_tscdeadline(apic))
1318 val = apic_get_tmcct(apic);
1321 apic_update_ppr(apic);
1322 val = kvm_lapic_get_reg(apic, offset);
1325 report_tpr_access(apic, false);
1328 val = kvm_lapic_get_reg(apic, offset);
1335 static inline struct kvm_lapic *to_lapic(struct kvm_io_device *dev)
1337 return container_of(dev, struct kvm_lapic, dev);
1340 #define APIC_REG_MASK(reg) (1ull << ((reg) >> 4))
1341 #define APIC_REGS_MASK(first, count) \
1342 (APIC_REG_MASK(first) * ((1ull << (count)) - 1))
1344 int kvm_lapic_reg_read(struct kvm_lapic *apic, u32 offset, int len,
1347 unsigned char alignment = offset & 0xf;
1349 /* this bitmask has a bit cleared for each reserved register */
1350 u64 valid_reg_mask =
1351 APIC_REG_MASK(APIC_ID) |
1352 APIC_REG_MASK(APIC_LVR) |
1353 APIC_REG_MASK(APIC_TASKPRI) |
1354 APIC_REG_MASK(APIC_PROCPRI) |
1355 APIC_REG_MASK(APIC_LDR) |
1356 APIC_REG_MASK(APIC_DFR) |
1357 APIC_REG_MASK(APIC_SPIV) |
1358 APIC_REGS_MASK(APIC_ISR, APIC_ISR_NR) |
1359 APIC_REGS_MASK(APIC_TMR, APIC_ISR_NR) |
1360 APIC_REGS_MASK(APIC_IRR, APIC_ISR_NR) |
1361 APIC_REG_MASK(APIC_ESR) |
1362 APIC_REG_MASK(APIC_ICR) |
1363 APIC_REG_MASK(APIC_ICR2) |
1364 APIC_REG_MASK(APIC_LVTT) |
1365 APIC_REG_MASK(APIC_LVTTHMR) |
1366 APIC_REG_MASK(APIC_LVTPC) |
1367 APIC_REG_MASK(APIC_LVT0) |
1368 APIC_REG_MASK(APIC_LVT1) |
1369 APIC_REG_MASK(APIC_LVTERR) |
1370 APIC_REG_MASK(APIC_TMICT) |
1371 APIC_REG_MASK(APIC_TMCCT) |
1372 APIC_REG_MASK(APIC_TDCR);
1374 /* ARBPRI is not valid on x2APIC */
1375 if (!apic_x2apic_mode(apic))
1376 valid_reg_mask |= APIC_REG_MASK(APIC_ARBPRI);
1378 if (offset > 0x3f0 || !(valid_reg_mask & APIC_REG_MASK(offset)))
1381 result = __apic_read(apic, offset & ~0xf);
1383 trace_kvm_apic_read(offset, result);
1389 memcpy(data, (char *)&result + alignment, len);
1392 printk(KERN_ERR "Local APIC read with len = %x, "
1393 "should be 1,2, or 4 instead\n", len);
1398 EXPORT_SYMBOL_GPL(kvm_lapic_reg_read);
1400 static int apic_mmio_in_range(struct kvm_lapic *apic, gpa_t addr)
1402 return addr >= apic->base_address &&
1403 addr < apic->base_address + LAPIC_MMIO_LENGTH;
1406 static int apic_mmio_read(struct kvm_vcpu *vcpu, struct kvm_io_device *this,
1407 gpa_t address, int len, void *data)
1409 struct kvm_lapic *apic = to_lapic(this);
1410 u32 offset = address - apic->base_address;
1412 if (!apic_mmio_in_range(apic, address))
1415 if (!kvm_apic_hw_enabled(apic) || apic_x2apic_mode(apic)) {
1416 if (!kvm_check_has_quirk(vcpu->kvm,
1417 KVM_X86_QUIRK_LAPIC_MMIO_HOLE))
1420 memset(data, 0xff, len);
1424 kvm_lapic_reg_read(apic, offset, len, data);
1429 static void update_divide_count(struct kvm_lapic *apic)
1431 u32 tmp1, tmp2, tdcr;
1433 tdcr = kvm_lapic_get_reg(apic, APIC_TDCR);
1435 tmp2 = ((tmp1 & 0x3) | ((tmp1 & 0x8) >> 1)) + 1;
1436 apic->divide_count = 0x1 << (tmp2 & 0x7);
1439 static void limit_periodic_timer_frequency(struct kvm_lapic *apic)
1442 * Do not allow the guest to program periodic timers with small
1443 * interval, since the hrtimers are not throttled by the host
1446 if (apic_lvtt_period(apic) && apic->lapic_timer.period) {
1447 s64 min_period = min_timer_period_us * 1000LL;
1449 if (apic->lapic_timer.period < min_period) {
1450 pr_info_ratelimited(
1451 "kvm: vcpu %i: requested %lld ns "
1452 "lapic timer period limited to %lld ns\n",
1453 apic->vcpu->vcpu_id,
1454 apic->lapic_timer.period, min_period);
1455 apic->lapic_timer.period = min_period;
1460 static void cancel_hv_timer(struct kvm_lapic *apic);
1462 static void apic_update_lvtt(struct kvm_lapic *apic)
1464 u32 timer_mode = kvm_lapic_get_reg(apic, APIC_LVTT) &
1465 apic->lapic_timer.timer_mode_mask;
1467 if (apic->lapic_timer.timer_mode != timer_mode) {
1468 if (apic_lvtt_tscdeadline(apic) != (timer_mode ==
1469 APIC_LVT_TIMER_TSCDEADLINE)) {
1470 hrtimer_cancel(&apic->lapic_timer.timer);
1472 if (apic->lapic_timer.hv_timer_in_use)
1473 cancel_hv_timer(apic);
1475 kvm_lapic_set_reg(apic, APIC_TMICT, 0);
1476 apic->lapic_timer.period = 0;
1477 apic->lapic_timer.tscdeadline = 0;
1479 apic->lapic_timer.timer_mode = timer_mode;
1480 limit_periodic_timer_frequency(apic);
1485 * On APICv, this test will cause a busy wait
1486 * during a higher-priority task.
1489 static bool lapic_timer_int_injected(struct kvm_vcpu *vcpu)
1491 struct kvm_lapic *apic = vcpu->arch.apic;
1492 u32 reg = kvm_lapic_get_reg(apic, APIC_LVTT);
1494 if (kvm_apic_hw_enabled(apic)) {
1495 int vec = reg & APIC_VECTOR_MASK;
1496 void *bitmap = apic->regs + APIC_ISR;
1498 if (vcpu->arch.apicv_active)
1499 bitmap = apic->regs + APIC_IRR;
1501 if (apic_test_vector(vec, bitmap))
1507 static inline void __wait_lapic_expire(struct kvm_vcpu *vcpu, u64 guest_cycles)
1509 u64 timer_advance_ns = vcpu->arch.apic->lapic_timer.timer_advance_ns;
1512 * If the guest TSC is running at a different ratio than the host, then
1513 * convert the delay to nanoseconds to achieve an accurate delay. Note
1514 * that __delay() uses delay_tsc whenever the hardware has TSC, thus
1515 * always for VMX enabled hardware.
1517 if (vcpu->arch.tsc_scaling_ratio == kvm_default_tsc_scaling_ratio) {
1518 __delay(min(guest_cycles,
1519 nsec_to_cycles(vcpu, timer_advance_ns)));
1521 u64 delay_ns = guest_cycles * 1000000ULL;
1522 do_div(delay_ns, vcpu->arch.virtual_tsc_khz);
1523 ndelay(min_t(u32, delay_ns, timer_advance_ns));
1527 static inline void adjust_lapic_timer_advance(struct kvm_vcpu *vcpu,
1528 s64 advance_expire_delta)
1530 struct kvm_lapic *apic = vcpu->arch.apic;
1531 u32 timer_advance_ns = apic->lapic_timer.timer_advance_ns;
1534 /* Do not adjust for tiny fluctuations or large random spikes. */
1535 if (abs(advance_expire_delta) > LAPIC_TIMER_ADVANCE_ADJUST_MAX ||
1536 abs(advance_expire_delta) < LAPIC_TIMER_ADVANCE_ADJUST_MIN)
1540 if (advance_expire_delta < 0) {
1541 ns = -advance_expire_delta * 1000000ULL;
1542 do_div(ns, vcpu->arch.virtual_tsc_khz);
1543 timer_advance_ns -= ns/LAPIC_TIMER_ADVANCE_ADJUST_STEP;
1546 ns = advance_expire_delta * 1000000ULL;
1547 do_div(ns, vcpu->arch.virtual_tsc_khz);
1548 timer_advance_ns += ns/LAPIC_TIMER_ADVANCE_ADJUST_STEP;
1551 if (unlikely(timer_advance_ns > LAPIC_TIMER_ADVANCE_NS_MAX))
1552 timer_advance_ns = LAPIC_TIMER_ADVANCE_NS_INIT;
1553 apic->lapic_timer.timer_advance_ns = timer_advance_ns;
1556 static void __kvm_wait_lapic_expire(struct kvm_vcpu *vcpu)
1558 struct kvm_lapic *apic = vcpu->arch.apic;
1559 u64 guest_tsc, tsc_deadline;
1561 if (apic->lapic_timer.expired_tscdeadline == 0)
1564 tsc_deadline = apic->lapic_timer.expired_tscdeadline;
1565 apic->lapic_timer.expired_tscdeadline = 0;
1566 guest_tsc = kvm_read_l1_tsc(vcpu, rdtsc());
1567 apic->lapic_timer.advance_expire_delta = guest_tsc - tsc_deadline;
1569 if (guest_tsc < tsc_deadline)
1570 __wait_lapic_expire(vcpu, tsc_deadline - guest_tsc);
1572 if (lapic_timer_advance_dynamic)
1573 adjust_lapic_timer_advance(vcpu, apic->lapic_timer.advance_expire_delta);
1576 void kvm_wait_lapic_expire(struct kvm_vcpu *vcpu)
1578 if (lapic_timer_int_injected(vcpu))
1579 __kvm_wait_lapic_expire(vcpu);
1581 EXPORT_SYMBOL_GPL(kvm_wait_lapic_expire);
1583 static void kvm_apic_inject_pending_timer_irqs(struct kvm_lapic *apic)
1585 struct kvm_timer *ktimer = &apic->lapic_timer;
1587 kvm_apic_local_deliver(apic, APIC_LVTT);
1588 if (apic_lvtt_tscdeadline(apic)) {
1589 ktimer->tscdeadline = 0;
1590 } else if (apic_lvtt_oneshot(apic)) {
1591 ktimer->tscdeadline = 0;
1592 ktimer->target_expiration = 0;
1596 static void apic_timer_expired(struct kvm_lapic *apic)
1598 struct kvm_vcpu *vcpu = apic->vcpu;
1599 struct kvm_timer *ktimer = &apic->lapic_timer;
1601 if (atomic_read(&apic->lapic_timer.pending))
1604 if (apic_lvtt_tscdeadline(apic) || ktimer->hv_timer_in_use)
1605 ktimer->expired_tscdeadline = ktimer->tscdeadline;
1607 if (kvm_use_posted_timer_interrupt(apic->vcpu)) {
1608 if (apic->lapic_timer.timer_advance_ns)
1609 __kvm_wait_lapic_expire(vcpu);
1610 kvm_apic_inject_pending_timer_irqs(apic);
1614 atomic_inc(&apic->lapic_timer.pending);
1615 kvm_set_pending_timer(vcpu);
1618 static void start_sw_tscdeadline(struct kvm_lapic *apic)
1620 struct kvm_timer *ktimer = &apic->lapic_timer;
1621 u64 guest_tsc, tscdeadline = ktimer->tscdeadline;
1624 struct kvm_vcpu *vcpu = apic->vcpu;
1625 unsigned long this_tsc_khz = vcpu->arch.virtual_tsc_khz;
1626 unsigned long flags;
1629 if (unlikely(!tscdeadline || !this_tsc_khz))
1632 local_irq_save(flags);
1635 guest_tsc = kvm_read_l1_tsc(vcpu, rdtsc());
1637 ns = (tscdeadline - guest_tsc) * 1000000ULL;
1638 do_div(ns, this_tsc_khz);
1640 if (likely(tscdeadline > guest_tsc) &&
1641 likely(ns > apic->lapic_timer.timer_advance_ns)) {
1642 expire = ktime_add_ns(now, ns);
1643 expire = ktime_sub_ns(expire, ktimer->timer_advance_ns);
1644 hrtimer_start(&ktimer->timer, expire, HRTIMER_MODE_ABS_HARD);
1646 apic_timer_expired(apic);
1648 local_irq_restore(flags);
1651 static void update_target_expiration(struct kvm_lapic *apic, uint32_t old_divisor)
1653 ktime_t now, remaining;
1654 u64 ns_remaining_old, ns_remaining_new;
1656 apic->lapic_timer.period = (u64)kvm_lapic_get_reg(apic, APIC_TMICT)
1657 * APIC_BUS_CYCLE_NS * apic->divide_count;
1658 limit_periodic_timer_frequency(apic);
1661 remaining = ktime_sub(apic->lapic_timer.target_expiration, now);
1662 if (ktime_to_ns(remaining) < 0)
1665 ns_remaining_old = ktime_to_ns(remaining);
1666 ns_remaining_new = mul_u64_u32_div(ns_remaining_old,
1667 apic->divide_count, old_divisor);
1669 apic->lapic_timer.tscdeadline +=
1670 nsec_to_cycles(apic->vcpu, ns_remaining_new) -
1671 nsec_to_cycles(apic->vcpu, ns_remaining_old);
1672 apic->lapic_timer.target_expiration = ktime_add_ns(now, ns_remaining_new);
1675 static bool set_target_expiration(struct kvm_lapic *apic)
1681 apic->lapic_timer.period = (u64)kvm_lapic_get_reg(apic, APIC_TMICT)
1682 * APIC_BUS_CYCLE_NS * apic->divide_count;
1684 if (!apic->lapic_timer.period) {
1685 apic->lapic_timer.tscdeadline = 0;
1689 limit_periodic_timer_frequency(apic);
1691 apic->lapic_timer.tscdeadline = kvm_read_l1_tsc(apic->vcpu, tscl) +
1692 nsec_to_cycles(apic->vcpu, apic->lapic_timer.period);
1693 apic->lapic_timer.target_expiration = ktime_add_ns(now, apic->lapic_timer.period);
1698 static void advance_periodic_target_expiration(struct kvm_lapic *apic)
1700 ktime_t now = ktime_get();
1705 * Synchronize both deadlines to the same time source or
1706 * differences in the periods (caused by differences in the
1707 * underlying clocks or numerical approximation errors) will
1708 * cause the two to drift apart over time as the errors
1711 apic->lapic_timer.target_expiration =
1712 ktime_add_ns(apic->lapic_timer.target_expiration,
1713 apic->lapic_timer.period);
1714 delta = ktime_sub(apic->lapic_timer.target_expiration, now);
1715 apic->lapic_timer.tscdeadline = kvm_read_l1_tsc(apic->vcpu, tscl) +
1716 nsec_to_cycles(apic->vcpu, delta);
1719 static void start_sw_period(struct kvm_lapic *apic)
1721 if (!apic->lapic_timer.period)
1724 if (ktime_after(ktime_get(),
1725 apic->lapic_timer.target_expiration)) {
1726 apic_timer_expired(apic);
1728 if (apic_lvtt_oneshot(apic))
1731 advance_periodic_target_expiration(apic);
1734 hrtimer_start(&apic->lapic_timer.timer,
1735 apic->lapic_timer.target_expiration,
1736 HRTIMER_MODE_ABS_HARD);
1739 bool kvm_lapic_hv_timer_in_use(struct kvm_vcpu *vcpu)
1741 if (!lapic_in_kernel(vcpu))
1744 return vcpu->arch.apic->lapic_timer.hv_timer_in_use;
1746 EXPORT_SYMBOL_GPL(kvm_lapic_hv_timer_in_use);
1748 static void cancel_hv_timer(struct kvm_lapic *apic)
1750 WARN_ON(preemptible());
1751 WARN_ON(!apic->lapic_timer.hv_timer_in_use);
1752 kvm_x86_ops.cancel_hv_timer(apic->vcpu);
1753 apic->lapic_timer.hv_timer_in_use = false;
1756 static bool start_hv_timer(struct kvm_lapic *apic)
1758 struct kvm_timer *ktimer = &apic->lapic_timer;
1759 struct kvm_vcpu *vcpu = apic->vcpu;
1762 WARN_ON(preemptible());
1763 if (!kvm_x86_ops.set_hv_timer)
1766 if (!ktimer->tscdeadline)
1769 if (kvm_x86_ops.set_hv_timer(vcpu, ktimer->tscdeadline, &expired))
1772 ktimer->hv_timer_in_use = true;
1773 hrtimer_cancel(&ktimer->timer);
1776 * To simplify handling the periodic timer, leave the hv timer running
1777 * even if the deadline timer has expired, i.e. rely on the resulting
1778 * VM-Exit to recompute the periodic timer's target expiration.
1780 if (!apic_lvtt_period(apic)) {
1782 * Cancel the hv timer if the sw timer fired while the hv timer
1783 * was being programmed, or if the hv timer itself expired.
1785 if (atomic_read(&ktimer->pending)) {
1786 cancel_hv_timer(apic);
1787 } else if (expired) {
1788 apic_timer_expired(apic);
1789 cancel_hv_timer(apic);
1793 trace_kvm_hv_timer_state(vcpu->vcpu_id, ktimer->hv_timer_in_use);
1798 static void start_sw_timer(struct kvm_lapic *apic)
1800 struct kvm_timer *ktimer = &apic->lapic_timer;
1802 WARN_ON(preemptible());
1803 if (apic->lapic_timer.hv_timer_in_use)
1804 cancel_hv_timer(apic);
1805 if (!apic_lvtt_period(apic) && atomic_read(&ktimer->pending))
1808 if (apic_lvtt_period(apic) || apic_lvtt_oneshot(apic))
1809 start_sw_period(apic);
1810 else if (apic_lvtt_tscdeadline(apic))
1811 start_sw_tscdeadline(apic);
1812 trace_kvm_hv_timer_state(apic->vcpu->vcpu_id, false);
1815 static void restart_apic_timer(struct kvm_lapic *apic)
1819 if (!apic_lvtt_period(apic) && atomic_read(&apic->lapic_timer.pending))
1822 if (!start_hv_timer(apic))
1823 start_sw_timer(apic);
1828 void kvm_lapic_expired_hv_timer(struct kvm_vcpu *vcpu)
1830 struct kvm_lapic *apic = vcpu->arch.apic;
1833 /* If the preempt notifier has already run, it also called apic_timer_expired */
1834 if (!apic->lapic_timer.hv_timer_in_use)
1836 WARN_ON(swait_active(&vcpu->wq));
1837 cancel_hv_timer(apic);
1838 apic_timer_expired(apic);
1840 if (apic_lvtt_period(apic) && apic->lapic_timer.period) {
1841 advance_periodic_target_expiration(apic);
1842 restart_apic_timer(apic);
1847 EXPORT_SYMBOL_GPL(kvm_lapic_expired_hv_timer);
1849 void kvm_lapic_switch_to_hv_timer(struct kvm_vcpu *vcpu)
1851 restart_apic_timer(vcpu->arch.apic);
1853 EXPORT_SYMBOL_GPL(kvm_lapic_switch_to_hv_timer);
1855 void kvm_lapic_switch_to_sw_timer(struct kvm_vcpu *vcpu)
1857 struct kvm_lapic *apic = vcpu->arch.apic;
1860 /* Possibly the TSC deadline timer is not enabled yet */
1861 if (apic->lapic_timer.hv_timer_in_use)
1862 start_sw_timer(apic);
1865 EXPORT_SYMBOL_GPL(kvm_lapic_switch_to_sw_timer);
1867 void kvm_lapic_restart_hv_timer(struct kvm_vcpu *vcpu)
1869 struct kvm_lapic *apic = vcpu->arch.apic;
1871 WARN_ON(!apic->lapic_timer.hv_timer_in_use);
1872 restart_apic_timer(apic);
1875 static void start_apic_timer(struct kvm_lapic *apic)
1877 atomic_set(&apic->lapic_timer.pending, 0);
1879 if ((apic_lvtt_period(apic) || apic_lvtt_oneshot(apic))
1880 && !set_target_expiration(apic))
1883 restart_apic_timer(apic);
1886 static void apic_manage_nmi_watchdog(struct kvm_lapic *apic, u32 lvt0_val)
1888 bool lvt0_in_nmi_mode = apic_lvt_nmi_mode(lvt0_val);
1890 if (apic->lvt0_in_nmi_mode != lvt0_in_nmi_mode) {
1891 apic->lvt0_in_nmi_mode = lvt0_in_nmi_mode;
1892 if (lvt0_in_nmi_mode) {
1893 atomic_inc(&apic->vcpu->kvm->arch.vapics_in_nmi_mode);
1895 atomic_dec(&apic->vcpu->kvm->arch.vapics_in_nmi_mode);
1899 int kvm_lapic_reg_write(struct kvm_lapic *apic, u32 reg, u32 val)
1903 trace_kvm_apic_write(reg, val);
1906 case APIC_ID: /* Local APIC ID */
1907 if (!apic_x2apic_mode(apic))
1908 kvm_apic_set_xapic_id(apic, val >> 24);
1914 report_tpr_access(apic, true);
1915 apic_set_tpr(apic, val & 0xff);
1923 if (!apic_x2apic_mode(apic))
1924 kvm_apic_set_ldr(apic, val & APIC_LDR_MASK);
1930 if (!apic_x2apic_mode(apic)) {
1931 kvm_lapic_set_reg(apic, APIC_DFR, val | 0x0FFFFFFF);
1932 apic->vcpu->kvm->arch.apic_map_dirty = true;
1939 if (kvm_lapic_get_reg(apic, APIC_LVR) & APIC_LVR_DIRECTED_EOI)
1940 mask |= APIC_SPIV_DIRECTED_EOI;
1941 apic_set_spiv(apic, val & mask);
1942 if (!(val & APIC_SPIV_APIC_ENABLED)) {
1946 for (i = 0; i < KVM_APIC_LVT_NUM; i++) {
1947 lvt_val = kvm_lapic_get_reg(apic,
1948 APIC_LVTT + 0x10 * i);
1949 kvm_lapic_set_reg(apic, APIC_LVTT + 0x10 * i,
1950 lvt_val | APIC_LVT_MASKED);
1952 apic_update_lvtt(apic);
1953 atomic_set(&apic->lapic_timer.pending, 0);
1959 /* No delay here, so we always clear the pending bit */
1961 kvm_apic_send_ipi(apic, val, kvm_lapic_get_reg(apic, APIC_ICR2));
1962 kvm_lapic_set_reg(apic, APIC_ICR, val);
1966 if (!apic_x2apic_mode(apic))
1968 kvm_lapic_set_reg(apic, APIC_ICR2, val);
1972 apic_manage_nmi_watchdog(apic, val);
1978 /* TODO: Check vector */
1982 if (!kvm_apic_sw_enabled(apic))
1983 val |= APIC_LVT_MASKED;
1984 size = ARRAY_SIZE(apic_lvt_mask);
1985 index = array_index_nospec(
1986 (reg - APIC_LVTT) >> 4, size);
1987 val &= apic_lvt_mask[index];
1988 kvm_lapic_set_reg(apic, reg, val);
1993 if (!kvm_apic_sw_enabled(apic))
1994 val |= APIC_LVT_MASKED;
1995 val &= (apic_lvt_mask[0] | apic->lapic_timer.timer_mode_mask);
1996 kvm_lapic_set_reg(apic, APIC_LVTT, val);
1997 apic_update_lvtt(apic);
2001 if (apic_lvtt_tscdeadline(apic))
2004 hrtimer_cancel(&apic->lapic_timer.timer);
2005 kvm_lapic_set_reg(apic, APIC_TMICT, val);
2006 start_apic_timer(apic);
2010 uint32_t old_divisor = apic->divide_count;
2012 kvm_lapic_set_reg(apic, APIC_TDCR, val);
2013 update_divide_count(apic);
2014 if (apic->divide_count != old_divisor &&
2015 apic->lapic_timer.period) {
2016 hrtimer_cancel(&apic->lapic_timer.timer);
2017 update_target_expiration(apic, old_divisor);
2018 restart_apic_timer(apic);
2023 if (apic_x2apic_mode(apic) && val != 0)
2028 if (apic_x2apic_mode(apic)) {
2029 kvm_lapic_reg_write(apic, APIC_ICR, 0x40000 | (val & 0xff));
2038 kvm_recalculate_apic_map(apic->vcpu->kvm);
2042 EXPORT_SYMBOL_GPL(kvm_lapic_reg_write);
2044 static int apic_mmio_write(struct kvm_vcpu *vcpu, struct kvm_io_device *this,
2045 gpa_t address, int len, const void *data)
2047 struct kvm_lapic *apic = to_lapic(this);
2048 unsigned int offset = address - apic->base_address;
2051 if (!apic_mmio_in_range(apic, address))
2054 if (!kvm_apic_hw_enabled(apic) || apic_x2apic_mode(apic)) {
2055 if (!kvm_check_has_quirk(vcpu->kvm,
2056 KVM_X86_QUIRK_LAPIC_MMIO_HOLE))
2063 * APIC register must be aligned on 128-bits boundary.
2064 * 32/64/128 bits registers must be accessed thru 32 bits.
2067 if (len != 4 || (offset & 0xf))
2072 kvm_lapic_reg_write(apic, offset & 0xff0, val);
2077 void kvm_lapic_set_eoi(struct kvm_vcpu *vcpu)
2079 kvm_lapic_reg_write(vcpu->arch.apic, APIC_EOI, 0);
2081 EXPORT_SYMBOL_GPL(kvm_lapic_set_eoi);
2083 /* emulate APIC access in a trap manner */
2084 void kvm_apic_write_nodecode(struct kvm_vcpu *vcpu, u32 offset)
2088 /* hw has done the conditional check and inst decode */
2091 kvm_lapic_reg_read(vcpu->arch.apic, offset, 4, &val);
2093 /* TODO: optimize to just emulate side effect w/o one more write */
2094 kvm_lapic_reg_write(vcpu->arch.apic, offset, val);
2096 EXPORT_SYMBOL_GPL(kvm_apic_write_nodecode);
2098 void kvm_free_lapic(struct kvm_vcpu *vcpu)
2100 struct kvm_lapic *apic = vcpu->arch.apic;
2102 if (!vcpu->arch.apic)
2105 hrtimer_cancel(&apic->lapic_timer.timer);
2107 if (!(vcpu->arch.apic_base & MSR_IA32_APICBASE_ENABLE))
2108 static_key_slow_dec_deferred(&apic_hw_disabled);
2110 if (!apic->sw_enabled)
2111 static_key_slow_dec_deferred(&apic_sw_disabled);
2114 free_page((unsigned long)apic->regs);
2120 *----------------------------------------------------------------------
2122 *----------------------------------------------------------------------
2124 u64 kvm_get_lapic_tscdeadline_msr(struct kvm_vcpu *vcpu)
2126 struct kvm_lapic *apic = vcpu->arch.apic;
2128 if (!lapic_in_kernel(vcpu) ||
2129 !apic_lvtt_tscdeadline(apic))
2132 return apic->lapic_timer.tscdeadline;
2135 void kvm_set_lapic_tscdeadline_msr(struct kvm_vcpu *vcpu, u64 data)
2137 struct kvm_lapic *apic = vcpu->arch.apic;
2139 if (!lapic_in_kernel(vcpu) || apic_lvtt_oneshot(apic) ||
2140 apic_lvtt_period(apic))
2143 hrtimer_cancel(&apic->lapic_timer.timer);
2144 apic->lapic_timer.tscdeadline = data;
2145 start_apic_timer(apic);
2148 void kvm_lapic_set_tpr(struct kvm_vcpu *vcpu, unsigned long cr8)
2150 struct kvm_lapic *apic = vcpu->arch.apic;
2152 apic_set_tpr(apic, ((cr8 & 0x0f) << 4)
2153 | (kvm_lapic_get_reg(apic, APIC_TASKPRI) & 4));
2156 u64 kvm_lapic_get_cr8(struct kvm_vcpu *vcpu)
2160 tpr = (u64) kvm_lapic_get_reg(vcpu->arch.apic, APIC_TASKPRI);
2162 return (tpr & 0xf0) >> 4;
2165 void kvm_lapic_set_base(struct kvm_vcpu *vcpu, u64 value)
2167 u64 old_value = vcpu->arch.apic_base;
2168 struct kvm_lapic *apic = vcpu->arch.apic;
2171 value |= MSR_IA32_APICBASE_BSP;
2173 vcpu->arch.apic_base = value;
2175 if ((old_value ^ value) & MSR_IA32_APICBASE_ENABLE)
2176 kvm_update_cpuid(vcpu);
2181 /* update jump label if enable bit changes */
2182 if ((old_value ^ value) & MSR_IA32_APICBASE_ENABLE) {
2183 if (value & MSR_IA32_APICBASE_ENABLE) {
2184 kvm_apic_set_xapic_id(apic, vcpu->vcpu_id);
2185 static_key_slow_dec_deferred(&apic_hw_disabled);
2187 static_key_slow_inc(&apic_hw_disabled.key);
2188 vcpu->kvm->arch.apic_map_dirty = true;
2192 if (((old_value ^ value) & X2APIC_ENABLE) && (value & X2APIC_ENABLE))
2193 kvm_apic_set_x2apic_id(apic, vcpu->vcpu_id);
2195 if ((old_value ^ value) & (MSR_IA32_APICBASE_ENABLE | X2APIC_ENABLE))
2196 kvm_x86_ops.set_virtual_apic_mode(vcpu);
2198 apic->base_address = apic->vcpu->arch.apic_base &
2199 MSR_IA32_APICBASE_BASE;
2201 if ((value & MSR_IA32_APICBASE_ENABLE) &&
2202 apic->base_address != APIC_DEFAULT_PHYS_BASE)
2203 pr_warn_once("APIC base relocation is unsupported by KVM");
2206 void kvm_apic_update_apicv(struct kvm_vcpu *vcpu)
2208 struct kvm_lapic *apic = vcpu->arch.apic;
2210 if (vcpu->arch.apicv_active) {
2211 /* irr_pending is always true when apicv is activated. */
2212 apic->irr_pending = true;
2213 apic->isr_count = 1;
2215 apic->irr_pending = (apic_search_irr(apic) != -1);
2216 apic->isr_count = count_vectors(apic->regs + APIC_ISR);
2219 EXPORT_SYMBOL_GPL(kvm_apic_update_apicv);
2221 void kvm_lapic_reset(struct kvm_vcpu *vcpu, bool init_event)
2223 struct kvm_lapic *apic = vcpu->arch.apic;
2229 vcpu->kvm->arch.apic_map_dirty = false;
2230 /* Stop the timer in case it's a reset to an active apic */
2231 hrtimer_cancel(&apic->lapic_timer.timer);
2234 kvm_lapic_set_base(vcpu, APIC_DEFAULT_PHYS_BASE |
2235 MSR_IA32_APICBASE_ENABLE);
2236 kvm_apic_set_xapic_id(apic, vcpu->vcpu_id);
2238 kvm_apic_set_version(apic->vcpu);
2240 for (i = 0; i < KVM_APIC_LVT_NUM; i++)
2241 kvm_lapic_set_reg(apic, APIC_LVTT + 0x10 * i, APIC_LVT_MASKED);
2242 apic_update_lvtt(apic);
2243 if (kvm_vcpu_is_reset_bsp(vcpu) &&
2244 kvm_check_has_quirk(vcpu->kvm, KVM_X86_QUIRK_LINT0_REENABLED))
2245 kvm_lapic_set_reg(apic, APIC_LVT0,
2246 SET_APIC_DELIVERY_MODE(0, APIC_MODE_EXTINT));
2247 apic_manage_nmi_watchdog(apic, kvm_lapic_get_reg(apic, APIC_LVT0));
2249 kvm_lapic_set_reg(apic, APIC_DFR, 0xffffffffU);
2250 apic_set_spiv(apic, 0xff);
2251 kvm_lapic_set_reg(apic, APIC_TASKPRI, 0);
2252 if (!apic_x2apic_mode(apic))
2253 kvm_apic_set_ldr(apic, 0);
2254 kvm_lapic_set_reg(apic, APIC_ESR, 0);
2255 kvm_lapic_set_reg(apic, APIC_ICR, 0);
2256 kvm_lapic_set_reg(apic, APIC_ICR2, 0);
2257 kvm_lapic_set_reg(apic, APIC_TDCR, 0);
2258 kvm_lapic_set_reg(apic, APIC_TMICT, 0);
2259 for (i = 0; i < 8; i++) {
2260 kvm_lapic_set_reg(apic, APIC_IRR + 0x10 * i, 0);
2261 kvm_lapic_set_reg(apic, APIC_ISR + 0x10 * i, 0);
2262 kvm_lapic_set_reg(apic, APIC_TMR + 0x10 * i, 0);
2264 kvm_apic_update_apicv(vcpu);
2265 apic->highest_isr_cache = -1;
2266 update_divide_count(apic);
2267 atomic_set(&apic->lapic_timer.pending, 0);
2268 if (kvm_vcpu_is_bsp(vcpu))
2269 kvm_lapic_set_base(vcpu,
2270 vcpu->arch.apic_base | MSR_IA32_APICBASE_BSP);
2271 vcpu->arch.pv_eoi.msr_val = 0;
2272 apic_update_ppr(apic);
2273 if (vcpu->arch.apicv_active) {
2274 kvm_x86_ops.apicv_post_state_restore(vcpu);
2275 kvm_x86_ops.hwapic_irr_update(vcpu, -1);
2276 kvm_x86_ops.hwapic_isr_update(vcpu, -1);
2279 vcpu->arch.apic_arb_prio = 0;
2280 vcpu->arch.apic_attention = 0;
2282 kvm_recalculate_apic_map(vcpu->kvm);
2286 *----------------------------------------------------------------------
2288 *----------------------------------------------------------------------
2291 static bool lapic_is_periodic(struct kvm_lapic *apic)
2293 return apic_lvtt_period(apic);
2296 int apic_has_pending_timer(struct kvm_vcpu *vcpu)
2298 struct kvm_lapic *apic = vcpu->arch.apic;
2300 if (apic_enabled(apic) && apic_lvt_enabled(apic, APIC_LVTT))
2301 return atomic_read(&apic->lapic_timer.pending);
2306 int kvm_apic_local_deliver(struct kvm_lapic *apic, int lvt_type)
2308 u32 reg = kvm_lapic_get_reg(apic, lvt_type);
2309 int vector, mode, trig_mode;
2311 if (kvm_apic_hw_enabled(apic) && !(reg & APIC_LVT_MASKED)) {
2312 vector = reg & APIC_VECTOR_MASK;
2313 mode = reg & APIC_MODE_MASK;
2314 trig_mode = reg & APIC_LVT_LEVEL_TRIGGER;
2315 return __apic_accept_irq(apic, mode, vector, 1, trig_mode,
2321 void kvm_apic_nmi_wd_deliver(struct kvm_vcpu *vcpu)
2323 struct kvm_lapic *apic = vcpu->arch.apic;
2326 kvm_apic_local_deliver(apic, APIC_LVT0);
2329 static const struct kvm_io_device_ops apic_mmio_ops = {
2330 .read = apic_mmio_read,
2331 .write = apic_mmio_write,
2334 static enum hrtimer_restart apic_timer_fn(struct hrtimer *data)
2336 struct kvm_timer *ktimer = container_of(data, struct kvm_timer, timer);
2337 struct kvm_lapic *apic = container_of(ktimer, struct kvm_lapic, lapic_timer);
2339 apic_timer_expired(apic);
2341 if (lapic_is_periodic(apic)) {
2342 advance_periodic_target_expiration(apic);
2343 hrtimer_add_expires_ns(&ktimer->timer, ktimer->period);
2344 return HRTIMER_RESTART;
2346 return HRTIMER_NORESTART;
2349 int kvm_create_lapic(struct kvm_vcpu *vcpu, int timer_advance_ns)
2351 struct kvm_lapic *apic;
2353 ASSERT(vcpu != NULL);
2355 apic = kzalloc(sizeof(*apic), GFP_KERNEL_ACCOUNT);
2359 vcpu->arch.apic = apic;
2361 apic->regs = (void *)get_zeroed_page(GFP_KERNEL_ACCOUNT);
2363 printk(KERN_ERR "malloc apic regs error for vcpu %x\n",
2365 goto nomem_free_apic;
2369 hrtimer_init(&apic->lapic_timer.timer, CLOCK_MONOTONIC,
2370 HRTIMER_MODE_ABS_HARD);
2371 apic->lapic_timer.timer.function = apic_timer_fn;
2372 if (timer_advance_ns == -1) {
2373 apic->lapic_timer.timer_advance_ns = LAPIC_TIMER_ADVANCE_NS_INIT;
2374 lapic_timer_advance_dynamic = true;
2376 apic->lapic_timer.timer_advance_ns = timer_advance_ns;
2377 lapic_timer_advance_dynamic = false;
2381 * APIC is created enabled. This will prevent kvm_lapic_set_base from
2382 * thinking that APIC state has changed.
2384 vcpu->arch.apic_base = MSR_IA32_APICBASE_ENABLE;
2385 static_key_slow_inc(&apic_sw_disabled.key); /* sw disabled at reset */
2386 kvm_iodevice_init(&apic->dev, &apic_mmio_ops);
2391 vcpu->arch.apic = NULL;
2396 int kvm_apic_has_interrupt(struct kvm_vcpu *vcpu)
2398 struct kvm_lapic *apic = vcpu->arch.apic;
2401 if (!kvm_apic_hw_enabled(apic))
2404 __apic_update_ppr(apic, &ppr);
2405 return apic_has_interrupt_for_ppr(apic, ppr);
2408 int kvm_apic_accept_pic_intr(struct kvm_vcpu *vcpu)
2410 u32 lvt0 = kvm_lapic_get_reg(vcpu->arch.apic, APIC_LVT0);
2412 if (!kvm_apic_hw_enabled(vcpu->arch.apic))
2414 if ((lvt0 & APIC_LVT_MASKED) == 0 &&
2415 GET_APIC_DELIVERY_MODE(lvt0) == APIC_MODE_EXTINT)
2420 void kvm_inject_apic_timer_irqs(struct kvm_vcpu *vcpu)
2422 struct kvm_lapic *apic = vcpu->arch.apic;
2424 if (atomic_read(&apic->lapic_timer.pending) > 0) {
2425 kvm_apic_inject_pending_timer_irqs(apic);
2426 atomic_set(&apic->lapic_timer.pending, 0);
2430 int kvm_get_apic_interrupt(struct kvm_vcpu *vcpu)
2432 int vector = kvm_apic_has_interrupt(vcpu);
2433 struct kvm_lapic *apic = vcpu->arch.apic;
2440 * We get here even with APIC virtualization enabled, if doing
2441 * nested virtualization and L1 runs with the "acknowledge interrupt
2442 * on exit" mode. Then we cannot inject the interrupt via RVI,
2443 * because the process would deliver it through the IDT.
2446 apic_clear_irr(vector, apic);
2447 if (test_bit(vector, vcpu_to_synic(vcpu)->auto_eoi_bitmap)) {
2449 * For auto-EOI interrupts, there might be another pending
2450 * interrupt above PPR, so check whether to raise another
2453 apic_update_ppr(apic);
2456 * For normal interrupts, PPR has been raised and there cannot
2457 * be a higher-priority pending interrupt---except if there was
2458 * a concurrent interrupt injection, but that would have
2459 * triggered KVM_REQ_EVENT already.
2461 apic_set_isr(vector, apic);
2462 __apic_update_ppr(apic, &ppr);
2468 static int kvm_apic_state_fixup(struct kvm_vcpu *vcpu,
2469 struct kvm_lapic_state *s, bool set)
2471 if (apic_x2apic_mode(vcpu->arch.apic)) {
2472 u32 *id = (u32 *)(s->regs + APIC_ID);
2473 u32 *ldr = (u32 *)(s->regs + APIC_LDR);
2475 if (vcpu->kvm->arch.x2apic_format) {
2476 if (*id != vcpu->vcpu_id)
2485 /* In x2APIC mode, the LDR is fixed and based on the id */
2487 *ldr = kvm_apic_calc_x2apic_ldr(*id);
2493 int kvm_apic_get_state(struct kvm_vcpu *vcpu, struct kvm_lapic_state *s)
2495 memcpy(s->regs, vcpu->arch.apic->regs, sizeof(*s));
2496 return kvm_apic_state_fixup(vcpu, s, false);
2499 int kvm_apic_set_state(struct kvm_vcpu *vcpu, struct kvm_lapic_state *s)
2501 struct kvm_lapic *apic = vcpu->arch.apic;
2504 kvm_lapic_set_base(vcpu, vcpu->arch.apic_base);
2505 /* set SPIV separately to get count of SW disabled APICs right */
2506 apic_set_spiv(apic, *((u32 *)(s->regs + APIC_SPIV)));
2508 r = kvm_apic_state_fixup(vcpu, s, true);
2510 kvm_recalculate_apic_map(vcpu->kvm);
2513 memcpy(vcpu->arch.apic->regs, s->regs, sizeof(*s));
2515 kvm_recalculate_apic_map(vcpu->kvm);
2516 kvm_apic_set_version(vcpu);
2518 apic_update_ppr(apic);
2519 hrtimer_cancel(&apic->lapic_timer.timer);
2520 apic_update_lvtt(apic);
2521 apic_manage_nmi_watchdog(apic, kvm_lapic_get_reg(apic, APIC_LVT0));
2522 update_divide_count(apic);
2523 start_apic_timer(apic);
2524 kvm_apic_update_apicv(vcpu);
2525 apic->highest_isr_cache = -1;
2526 if (vcpu->arch.apicv_active) {
2527 kvm_x86_ops.apicv_post_state_restore(vcpu);
2528 kvm_x86_ops.hwapic_irr_update(vcpu,
2529 apic_find_highest_irr(apic));
2530 kvm_x86_ops.hwapic_isr_update(vcpu,
2531 apic_find_highest_isr(apic));
2533 kvm_make_request(KVM_REQ_EVENT, vcpu);
2534 if (ioapic_in_kernel(vcpu->kvm))
2535 kvm_rtc_eoi_tracking_restore_one(vcpu);
2537 vcpu->arch.apic_arb_prio = 0;
2542 void __kvm_migrate_apic_timer(struct kvm_vcpu *vcpu)
2544 struct hrtimer *timer;
2546 if (!lapic_in_kernel(vcpu) ||
2547 kvm_can_post_timer_interrupt(vcpu))
2550 timer = &vcpu->arch.apic->lapic_timer.timer;
2551 if (hrtimer_cancel(timer))
2552 hrtimer_start_expires(timer, HRTIMER_MODE_ABS_HARD);
2556 * apic_sync_pv_eoi_from_guest - called on vmexit or cancel interrupt
2558 * Detect whether guest triggered PV EOI since the
2559 * last entry. If yes, set EOI on guests's behalf.
2560 * Clear PV EOI in guest memory in any case.
2562 static void apic_sync_pv_eoi_from_guest(struct kvm_vcpu *vcpu,
2563 struct kvm_lapic *apic)
2568 * PV EOI state is derived from KVM_APIC_PV_EOI_PENDING in host
2569 * and KVM_PV_EOI_ENABLED in guest memory as follows:
2571 * KVM_APIC_PV_EOI_PENDING is unset:
2572 * -> host disabled PV EOI.
2573 * KVM_APIC_PV_EOI_PENDING is set, KVM_PV_EOI_ENABLED is set:
2574 * -> host enabled PV EOI, guest did not execute EOI yet.
2575 * KVM_APIC_PV_EOI_PENDING is set, KVM_PV_EOI_ENABLED is unset:
2576 * -> host enabled PV EOI, guest executed EOI.
2578 BUG_ON(!pv_eoi_enabled(vcpu));
2579 pending = pv_eoi_get_pending(vcpu);
2581 * Clear pending bit in any case: it will be set again on vmentry.
2582 * While this might not be ideal from performance point of view,
2583 * this makes sure pv eoi is only enabled when we know it's safe.
2585 pv_eoi_clr_pending(vcpu);
2588 vector = apic_set_eoi(apic);
2589 trace_kvm_pv_eoi(apic, vector);
2592 void kvm_lapic_sync_from_vapic(struct kvm_vcpu *vcpu)
2596 if (test_bit(KVM_APIC_PV_EOI_PENDING, &vcpu->arch.apic_attention))
2597 apic_sync_pv_eoi_from_guest(vcpu, vcpu->arch.apic);
2599 if (!test_bit(KVM_APIC_CHECK_VAPIC, &vcpu->arch.apic_attention))
2602 if (kvm_read_guest_cached(vcpu->kvm, &vcpu->arch.apic->vapic_cache, &data,
2606 apic_set_tpr(vcpu->arch.apic, data & 0xff);
2610 * apic_sync_pv_eoi_to_guest - called before vmentry
2612 * Detect whether it's safe to enable PV EOI and
2615 static void apic_sync_pv_eoi_to_guest(struct kvm_vcpu *vcpu,
2616 struct kvm_lapic *apic)
2618 if (!pv_eoi_enabled(vcpu) ||
2619 /* IRR set or many bits in ISR: could be nested. */
2620 apic->irr_pending ||
2621 /* Cache not set: could be safe but we don't bother. */
2622 apic->highest_isr_cache == -1 ||
2623 /* Need EOI to update ioapic. */
2624 kvm_ioapic_handles_vector(apic, apic->highest_isr_cache)) {
2626 * PV EOI was disabled by apic_sync_pv_eoi_from_guest
2627 * so we need not do anything here.
2632 pv_eoi_set_pending(apic->vcpu);
2635 void kvm_lapic_sync_to_vapic(struct kvm_vcpu *vcpu)
2638 int max_irr, max_isr;
2639 struct kvm_lapic *apic = vcpu->arch.apic;
2641 apic_sync_pv_eoi_to_guest(vcpu, apic);
2643 if (!test_bit(KVM_APIC_CHECK_VAPIC, &vcpu->arch.apic_attention))
2646 tpr = kvm_lapic_get_reg(apic, APIC_TASKPRI) & 0xff;
2647 max_irr = apic_find_highest_irr(apic);
2650 max_isr = apic_find_highest_isr(apic);
2653 data = (tpr & 0xff) | ((max_isr & 0xf0) << 8) | (max_irr << 24);
2655 kvm_write_guest_cached(vcpu->kvm, &vcpu->arch.apic->vapic_cache, &data,
2659 int kvm_lapic_set_vapic_addr(struct kvm_vcpu *vcpu, gpa_t vapic_addr)
2662 if (kvm_gfn_to_hva_cache_init(vcpu->kvm,
2663 &vcpu->arch.apic->vapic_cache,
2664 vapic_addr, sizeof(u32)))
2666 __set_bit(KVM_APIC_CHECK_VAPIC, &vcpu->arch.apic_attention);
2668 __clear_bit(KVM_APIC_CHECK_VAPIC, &vcpu->arch.apic_attention);
2671 vcpu->arch.apic->vapic_addr = vapic_addr;
2675 int kvm_x2apic_msr_write(struct kvm_vcpu *vcpu, u32 msr, u64 data)
2677 struct kvm_lapic *apic = vcpu->arch.apic;
2678 u32 reg = (msr - APIC_BASE_MSR) << 4;
2680 if (!lapic_in_kernel(vcpu) || !apic_x2apic_mode(apic))
2683 if (reg == APIC_ICR2)
2686 /* if this is ICR write vector before command */
2687 if (reg == APIC_ICR)
2688 kvm_lapic_reg_write(apic, APIC_ICR2, (u32)(data >> 32));
2689 return kvm_lapic_reg_write(apic, reg, (u32)data);
2692 int kvm_x2apic_msr_read(struct kvm_vcpu *vcpu, u32 msr, u64 *data)
2694 struct kvm_lapic *apic = vcpu->arch.apic;
2695 u32 reg = (msr - APIC_BASE_MSR) << 4, low, high = 0;
2697 if (!lapic_in_kernel(vcpu) || !apic_x2apic_mode(apic))
2700 if (reg == APIC_DFR || reg == APIC_ICR2)
2703 if (kvm_lapic_reg_read(apic, reg, 4, &low))
2705 if (reg == APIC_ICR)
2706 kvm_lapic_reg_read(apic, APIC_ICR2, 4, &high);
2708 *data = (((u64)high) << 32) | low;
2713 int kvm_hv_vapic_msr_write(struct kvm_vcpu *vcpu, u32 reg, u64 data)
2715 struct kvm_lapic *apic = vcpu->arch.apic;
2717 if (!lapic_in_kernel(vcpu))
2720 /* if this is ICR write vector before command */
2721 if (reg == APIC_ICR)
2722 kvm_lapic_reg_write(apic, APIC_ICR2, (u32)(data >> 32));
2723 return kvm_lapic_reg_write(apic, reg, (u32)data);
2726 int kvm_hv_vapic_msr_read(struct kvm_vcpu *vcpu, u32 reg, u64 *data)
2728 struct kvm_lapic *apic = vcpu->arch.apic;
2731 if (!lapic_in_kernel(vcpu))
2734 if (kvm_lapic_reg_read(apic, reg, 4, &low))
2736 if (reg == APIC_ICR)
2737 kvm_lapic_reg_read(apic, APIC_ICR2, 4, &high);
2739 *data = (((u64)high) << 32) | low;
2744 int kvm_lapic_enable_pv_eoi(struct kvm_vcpu *vcpu, u64 data, unsigned long len)
2746 u64 addr = data & ~KVM_MSR_ENABLED;
2747 struct gfn_to_hva_cache *ghc = &vcpu->arch.pv_eoi.data;
2748 unsigned long new_len;
2750 if (!IS_ALIGNED(addr, 4))
2753 vcpu->arch.pv_eoi.msr_val = data;
2754 if (!pv_eoi_enabled(vcpu))
2757 if (addr == ghc->gpa && len <= ghc->len)
2762 return kvm_gfn_to_hva_cache_init(vcpu->kvm, ghc, addr, new_len);
2765 void kvm_apic_accept_events(struct kvm_vcpu *vcpu)
2767 struct kvm_lapic *apic = vcpu->arch.apic;
2771 if (!lapic_in_kernel(vcpu) || !apic->pending_events)
2775 * INITs are latched while CPU is in specific states
2776 * (SMM, VMX non-root mode, SVM with GIF=0).
2777 * Because a CPU cannot be in these states immediately
2778 * after it has processed an INIT signal (and thus in
2779 * KVM_MP_STATE_INIT_RECEIVED state), just eat SIPIs
2780 * and leave the INIT pending.
2782 if (kvm_vcpu_latch_init(vcpu)) {
2783 WARN_ON_ONCE(vcpu->arch.mp_state == KVM_MP_STATE_INIT_RECEIVED);
2784 if (test_bit(KVM_APIC_SIPI, &apic->pending_events))
2785 clear_bit(KVM_APIC_SIPI, &apic->pending_events);
2789 pe = xchg(&apic->pending_events, 0);
2790 if (test_bit(KVM_APIC_INIT, &pe)) {
2791 kvm_vcpu_reset(vcpu, true);
2792 if (kvm_vcpu_is_bsp(apic->vcpu))
2793 vcpu->arch.mp_state = KVM_MP_STATE_RUNNABLE;
2795 vcpu->arch.mp_state = KVM_MP_STATE_INIT_RECEIVED;
2797 if (test_bit(KVM_APIC_SIPI, &pe) &&
2798 vcpu->arch.mp_state == KVM_MP_STATE_INIT_RECEIVED) {
2799 /* evaluate pending_events before reading the vector */
2801 sipi_vector = apic->sipi_vector;
2802 kvm_vcpu_deliver_sipi_vector(vcpu, sipi_vector);
2803 vcpu->arch.mp_state = KVM_MP_STATE_RUNNABLE;
2807 void kvm_lapic_init(void)
2809 /* do not patch jump label more than once per second */
2810 jump_label_rate_limit(&apic_hw_disabled, HZ);
2811 jump_label_rate_limit(&apic_sw_disabled, HZ);
2814 void kvm_lapic_exit(void)
2816 static_key_deferred_flush(&apic_hw_disabled);
2817 static_key_deferred_flush(&apic_sw_disabled);