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