File Index
Files and directories
Sign in
FILE

lapic.c

File preview with syntax highlighting.

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