xref: /linux/arch/x86/kvm/svm/avic.c (revision d0ee290071b475410476b4126c72da4bf6a2194c)
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  * Kernel-based Virtual Machine driver for Linux
4  *
5  * AMD SVM support
6  *
7  * Copyright (C) 2006 Qumranet, Inc.
8  * Copyright 2010 Red Hat, Inc. and/or its affiliates.
9  *
10  * Authors:
11  *   Yaniv Kamay  <yaniv@qumranet.com>
12  *   Avi Kivity   <avi@qumranet.com>
13  */
14 
15 #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
16 
17 #include <linux/kvm_types.h>
18 #include <linux/hashtable.h>
19 #include <linux/amd-iommu.h>
20 #include <linux/kvm_host.h>
21 #include <linux/kvm_irqfd.h>
22 #include <linux/sysfs.h>
23 
24 #include <asm/irq_remapping.h>
25 #include <asm/msr.h>
26 
27 #include "trace.h"
28 #include "lapic.h"
29 #include "x86.h"
30 #include "irq.h"
31 #include "svm.h"
32 
33 /*
34  * Encode the arbitrary VM ID and the vCPU's _index_ into the GATag so that
35  * KVM can retrieve the correct vCPU from a GALog entry if an interrupt can't
36  * be delivered, e.g. because the vCPU isn't running.  Use the vCPU's index
37  * instead of its ID (a.k.a. its default APIC ID), as KVM is guaranteed a fast
38  * lookup on the index, where as vCPUs whose index doesn't match their ID need
39  * to walk the entire xarray of vCPUs in the worst case scenario.
40  *
41  * For the vCPU index, use however many bits are currently allowed for the max
42  * guest physical APIC ID (limited by the size of the physical ID table), and
43  * use whatever bits remain to assign arbitrary AVIC IDs to VMs.  Note, the
44  * size of the GATag is defined by hardware (32 bits), but is an opaque value
45  * as far as hardware is concerned.
46  */
47 #define AVIC_VCPU_IDX_MASK		AVIC_PHYSICAL_MAX_INDEX_MASK
48 
49 #define AVIC_VM_ID_SHIFT		HWEIGHT32(AVIC_PHYSICAL_MAX_INDEX_MASK)
50 #define AVIC_VM_ID_MASK			(GENMASK(31, AVIC_VM_ID_SHIFT) >> AVIC_VM_ID_SHIFT)
51 
52 #define AVIC_GATAG_TO_VMID(x)		((x >> AVIC_VM_ID_SHIFT) & AVIC_VM_ID_MASK)
53 #define AVIC_GATAG_TO_VCPUIDX(x)	(x & AVIC_VCPU_IDX_MASK)
54 
55 #define __AVIC_GATAG(vm_id, vcpu_idx)	((((vm_id) & AVIC_VM_ID_MASK) << AVIC_VM_ID_SHIFT) | \
56 					 ((vcpu_idx) & AVIC_VCPU_IDX_MASK))
57 #define AVIC_GATAG(vm_id, vcpu_idx)					\
58 ({									\
59 	u32 ga_tag = __AVIC_GATAG(vm_id, vcpu_idx);			\
60 									\
61 	WARN_ON_ONCE(AVIC_GATAG_TO_VCPUIDX(ga_tag) != (vcpu_idx));	\
62 	WARN_ON_ONCE(AVIC_GATAG_TO_VMID(ga_tag) != (vm_id));		\
63 	ga_tag;								\
64 })
65 
66 static_assert(__AVIC_GATAG(AVIC_VM_ID_MASK, AVIC_VCPU_IDX_MASK) == -1u);
67 
68 #define AVIC_AUTO_MODE -1
69 
avic_param_set(const char * val,const struct kernel_param * kp)70 static int avic_param_set(const char *val, const struct kernel_param *kp)
71 {
72 	if (val && sysfs_streq(val, "auto")) {
73 		*(int *)kp->arg = AVIC_AUTO_MODE;
74 		return 0;
75 	}
76 
77 	return param_set_bint(val, kp);
78 }
79 
avic_param_get(char * buffer,const struct kernel_param * kp)80 static int avic_param_get(char *buffer, const struct kernel_param *kp)
81 {
82 	int val = *(int *)kp->arg;
83 
84 	if (val == AVIC_AUTO_MODE)
85 		return sysfs_emit(buffer, "N\n");
86 
87 	return param_get_bool(buffer, kp);
88 }
89 
90 static const struct kernel_param_ops avic_ops = {
91 	.flags = KERNEL_PARAM_OPS_FL_NOARG,
92 	.set = avic_param_set,
93 	.get = avic_param_get,
94 };
95 
96 /*
97  * Enable / disable AVIC.  In "auto" mode (default behavior), AVIC is enabled
98  * for Zen4+ CPUs with x2AVIC (and all other criteria for enablement are met).
99  */
100 static int __ro_after_init avic = AVIC_AUTO_MODE;
101 module_param_cb(avic, &avic_ops, &avic, 0444);
102 __MODULE_PARM_TYPE(avic, "bool");
103 
104 module_param(enable_ipiv, bool, 0444);
105 
106 static bool __ro_after_init force_avic;
107 module_param_unsafe(force_avic, bool, 0444);
108 
109 /* Note:
110  * This hash table is used to map VM_ID to a struct kvm_svm,
111  * when handling AMD IOMMU GALOG notification to schedule in
112  * a particular vCPU.
113  */
114 #define SVM_VM_DATA_HASH_BITS	8
115 static DEFINE_HASHTABLE(svm_vm_data_hash, SVM_VM_DATA_HASH_BITS);
116 static u32 next_vm_id = 0;
117 static bool next_vm_id_wrapped = 0;
118 static DEFINE_SPINLOCK(svm_vm_data_hash_lock);
119 static bool x2avic_enabled;
120 static u32 x2avic_max_physical_id;
121 
avic_set_x2apic_msr_interception(struct vcpu_svm * svm,bool intercept)122 static void avic_set_x2apic_msr_interception(struct vcpu_svm *svm,
123 					     bool intercept)
124 {
125 	static const u32 x2avic_passthrough_msrs[] = {
126 		X2APIC_MSR(APIC_ID),
127 		X2APIC_MSR(APIC_LVR),
128 		X2APIC_MSR(APIC_TASKPRI),
129 		X2APIC_MSR(APIC_ARBPRI),
130 		X2APIC_MSR(APIC_PROCPRI),
131 		X2APIC_MSR(APIC_EOI),
132 		X2APIC_MSR(APIC_RRR),
133 		X2APIC_MSR(APIC_LDR),
134 		X2APIC_MSR(APIC_DFR),
135 		X2APIC_MSR(APIC_SPIV),
136 		X2APIC_MSR(APIC_ISR),
137 		X2APIC_MSR(APIC_TMR),
138 		X2APIC_MSR(APIC_IRR),
139 		X2APIC_MSR(APIC_ESR),
140 		X2APIC_MSR(APIC_ICR),
141 		X2APIC_MSR(APIC_ICR2),
142 
143 		/*
144 		 * Note!  Always intercept LVTT, as TSC-deadline timer mode
145 		 * isn't virtualized by hardware, and the CPU will generate a
146 		 * #GP instead of a #VMEXIT.
147 		 */
148 		X2APIC_MSR(APIC_LVTTHMR),
149 		X2APIC_MSR(APIC_LVTPC),
150 		X2APIC_MSR(APIC_LVT0),
151 		X2APIC_MSR(APIC_LVT1),
152 		X2APIC_MSR(APIC_LVTERR),
153 		X2APIC_MSR(APIC_TMICT),
154 		X2APIC_MSR(APIC_TMCCT),
155 		X2APIC_MSR(APIC_TDCR),
156 	};
157 	int i;
158 
159 	if (intercept == svm->x2avic_msrs_intercepted)
160 		return;
161 
162 	if (!x2avic_enabled)
163 		return;
164 
165 	for (i = 0; i < ARRAY_SIZE(x2avic_passthrough_msrs); i++)
166 		svm_set_intercept_for_msr(&svm->vcpu, x2avic_passthrough_msrs[i],
167 					  MSR_TYPE_RW, intercept);
168 
169 	svm->x2avic_msrs_intercepted = intercept;
170 }
171 
__avic_get_max_physical_id(struct kvm * kvm,struct kvm_vcpu * vcpu)172 static u32 __avic_get_max_physical_id(struct kvm *kvm, struct kvm_vcpu *vcpu)
173 {
174 	u32 arch_max;
175 
176 	/*
177 	 * Return the largest size (x2APIC) when querying without a vCPU, e.g.
178 	 * to allocate the per-VM table..
179 	 */
180 	if (x2avic_enabled && (!vcpu || apic_x2apic_mode(vcpu->arch.apic)))
181 		arch_max = x2avic_max_physical_id;
182 	else
183 		arch_max = AVIC_MAX_PHYSICAL_ID;
184 
185 	/*
186 	 * Despite its name, KVM_CAP_MAX_VCPU_ID represents the maximum APIC ID
187 	 * plus one, so the max possible APIC ID is one less than that.
188 	 */
189 	return min(kvm->arch.max_vcpu_ids - 1, arch_max);
190 }
191 
avic_get_max_physical_id(struct kvm_vcpu * vcpu)192 static u32 avic_get_max_physical_id(struct kvm_vcpu *vcpu)
193 {
194 	return __avic_get_max_physical_id(vcpu->kvm, vcpu);
195 }
196 
avic_activate_vmcb(struct vcpu_svm * svm)197 static void avic_activate_vmcb(struct vcpu_svm *svm)
198 {
199 	struct vmcb *vmcb = svm->vmcb01.ptr;
200 	struct kvm_vcpu *vcpu = &svm->vcpu;
201 
202 	vmcb->control.int_ctl &= ~(AVIC_ENABLE_MASK | X2APIC_MODE_MASK);
203 	vmcb->control.avic_physical_id &= ~AVIC_PHYSICAL_MAX_INDEX_MASK;
204 	vmcb->control.avic_physical_id |= avic_get_max_physical_id(vcpu);
205 	vmcb->control.int_ctl |= AVIC_ENABLE_MASK;
206 
207 	svm_clr_intercept(svm, INTERCEPT_CR8_WRITE);
208 
209 	/*
210 	 * Flush the TLB when enabling (x2)AVIC and when transitioning between
211 	 * xAVIC and x2AVIC, as the CPU may have inserted a TLB entry for the
212 	 * "wrong" mapping.
213 	 *
214 	 * KVM uses a per-VM "scratch" page to back the APIC memslot, because
215 	 * KVM also uses per-VM page tables *and* maintains the page table (NPT
216 	 * or shadow page) mappings for said memslot even if one or more vCPUs
217 	 * have their local APIC hardware-disabled or are in x2APIC mode, i.e.
218 	 * even if one or more vCPUs' APIC MMIO BAR is effectively disabled.
219 	 *
220 	 * If xAVIC is fully enabled, hardware ignores the physical address in
221 	 * KVM's page tables, i.e. in the leaf SPTE for the APIC memslot, and
222 	 * instead redirects the access to the AVIC backing page, i.e. to the
223 	 * vCPU's virtual APIC page.  If xAVIC is not enabled (APIC is either
224 	 * hardware-disabled or in x2APIC mode), then guest accesses will use
225 	 * the page table mapping verbatim, i.e. will access the per-VM scratch
226 	 * page, as normal memory.
227 	 *
228 	 * In both cases, the CPU is allowed to cache TLB entries for the APIC
229 	 * base GPA.  So, KVM needs to flush the TLB when enabling xAVIC, as
230 	 * accesses need to be redirected to the virtual APIC page, but the TLB
231 	 * may contain entries pointing at the scratch page.  KVM also needs to
232 	 * flush the TLB when enabling x2AVIC, as accesses need to go to the
233 	 * scratch page, but the TLB may contain entries tagged as xAVIC, i.e.
234 	 * entries pointing to the vCPU's virtual APIC page.
235 	 */
236 	kvm_make_request(KVM_REQ_TLB_FLUSH_CURRENT, &svm->vcpu);
237 
238 	/*
239 	 * Note: KVM supports hybrid-AVIC mode, where KVM emulates x2APIC MSR
240 	 * accesses, while interrupt injection to a running vCPU can be
241 	 * achieved using AVIC doorbell.  KVM disables the APIC access page
242 	 * (deletes the memslot) if any vCPU has x2APIC enabled, thus enabling
243 	 * AVIC in hybrid mode activates only the doorbell mechanism.
244 	 */
245 	if (x2avic_enabled && apic_x2apic_mode(svm->vcpu.arch.apic)) {
246 		vmcb->control.int_ctl |= X2APIC_MODE_MASK;
247 
248 		/* Disabling MSR intercept for x2APIC registers */
249 		avic_set_x2apic_msr_interception(svm, false);
250 	} else {
251 		/* Enabling MSR intercept for x2APIC registers */
252 		avic_set_x2apic_msr_interception(svm, true);
253 	}
254 }
255 
avic_deactivate_vmcb(struct vcpu_svm * svm)256 static void avic_deactivate_vmcb(struct vcpu_svm *svm)
257 {
258 	struct vmcb *vmcb = svm->vmcb01.ptr;
259 
260 	vmcb->control.int_ctl &= ~(AVIC_ENABLE_MASK | X2APIC_MODE_MASK);
261 	vmcb->control.avic_physical_id &= ~AVIC_PHYSICAL_MAX_INDEX_MASK;
262 
263 	if (!is_sev_es_guest(&svm->vcpu))
264 		svm_set_intercept(svm, INTERCEPT_CR8_WRITE);
265 
266 	/*
267 	 * If running nested and the guest uses its own MSR bitmap, there
268 	 * is no need to update L0's msr bitmap
269 	 */
270 	if (is_guest_mode(&svm->vcpu) &&
271 	    vmcb12_is_intercept(&svm->nested.ctl, INTERCEPT_MSR_PROT))
272 		return;
273 
274 	/* Enabling MSR intercept for x2APIC registers */
275 	avic_set_x2apic_msr_interception(svm, true);
276 }
277 
278 /* Note:
279  * This function is called from IOMMU driver to notify
280  * SVM to schedule in a particular vCPU of a particular VM.
281  */
avic_ga_log_notifier(u32 ga_tag)282 static int avic_ga_log_notifier(u32 ga_tag)
283 {
284 	unsigned long flags;
285 	struct kvm_svm *kvm_svm;
286 	struct kvm_vcpu *vcpu = NULL;
287 	u32 vm_id = AVIC_GATAG_TO_VMID(ga_tag);
288 	u32 vcpu_idx = AVIC_GATAG_TO_VCPUIDX(ga_tag);
289 
290 	pr_debug("SVM: %s: vm_id=%#x, vcpu_idx=%#x\n", __func__, vm_id, vcpu_idx);
291 	trace_kvm_avic_ga_log(vm_id, vcpu_idx);
292 
293 	spin_lock_irqsave(&svm_vm_data_hash_lock, flags);
294 	hash_for_each_possible(svm_vm_data_hash, kvm_svm, hnode, vm_id) {
295 		if (kvm_svm->avic_vm_id != vm_id)
296 			continue;
297 		vcpu = kvm_get_vcpu(&kvm_svm->kvm, vcpu_idx);
298 		break;
299 	}
300 	spin_unlock_irqrestore(&svm_vm_data_hash_lock, flags);
301 
302 	/* Note:
303 	 * At this point, the IOMMU should have already set the pending
304 	 * bit in the vAPIC backing page. So, we just need to schedule
305 	 * in the vcpu.
306 	 */
307 	if (vcpu)
308 		kvm_vcpu_wake_up(vcpu);
309 
310 	return 0;
311 }
312 
avic_get_physical_id_table_order(struct kvm * kvm)313 static int avic_get_physical_id_table_order(struct kvm *kvm)
314 {
315 	/* Provision for the maximum physical ID supported in x2avic mode */
316 	return get_order((__avic_get_max_physical_id(kvm, NULL) + 1) * sizeof(u64));
317 }
318 
avic_alloc_physical_id_table(struct kvm * kvm)319 int avic_alloc_physical_id_table(struct kvm *kvm)
320 {
321 	struct kvm_svm *kvm_svm = to_kvm_svm(kvm);
322 
323 	if (!irqchip_in_kernel(kvm) || !enable_apicv)
324 		return 0;
325 
326 	if (kvm_svm->avic_physical_id_table)
327 		return 0;
328 
329 	kvm_svm->avic_physical_id_table = (void *)__get_free_pages(GFP_KERNEL_ACCOUNT | __GFP_ZERO,
330 								   avic_get_physical_id_table_order(kvm));
331 	if (!kvm_svm->avic_physical_id_table)
332 		return -ENOMEM;
333 
334 	return 0;
335 }
336 
avic_vm_destroy(struct kvm * kvm)337 void avic_vm_destroy(struct kvm *kvm)
338 {
339 	unsigned long flags;
340 	struct kvm_svm *kvm_svm = to_kvm_svm(kvm);
341 
342 	if (!enable_apicv)
343 		return;
344 
345 	free_page((unsigned long)kvm_svm->avic_logical_id_table);
346 	free_pages((unsigned long)kvm_svm->avic_physical_id_table,
347 		   avic_get_physical_id_table_order(kvm));
348 
349 	spin_lock_irqsave(&svm_vm_data_hash_lock, flags);
350 	hash_del(&kvm_svm->hnode);
351 	spin_unlock_irqrestore(&svm_vm_data_hash_lock, flags);
352 }
353 
avic_vm_init(struct kvm * kvm)354 int avic_vm_init(struct kvm *kvm)
355 {
356 	unsigned long flags;
357 	int err = -ENOMEM;
358 	struct kvm_svm *kvm_svm = to_kvm_svm(kvm);
359 	struct kvm_svm *k2;
360 	u32 vm_id;
361 
362 	if (!enable_apicv)
363 		return 0;
364 
365 	kvm_svm->avic_logical_id_table = (void *)get_zeroed_page(GFP_KERNEL_ACCOUNT);
366 	if (!kvm_svm->avic_logical_id_table)
367 		goto free_avic;
368 
369 	spin_lock_irqsave(&svm_vm_data_hash_lock, flags);
370  again:
371 	vm_id = next_vm_id = (next_vm_id + 1) & AVIC_VM_ID_MASK;
372 	if (vm_id == 0) { /* id is 1-based, zero is not okay */
373 		next_vm_id_wrapped = 1;
374 		goto again;
375 	}
376 	/* Is it still in use? Only possible if wrapped at least once */
377 	if (next_vm_id_wrapped) {
378 		hash_for_each_possible(svm_vm_data_hash, k2, hnode, vm_id) {
379 			if (k2->avic_vm_id == vm_id)
380 				goto again;
381 		}
382 	}
383 	kvm_svm->avic_vm_id = vm_id;
384 	hash_add(svm_vm_data_hash, &kvm_svm->hnode, kvm_svm->avic_vm_id);
385 	spin_unlock_irqrestore(&svm_vm_data_hash_lock, flags);
386 
387 	return 0;
388 
389 free_avic:
390 	avic_vm_destroy(kvm);
391 	return err;
392 }
393 
avic_get_backing_page_address(struct vcpu_svm * svm)394 static phys_addr_t avic_get_backing_page_address(struct vcpu_svm *svm)
395 {
396 	return __sme_set(__pa(svm->vcpu.arch.apic->regs));
397 }
398 
avic_init_vmcb(struct vcpu_svm * svm,struct vmcb * vmcb)399 void avic_init_vmcb(struct vcpu_svm *svm, struct vmcb *vmcb)
400 {
401 	struct kvm_svm *kvm_svm = to_kvm_svm(svm->vcpu.kvm);
402 
403 	vmcb->control.avic_backing_page = avic_get_backing_page_address(svm);
404 	vmcb->control.avic_logical_id = __sme_set(__pa(kvm_svm->avic_logical_id_table));
405 	vmcb->control.avic_physical_id = __sme_set(__pa(kvm_svm->avic_physical_id_table));
406 	vmcb->control.avic_vapic_bar = APIC_DEFAULT_PHYS_BASE;
407 
408 	if (kvm_vcpu_apicv_active(&svm->vcpu))
409 		avic_activate_vmcb(svm);
410 	else
411 		avic_deactivate_vmcb(svm);
412 }
413 
avic_init_backing_page(struct kvm_vcpu * vcpu)414 static int avic_init_backing_page(struct kvm_vcpu *vcpu)
415 {
416 	u32 max_id = x2avic_enabled ? x2avic_max_physical_id : AVIC_MAX_PHYSICAL_ID;
417 	struct kvm_svm *kvm_svm = to_kvm_svm(vcpu->kvm);
418 	struct vcpu_svm *svm = to_svm(vcpu);
419 	u32 id = vcpu->vcpu_id;
420 	u64 new_entry;
421 
422 	/*
423 	 * Inhibit AVIC if the vCPU ID is bigger than what is supported by AVIC
424 	 * hardware.  Immediately clear apicv_active, i.e. don't wait until the
425 	 * KVM_REQ_APICV_UPDATE request is processed on the first KVM_RUN, as
426 	 * avic_vcpu_load() expects to be called if and only if the vCPU has
427 	 * fully initialized AVIC.
428 	 */
429 	if (id > max_id) {
430 		kvm_set_apicv_inhibit(vcpu->kvm, APICV_INHIBIT_REASON_PHYSICAL_ID_TOO_BIG);
431 		vcpu->arch.apic->apicv_active = false;
432 		return 0;
433 	}
434 
435 	BUILD_BUG_ON((AVIC_MAX_PHYSICAL_ID + 1) * sizeof(new_entry) > PAGE_SIZE ||
436 		     (X2AVIC_MAX_PHYSICAL_ID + 1) * sizeof(new_entry) > PAGE_SIZE);
437 
438 	if (WARN_ON_ONCE(!vcpu->arch.apic->regs))
439 		return -EINVAL;
440 
441 	if (kvm_apicv_activated(vcpu->kvm)) {
442 		int ret;
443 
444 		/*
445 		 * Note, AVIC hardware walks the nested page table to check
446 		 * permissions, but does not use the SPA address specified in
447 		 * the leaf SPTE since it uses address in the AVIC_BACKING_PAGE
448 		 * pointer field of the VMCB.
449 		 */
450 		ret = kvm_alloc_apic_access_page(vcpu->kvm);
451 		if (ret)
452 			return ret;
453 	}
454 
455 	/* Note, fls64() returns the bit position, +1. */
456 	BUILD_BUG_ON(__PHYSICAL_MASK_SHIFT >
457 		     fls64(AVIC_PHYSICAL_ID_ENTRY_BACKING_PAGE_MASK));
458 
459 	/* Setting AVIC backing page address in the phy APIC ID table */
460 	new_entry = avic_get_backing_page_address(svm) |
461 		    AVIC_PHYSICAL_ID_ENTRY_VALID_MASK;
462 	svm->avic_physical_id_entry = new_entry;
463 
464 	/*
465 	 * Initialize the real table, as vCPUs must have a valid entry in order
466 	 * for broadcast IPIs to function correctly (broadcast IPIs ignore
467 	 * invalid entries, i.e. aren't guaranteed to generate a VM-Exit).
468 	 */
469 	WRITE_ONCE(kvm_svm->avic_physical_id_table[id], new_entry);
470 
471 	return 0;
472 }
473 
avic_ring_doorbell(struct kvm_vcpu * vcpu)474 void avic_ring_doorbell(struct kvm_vcpu *vcpu)
475 {
476 	/*
477 	 * Note, the vCPU could get migrated to a different pCPU at any point,
478 	 * which could result in signalling the wrong/previous pCPU.  But if
479 	 * that happens the vCPU is guaranteed to do a VMRUN (after being
480 	 * migrated) and thus will process pending interrupts, i.e. a doorbell
481 	 * is not needed (and the spurious one is harmless).
482 	 */
483 	int cpu = READ_ONCE(vcpu->cpu);
484 
485 	if (cpu != get_cpu()) {
486 		wrmsrq(MSR_AMD64_SVM_AVIC_DOORBELL, kvm_cpu_get_apicid(cpu));
487 		trace_kvm_avic_doorbell(vcpu->vcpu_id, kvm_cpu_get_apicid(cpu));
488 	}
489 	put_cpu();
490 }
491 
492 
avic_kick_vcpu(struct kvm_vcpu * vcpu,u32 icrl)493 static void avic_kick_vcpu(struct kvm_vcpu *vcpu, u32 icrl)
494 {
495 	vcpu->arch.apic->irr_pending = true;
496 	svm_complete_interrupt_delivery(vcpu,
497 					icrl & APIC_MODE_MASK,
498 					icrl & APIC_INT_LEVELTRIG,
499 					icrl & APIC_VECTOR_MASK);
500 }
501 
avic_kick_vcpu_by_physical_id(struct kvm * kvm,u32 physical_id,u32 icrl)502 static void avic_kick_vcpu_by_physical_id(struct kvm *kvm, u32 physical_id,
503 					  u32 icrl)
504 {
505 	/*
506 	 * KVM inhibits AVIC if any vCPU ID diverges from the vCPUs APIC ID,
507 	 * i.e. APIC ID == vCPU ID.
508 	 */
509 	struct kvm_vcpu *target_vcpu = kvm_get_vcpu_by_id(kvm, physical_id);
510 
511 	/* Once again, nothing to do if the target vCPU doesn't exist. */
512 	if (unlikely(!target_vcpu))
513 		return;
514 
515 	avic_kick_vcpu(target_vcpu, icrl);
516 }
517 
avic_kick_vcpu_by_logical_id(struct kvm * kvm,u32 * avic_logical_id_table,u32 logid_index,u32 icrl)518 static void avic_kick_vcpu_by_logical_id(struct kvm *kvm, u32 *avic_logical_id_table,
519 					 u32 logid_index, u32 icrl)
520 {
521 	u32 physical_id;
522 
523 	if (avic_logical_id_table) {
524 		u32 logid_entry = avic_logical_id_table[logid_index];
525 
526 		/* Nothing to do if the logical destination is invalid. */
527 		if (unlikely(!(logid_entry & AVIC_LOGICAL_ID_ENTRY_VALID_MASK)))
528 			return;
529 
530 		physical_id = logid_entry &
531 			      AVIC_LOGICAL_ID_ENTRY_GUEST_PHYSICAL_ID_MASK;
532 	} else {
533 		/*
534 		 * For x2APIC, the logical APIC ID is a read-only value that is
535 		 * derived from the x2APIC ID, thus the x2APIC ID can be found
536 		 * by reversing the calculation (stored in logid_index).  Note,
537 		 * bits 31:20 of the x2APIC ID aren't propagated to the logical
538 		 * ID, but KVM limits the x2APIC ID limited to KVM_MAX_VCPU_IDS.
539 		 */
540 		physical_id = logid_index;
541 	}
542 
543 	avic_kick_vcpu_by_physical_id(kvm, physical_id, icrl);
544 }
545 
546 /*
547  * A fast-path version of avic_kick_target_vcpus(), which attempts to match
548  * destination APIC ID to vCPU without looping through all vCPUs.
549  */
avic_kick_target_vcpus_fast(struct kvm * kvm,struct kvm_lapic * source,u32 icrl,u32 icrh,u32 index)550 static int avic_kick_target_vcpus_fast(struct kvm *kvm, struct kvm_lapic *source,
551 				       u32 icrl, u32 icrh, u32 index)
552 {
553 	int dest_mode = icrl & APIC_DEST_MASK;
554 	int shorthand = icrl & APIC_SHORT_MASK;
555 	struct kvm_svm *kvm_svm = to_kvm_svm(kvm);
556 	u32 dest;
557 
558 	if (shorthand != APIC_DEST_NOSHORT)
559 		return -EINVAL;
560 
561 	if (apic_x2apic_mode(source))
562 		dest = icrh;
563 	else
564 		dest = GET_XAPIC_DEST_FIELD(icrh);
565 
566 	if (dest_mode == APIC_DEST_PHYSICAL) {
567 		/* broadcast destination, use slow path */
568 		if (apic_x2apic_mode(source) && dest == X2APIC_BROADCAST)
569 			return -EINVAL;
570 		if (!apic_x2apic_mode(source) && dest == APIC_BROADCAST)
571 			return -EINVAL;
572 
573 		if (WARN_ON_ONCE(dest != index))
574 			return -EINVAL;
575 
576 		avic_kick_vcpu_by_physical_id(kvm, dest, icrl);
577 	} else {
578 		u32 *avic_logical_id_table;
579 		unsigned long bitmap, i;
580 		u32 cluster;
581 
582 		if (apic_x2apic_mode(source)) {
583 			/* 16 bit dest mask, 16 bit cluster id */
584 			bitmap = dest & 0xFFFF;
585 			cluster = (dest >> 16) << 4;
586 		} else if (kvm_lapic_get_reg(source, APIC_DFR) == APIC_DFR_FLAT) {
587 			/* 8 bit dest mask*/
588 			bitmap = dest;
589 			cluster = 0;
590 		} else {
591 			/* 4 bit desk mask, 4 bit cluster id */
592 			bitmap = dest & 0xF;
593 			cluster = (dest >> 4) << 2;
594 		}
595 
596 		/* Nothing to do if there are no destinations in the cluster. */
597 		if (unlikely(!bitmap))
598 			return 0;
599 
600 		if (apic_x2apic_mode(source))
601 			avic_logical_id_table = NULL;
602 		else
603 			avic_logical_id_table = kvm_svm->avic_logical_id_table;
604 
605 		/*
606 		 * AVIC is inhibited if vCPUs aren't mapped 1:1 with logical
607 		 * IDs, thus each bit in the destination is guaranteed to map
608 		 * to at most one vCPU.
609 		 */
610 		for_each_set_bit(i, &bitmap, 16)
611 			avic_kick_vcpu_by_logical_id(kvm, avic_logical_id_table,
612 						     cluster + i, icrl);
613 	}
614 
615 	return 0;
616 }
617 
avic_kick_target_vcpus(struct kvm * kvm,struct kvm_lapic * source,u32 icrl,u32 icrh,u32 index)618 static void avic_kick_target_vcpus(struct kvm *kvm, struct kvm_lapic *source,
619 				   u32 icrl, u32 icrh, u32 index)
620 {
621 	u32 dest = apic_x2apic_mode(source) ? icrh : GET_XAPIC_DEST_FIELD(icrh);
622 	unsigned long i;
623 	struct kvm_vcpu *vcpu;
624 
625 	if (!avic_kick_target_vcpus_fast(kvm, source, icrl, icrh, index))
626 		return;
627 
628 	trace_kvm_avic_kick_vcpu_slowpath(icrh, icrl, index);
629 
630 	/*
631 	 * Wake any target vCPUs that are blocking, i.e. waiting for a wake
632 	 * event.  There's no need to signal doorbells, as hardware has handled
633 	 * vCPUs that were in guest at the time of the IPI, and vCPUs that have
634 	 * since entered the guest will have processed pending IRQs at VMRUN.
635 	 */
636 	kvm_for_each_vcpu(i, vcpu, kvm) {
637 		if (kvm_apic_match_dest(vcpu, source, icrl & APIC_SHORT_MASK,
638 					dest, icrl & APIC_DEST_MASK))
639 			avic_kick_vcpu(vcpu, icrl);
640 	}
641 }
642 
avic_incomplete_ipi_interception(struct kvm_vcpu * vcpu)643 int avic_incomplete_ipi_interception(struct kvm_vcpu *vcpu)
644 {
645 	struct vcpu_svm *svm = to_svm(vcpu);
646 	u32 icrh = svm->vmcb->control.exit_info_1 >> 32;
647 	u32 icrl = svm->vmcb->control.exit_info_1;
648 	u32 id = svm->vmcb->control.exit_info_2 >> 32;
649 	u32 index = svm->vmcb->control.exit_info_2 & AVIC_PHYSICAL_MAX_INDEX_MASK;
650 	struct kvm_lapic *apic = vcpu->arch.apic;
651 
652 	trace_kvm_avic_incomplete_ipi(vcpu->vcpu_id, icrh, icrl, id, index);
653 
654 	switch (id) {
655 	case AVIC_IPI_FAILURE_INVALID_TARGET:
656 	case AVIC_IPI_FAILURE_INVALID_INT_TYPE:
657 		/*
658 		 * Emulate IPIs that are not handled by AVIC hardware, which
659 		 * only virtualizes Fixed, Edge-Triggered INTRs, and falls over
660 		 * if _any_ targets are invalid, e.g. if the logical mode mask
661 		 * is a superset of running vCPUs.
662 		 *
663 		 * The exit is a trap, e.g. ICR holds the correct value and RIP
664 		 * has been advanced, KVM is responsible only for emulating the
665 		 * IPI.  Sadly, hardware may sometimes leave the BUSY flag set,
666 		 * in which case KVM needs to emulate the ICR write as well in
667 		 * order to clear the BUSY flag.
668 		 */
669 		if (icrl & APIC_ICR_BUSY)
670 			kvm_apic_write_nodecode(vcpu, APIC_ICR);
671 		else
672 			kvm_apic_send_ipi(apic, icrl, icrh);
673 		break;
674 	case AVIC_IPI_FAILURE_TARGET_NOT_RUNNING:
675 		/*
676 		 * At this point, we expect that the AVIC HW has already
677 		 * set the appropriate IRR bits on the valid target
678 		 * vcpus. So, we just need to kick the appropriate vcpu.
679 		 */
680 		avic_kick_target_vcpus(vcpu->kvm, apic, icrl, icrh, index);
681 		break;
682 	case AVIC_IPI_FAILURE_INVALID_BACKING_PAGE:
683 		WARN_ONCE(1, "Invalid backing page\n");
684 		break;
685 	case AVIC_IPI_FAILURE_INVALID_IPI_VECTOR:
686 		/* Invalid IPI with vector < 16 */
687 		break;
688 	default:
689 		vcpu_unimpl(vcpu, "Unknown avic incomplete IPI interception\n");
690 	}
691 
692 	return 1;
693 }
694 
avic_vcpu_get_apicv_inhibit_reasons(struct kvm_vcpu * vcpu)695 unsigned long avic_vcpu_get_apicv_inhibit_reasons(struct kvm_vcpu *vcpu)
696 {
697 	if (is_guest_mode(vcpu))
698 		return APICV_INHIBIT_REASON_NESTED;
699 	return 0;
700 }
701 
avic_get_logical_id_entry(struct kvm_vcpu * vcpu,u32 ldr,bool flat)702 static u32 *avic_get_logical_id_entry(struct kvm_vcpu *vcpu, u32 ldr, bool flat)
703 {
704 	struct kvm_svm *kvm_svm = to_kvm_svm(vcpu->kvm);
705 	u32 cluster, index;
706 
707 	ldr = GET_APIC_LOGICAL_ID(ldr);
708 
709 	if (flat) {
710 		cluster = 0;
711 	} else {
712 		cluster = (ldr >> 4);
713 		if (cluster >= 0xf)
714 			return NULL;
715 		ldr &= 0xf;
716 	}
717 	if (!ldr || !is_power_of_2(ldr))
718 		return NULL;
719 
720 	index = __ffs(ldr);
721 	if (WARN_ON_ONCE(index > 7))
722 		return NULL;
723 	index += (cluster << 2);
724 
725 	return &kvm_svm->avic_logical_id_table[index];
726 }
727 
avic_ldr_write(struct kvm_vcpu * vcpu,u8 g_physical_id,u32 ldr)728 static void avic_ldr_write(struct kvm_vcpu *vcpu, u8 g_physical_id, u32 ldr)
729 {
730 	bool flat;
731 	u32 *entry, new_entry;
732 
733 	flat = kvm_lapic_get_reg(vcpu->arch.apic, APIC_DFR) == APIC_DFR_FLAT;
734 	entry = avic_get_logical_id_entry(vcpu, ldr, flat);
735 	if (!entry)
736 		return;
737 
738 	new_entry = READ_ONCE(*entry);
739 	new_entry &= ~AVIC_LOGICAL_ID_ENTRY_GUEST_PHYSICAL_ID_MASK;
740 	new_entry |= (g_physical_id & AVIC_LOGICAL_ID_ENTRY_GUEST_PHYSICAL_ID_MASK);
741 	new_entry |= AVIC_LOGICAL_ID_ENTRY_VALID_MASK;
742 	WRITE_ONCE(*entry, new_entry);
743 }
744 
avic_invalidate_logical_id_entry(struct kvm_vcpu * vcpu)745 static void avic_invalidate_logical_id_entry(struct kvm_vcpu *vcpu)
746 {
747 	struct vcpu_svm *svm = to_svm(vcpu);
748 	bool flat = svm->dfr_reg == APIC_DFR_FLAT;
749 	u32 *entry;
750 
751 	/* Note: x2AVIC does not use logical APIC ID table */
752 	if (apic_x2apic_mode(vcpu->arch.apic))
753 		return;
754 
755 	entry = avic_get_logical_id_entry(vcpu, svm->ldr_reg, flat);
756 	if (entry)
757 		clear_bit(AVIC_LOGICAL_ID_ENTRY_VALID_BIT, (unsigned long *)entry);
758 }
759 
avic_handle_ldr_update(struct kvm_vcpu * vcpu)760 static void avic_handle_ldr_update(struct kvm_vcpu *vcpu)
761 {
762 	struct vcpu_svm *svm = to_svm(vcpu);
763 	u32 ldr = kvm_lapic_get_reg(vcpu->arch.apic, APIC_LDR);
764 	u32 id = kvm_xapic_id(vcpu->arch.apic);
765 
766 	/* AVIC does not support LDR update for x2APIC */
767 	if (apic_x2apic_mode(vcpu->arch.apic))
768 		return;
769 
770 	if (ldr == svm->ldr_reg)
771 		return;
772 
773 	avic_invalidate_logical_id_entry(vcpu);
774 
775 	svm->ldr_reg = ldr;
776 	avic_ldr_write(vcpu, id, ldr);
777 }
778 
avic_handle_dfr_update(struct kvm_vcpu * vcpu)779 static void avic_handle_dfr_update(struct kvm_vcpu *vcpu)
780 {
781 	struct vcpu_svm *svm = to_svm(vcpu);
782 	u32 dfr = kvm_lapic_get_reg(vcpu->arch.apic, APIC_DFR);
783 
784 	if (svm->dfr_reg == dfr)
785 		return;
786 
787 	avic_invalidate_logical_id_entry(vcpu);
788 	svm->dfr_reg = dfr;
789 }
790 
avic_unaccel_trap_write(struct kvm_vcpu * vcpu)791 static int avic_unaccel_trap_write(struct kvm_vcpu *vcpu)
792 {
793 	u32 offset = to_svm(vcpu)->vmcb->control.exit_info_1 &
794 				AVIC_UNACCEL_ACCESS_OFFSET_MASK;
795 
796 	switch (offset) {
797 	case APIC_LDR:
798 		avic_handle_ldr_update(vcpu);
799 		break;
800 	case APIC_DFR:
801 		avic_handle_dfr_update(vcpu);
802 		break;
803 	case APIC_RRR:
804 		/* Ignore writes to Read Remote Data, it's read-only. */
805 		return 1;
806 	default:
807 		break;
808 	}
809 
810 	kvm_apic_write_nodecode(vcpu, offset);
811 	return 1;
812 }
813 
is_avic_unaccelerated_access_trap(u32 offset)814 static bool is_avic_unaccelerated_access_trap(u32 offset)
815 {
816 	bool ret = false;
817 
818 	switch (offset) {
819 	case APIC_ID:
820 	case APIC_EOI:
821 	case APIC_RRR:
822 	case APIC_LDR:
823 	case APIC_DFR:
824 	case APIC_SPIV:
825 	case APIC_ESR:
826 	case APIC_ICR:
827 	case APIC_LVTT:
828 	case APIC_LVTTHMR:
829 	case APIC_LVTPC:
830 	case APIC_LVT0:
831 	case APIC_LVT1:
832 	case APIC_LVTERR:
833 	case APIC_TMICT:
834 	case APIC_TDCR:
835 		ret = true;
836 		break;
837 	default:
838 		break;
839 	}
840 	return ret;
841 }
842 
avic_unaccelerated_access_interception(struct kvm_vcpu * vcpu)843 int avic_unaccelerated_access_interception(struct kvm_vcpu *vcpu)
844 {
845 	struct vcpu_svm *svm = to_svm(vcpu);
846 	int ret = 0;
847 	u32 offset = svm->vmcb->control.exit_info_1 &
848 		     AVIC_UNACCEL_ACCESS_OFFSET_MASK;
849 	u32 vector = svm->vmcb->control.exit_info_2 &
850 		     AVIC_UNACCEL_ACCESS_VECTOR_MASK;
851 	bool write = (svm->vmcb->control.exit_info_1 >> 32) &
852 		     AVIC_UNACCEL_ACCESS_WRITE_MASK;
853 	bool trap = is_avic_unaccelerated_access_trap(offset);
854 
855 	trace_kvm_avic_unaccelerated_access(vcpu->vcpu_id, offset,
856 					    trap, write, vector);
857 	if (trap) {
858 		/* Handling Trap */
859 		WARN_ONCE(!write, "svm: Handling trap read.\n");
860 		ret = avic_unaccel_trap_write(vcpu);
861 	} else {
862 		/* Handling Fault */
863 		ret = kvm_emulate_instruction(vcpu, 0);
864 	}
865 
866 	return ret;
867 }
868 
avic_init_vcpu(struct vcpu_svm * svm)869 int avic_init_vcpu(struct vcpu_svm *svm)
870 {
871 	int ret;
872 	struct kvm_vcpu *vcpu = &svm->vcpu;
873 
874 	INIT_LIST_HEAD(&svm->ir_list);
875 	raw_spin_lock_init(&svm->ir_list_lock);
876 
877 	if (!enable_apicv || !irqchip_in_kernel(vcpu->kvm))
878 		return 0;
879 
880 	ret = avic_init_backing_page(vcpu);
881 	if (ret)
882 		return ret;
883 
884 	svm->dfr_reg = APIC_DFR_FLAT;
885 
886 	return ret;
887 }
888 
avic_apicv_post_state_restore(struct kvm_vcpu * vcpu)889 void avic_apicv_post_state_restore(struct kvm_vcpu *vcpu)
890 {
891 	avic_handle_dfr_update(vcpu);
892 	avic_handle_ldr_update(vcpu);
893 }
894 
svm_ir_list_del(struct kvm_kernel_irqfd * irqfd)895 static void svm_ir_list_del(struct kvm_kernel_irqfd *irqfd)
896 {
897 	struct kvm_vcpu *vcpu = irqfd->irq_bypass_vcpu;
898 	unsigned long flags;
899 
900 	if (!vcpu)
901 		return;
902 
903 	raw_spin_lock_irqsave(&to_svm(vcpu)->ir_list_lock, flags);
904 	list_del(&irqfd->vcpu_list);
905 	raw_spin_unlock_irqrestore(&to_svm(vcpu)->ir_list_lock, flags);
906 }
907 
avic_pi_update_irte(struct kvm_kernel_irqfd * irqfd,struct kvm * kvm,unsigned int host_irq,uint32_t guest_irq,struct kvm_vcpu * vcpu,u32 vector)908 int avic_pi_update_irte(struct kvm_kernel_irqfd *irqfd, struct kvm *kvm,
909 			unsigned int host_irq, uint32_t guest_irq,
910 			struct kvm_vcpu *vcpu, u32 vector)
911 {
912 	/*
913 	 * If the IRQ was affined to a different vCPU, remove the IRTE metadata
914 	 * from the *previous* vCPU's list.
915 	 */
916 	svm_ir_list_del(irqfd);
917 
918 	if (vcpu) {
919 		/*
920 		 * Try to enable guest_mode in IRTE, unless AVIC is inhibited,
921 		 * in which case configure the IRTE for legacy mode, but track
922 		 * the IRTE metadata so that it can be converted to guest mode
923 		 * if AVIC is enabled/uninhibited in the future.
924 		 */
925 		struct amd_iommu_pi_data pi_data = {
926 			.ga_tag = AVIC_GATAG(to_kvm_svm(kvm)->avic_vm_id,
927 					     vcpu->vcpu_idx),
928 			.is_guest_mode = kvm_vcpu_apicv_active(vcpu),
929 			.vapic_addr = avic_get_backing_page_address(to_svm(vcpu)),
930 			.vector = vector,
931 		};
932 		struct vcpu_svm *svm = to_svm(vcpu);
933 		u64 entry;
934 		int ret;
935 
936 		/*
937 		 * Prevent the vCPU from being scheduled out or migrated until
938 		 * the IRTE is updated and its metadata has been added to the
939 		 * list of IRQs being posted to the vCPU, to ensure the IRTE
940 		 * isn't programmed with stale pCPU/IsRunning information.
941 		 */
942 		guard(raw_spinlock_irqsave)(&svm->ir_list_lock);
943 
944 		/*
945 		 * Update the target pCPU for IOMMU doorbells if the vCPU is
946 		 * running.  If the vCPU is NOT running, i.e. is blocking or
947 		 * scheduled out, KVM will update the pCPU info when the vCPU
948 		 * is awakened and/or scheduled in.  See also avic_vcpu_load().
949 		 */
950 		entry = svm->avic_physical_id_entry;
951 		if (entry & AVIC_PHYSICAL_ID_ENTRY_IS_RUNNING_MASK) {
952 			pi_data.cpu = entry & AVIC_PHYSICAL_ID_ENTRY_HOST_PHYSICAL_ID_MASK;
953 		} else {
954 			pi_data.cpu = -1;
955 			pi_data.ga_log_intr = entry & AVIC_PHYSICAL_ID_ENTRY_GA_LOG_INTR;
956 		}
957 
958 		ret = irq_set_vcpu_affinity(host_irq, &pi_data);
959 		if (ret)
960 			return ret;
961 
962 		/*
963 		 * Revert to legacy mode if the IOMMU didn't provide metadata
964 		 * for the IRTE, which KVM needs to keep the IRTE up-to-date,
965 		 * e.g. if the vCPU is migrated or AVIC is disabled.
966 		 */
967 		if (WARN_ON_ONCE(!pi_data.ir_data)) {
968 			irq_set_vcpu_affinity(host_irq, NULL);
969 			return -EIO;
970 		}
971 
972 		irqfd->irq_bypass_data = pi_data.ir_data;
973 		list_add(&irqfd->vcpu_list, &svm->ir_list);
974 		return 0;
975 	}
976 	return irq_set_vcpu_affinity(host_irq, NULL);
977 }
978 
979 enum avic_vcpu_action {
980 	/*
981 	 * There is no need to differentiate between activate and deactivate,
982 	 * as KVM only refreshes AVIC state when the vCPU is scheduled in and
983 	 * isn't blocking, i.e. the pCPU must always be (in)valid when AVIC is
984 	 * being (de)activated.
985 	 */
986 	AVIC_TOGGLE_ON_OFF	= BIT(0),
987 	AVIC_ACTIVATE		= AVIC_TOGGLE_ON_OFF,
988 	AVIC_DEACTIVATE		= AVIC_TOGGLE_ON_OFF,
989 
990 	/*
991 	 * No unique action is required to deal with a vCPU that stops/starts
992 	 * running.  A vCPU that starts running by definition stops blocking as
993 	 * well, and a vCPU that stops running can't have been blocking, i.e.
994 	 * doesn't need to toggle GALogIntr.
995 	 */
996 	AVIC_START_RUNNING	= 0,
997 	AVIC_STOP_RUNNING	= 0,
998 
999 	/*
1000 	 * When a vCPU starts blocking, KVM needs to set the GALogIntr flag
1001 	 * int all associated IRTEs so that KVM can wake the vCPU if an IRQ is
1002 	 * sent to the vCPU.
1003 	 */
1004 	AVIC_START_BLOCKING	= BIT(1),
1005 };
1006 
avic_update_iommu_vcpu_affinity(struct kvm_vcpu * vcpu,int cpu,enum avic_vcpu_action action)1007 static void avic_update_iommu_vcpu_affinity(struct kvm_vcpu *vcpu, int cpu,
1008 					    enum avic_vcpu_action action)
1009 {
1010 	bool ga_log_intr = (action & AVIC_START_BLOCKING);
1011 	struct vcpu_svm *svm = to_svm(vcpu);
1012 	struct kvm_kernel_irqfd *irqfd;
1013 
1014 	lockdep_assert_held(&svm->ir_list_lock);
1015 
1016 	/*
1017 	 * Here, we go through the per-vcpu ir_list to update all existing
1018 	 * interrupt remapping table entry targeting this vcpu.
1019 	 */
1020 	if (list_empty(&svm->ir_list))
1021 		return;
1022 
1023 	list_for_each_entry(irqfd, &svm->ir_list, vcpu_list) {
1024 		void *data = irqfd->irq_bypass_data;
1025 
1026 		if (!(action & AVIC_TOGGLE_ON_OFF))
1027 			WARN_ON_ONCE(amd_iommu_update_ga(data, cpu, ga_log_intr));
1028 		else if (cpu >= 0)
1029 			WARN_ON_ONCE(amd_iommu_activate_guest_mode(data, cpu, ga_log_intr));
1030 		else
1031 			WARN_ON_ONCE(amd_iommu_deactivate_guest_mode(data));
1032 	}
1033 }
1034 
__avic_vcpu_load(struct kvm_vcpu * vcpu,int cpu,enum avic_vcpu_action action)1035 static void __avic_vcpu_load(struct kvm_vcpu *vcpu, int cpu,
1036 			     enum avic_vcpu_action action)
1037 {
1038 	struct kvm_svm *kvm_svm = to_kvm_svm(vcpu->kvm);
1039 	int h_physical_id = kvm_cpu_get_apicid(cpu);
1040 	struct vcpu_svm *svm = to_svm(vcpu);
1041 	unsigned long flags;
1042 	u64 entry;
1043 
1044 	lockdep_assert_preemption_disabled();
1045 
1046 	if (WARN_ON(h_physical_id & ~AVIC_PHYSICAL_ID_ENTRY_HOST_PHYSICAL_ID_MASK))
1047 		return;
1048 
1049 	if (WARN_ON_ONCE(vcpu->vcpu_id * sizeof(entry) >=
1050 			 PAGE_SIZE << avic_get_physical_id_table_order(vcpu->kvm)))
1051 		return;
1052 
1053 	/*
1054 	 * Grab the per-vCPU interrupt remapping lock even if the VM doesn't
1055 	 * _currently_ have assigned devices, as that can change.  Holding
1056 	 * ir_list_lock ensures that either svm_ir_list_add() will consume
1057 	 * up-to-date entry information, or that this task will wait until
1058 	 * svm_ir_list_add() completes to set the new target pCPU.
1059 	 */
1060 	raw_spin_lock_irqsave(&svm->ir_list_lock, flags);
1061 
1062 	entry = svm->avic_physical_id_entry;
1063 	WARN_ON_ONCE(entry & AVIC_PHYSICAL_ID_ENTRY_IS_RUNNING_MASK);
1064 
1065 	entry &= ~(AVIC_PHYSICAL_ID_ENTRY_HOST_PHYSICAL_ID_MASK |
1066 		   AVIC_PHYSICAL_ID_ENTRY_GA_LOG_INTR);
1067 	entry |= (h_physical_id & AVIC_PHYSICAL_ID_ENTRY_HOST_PHYSICAL_ID_MASK);
1068 	entry |= AVIC_PHYSICAL_ID_ENTRY_IS_RUNNING_MASK;
1069 
1070 	svm->avic_physical_id_entry = entry;
1071 
1072 	/*
1073 	 * If IPI virtualization is disabled, clear IsRunning when updating the
1074 	 * actual Physical ID table, so that the CPU never sees IsRunning=1.
1075 	 * Keep the APIC ID up-to-date in the entry to minimize the chances of
1076 	 * things going sideways if hardware peeks at the ID.
1077 	 */
1078 	if (!enable_ipiv)
1079 		entry &= ~AVIC_PHYSICAL_ID_ENTRY_IS_RUNNING_MASK;
1080 
1081 	WRITE_ONCE(kvm_svm->avic_physical_id_table[vcpu->vcpu_id], entry);
1082 
1083 	avic_update_iommu_vcpu_affinity(vcpu, h_physical_id, action);
1084 
1085 	raw_spin_unlock_irqrestore(&svm->ir_list_lock, flags);
1086 }
1087 
avic_vcpu_load(struct kvm_vcpu * vcpu,int cpu)1088 void avic_vcpu_load(struct kvm_vcpu *vcpu, int cpu)
1089 {
1090 	/*
1091 	 * No need to update anything if the vCPU is blocking, i.e. if the vCPU
1092 	 * is being scheduled in after being preempted.  The CPU entries in the
1093 	 * Physical APIC table and IRTE are consumed iff IsRun{ning} is '1'.
1094 	 * If the vCPU was migrated, its new CPU value will be stuffed when the
1095 	 * vCPU unblocks.
1096 	 */
1097 	if (kvm_vcpu_is_blocking(vcpu))
1098 		return;
1099 
1100 	__avic_vcpu_load(vcpu, cpu, AVIC_START_RUNNING);
1101 }
1102 
__avic_vcpu_put(struct kvm_vcpu * vcpu,enum avic_vcpu_action action)1103 static void __avic_vcpu_put(struct kvm_vcpu *vcpu, enum avic_vcpu_action action)
1104 {
1105 	struct kvm_svm *kvm_svm = to_kvm_svm(vcpu->kvm);
1106 	struct vcpu_svm *svm = to_svm(vcpu);
1107 	unsigned long flags;
1108 	u64 entry = svm->avic_physical_id_entry;
1109 
1110 	lockdep_assert_preemption_disabled();
1111 
1112 	if (WARN_ON_ONCE(vcpu->vcpu_id * sizeof(entry) >=
1113 			 PAGE_SIZE << avic_get_physical_id_table_order(vcpu->kvm)))
1114 		return;
1115 
1116 	/*
1117 	 * Take and hold the per-vCPU interrupt remapping lock while updating
1118 	 * the Physical ID entry even though the lock doesn't protect against
1119 	 * multiple writers (see above).  Holding ir_list_lock ensures that
1120 	 * either svm_ir_list_add() will consume up-to-date entry information,
1121 	 * or that this task will wait until svm_ir_list_add() completes to
1122 	 * mark the vCPU as not running.
1123 	 */
1124 	raw_spin_lock_irqsave(&svm->ir_list_lock, flags);
1125 
1126 	avic_update_iommu_vcpu_affinity(vcpu, -1, action);
1127 
1128 	WARN_ON_ONCE(entry & AVIC_PHYSICAL_ID_ENTRY_GA_LOG_INTR);
1129 
1130 	/*
1131 	 * Keep the previous APIC ID in the entry so that a rogue doorbell from
1132 	 * hardware is at least restricted to a CPU associated with the vCPU.
1133 	 */
1134 	entry &= ~AVIC_PHYSICAL_ID_ENTRY_IS_RUNNING_MASK;
1135 
1136 	if (enable_ipiv)
1137 		WRITE_ONCE(kvm_svm->avic_physical_id_table[vcpu->vcpu_id], entry);
1138 
1139 	/*
1140 	 * Note!  Don't set AVIC_PHYSICAL_ID_ENTRY_GA_LOG_INTR in the table as
1141 	 * it's a synthetic flag that usurps an unused should-be-zero bit.
1142 	 */
1143 	if (action & AVIC_START_BLOCKING)
1144 		entry |= AVIC_PHYSICAL_ID_ENTRY_GA_LOG_INTR;
1145 
1146 	svm->avic_physical_id_entry = entry;
1147 
1148 	raw_spin_unlock_irqrestore(&svm->ir_list_lock, flags);
1149 }
1150 
avic_vcpu_put(struct kvm_vcpu * vcpu)1151 void avic_vcpu_put(struct kvm_vcpu *vcpu)
1152 {
1153 	/*
1154 	 * Note, reading the Physical ID entry outside of ir_list_lock is safe
1155 	 * as only the pCPU that has loaded (or is loading) the vCPU is allowed
1156 	 * to modify the entry, and preemption is disabled.  I.e. the vCPU
1157 	 * can't be scheduled out and thus avic_vcpu_{put,load}() can't run
1158 	 * recursively.
1159 	 */
1160 	u64 entry = to_svm(vcpu)->avic_physical_id_entry;
1161 
1162 	/*
1163 	 * Nothing to do if IsRunning == '0' due to vCPU blocking, i.e. if the
1164 	 * vCPU is preempted while its in the process of blocking.  WARN if the
1165 	 * vCPU wasn't running and isn't blocking, KVM shouldn't attempt to put
1166 	 * the AVIC if it wasn't previously loaded.
1167 	 */
1168 	if (!(entry & AVIC_PHYSICAL_ID_ENTRY_IS_RUNNING_MASK)) {
1169 		if (WARN_ON_ONCE(!kvm_vcpu_is_blocking(vcpu)))
1170 			return;
1171 
1172 		/*
1173 		 * The vCPU was preempted while blocking, ensure its IRTEs are
1174 		 * configured to generate GA Log Interrupts.
1175 		 */
1176 		if (!(WARN_ON_ONCE(!(entry & AVIC_PHYSICAL_ID_ENTRY_GA_LOG_INTR))))
1177 			return;
1178 	}
1179 
1180 	__avic_vcpu_put(vcpu, kvm_vcpu_is_blocking(vcpu) ? AVIC_START_BLOCKING :
1181 							   AVIC_STOP_RUNNING);
1182 }
1183 
avic_refresh_virtual_apic_mode(struct kvm_vcpu * vcpu)1184 void avic_refresh_virtual_apic_mode(struct kvm_vcpu *vcpu)
1185 {
1186 	struct vcpu_svm *svm = to_svm(vcpu);
1187 	struct vmcb *vmcb = svm->vmcb01.ptr;
1188 
1189 	if (!lapic_in_kernel(vcpu) || !enable_apicv)
1190 		return;
1191 
1192 	if (kvm_vcpu_apicv_active(vcpu)) {
1193 		/**
1194 		 * During AVIC temporary deactivation, guest could update
1195 		 * APIC ID, DFR and LDR registers, which would not be trapped
1196 		 * by avic_unaccelerated_access_interception(). In this case,
1197 		 * we need to check and update the AVIC logical APIC ID table
1198 		 * accordingly before re-activating.
1199 		 */
1200 		avic_apicv_post_state_restore(vcpu);
1201 		avic_activate_vmcb(svm);
1202 	} else {
1203 		avic_deactivate_vmcb(svm);
1204 	}
1205 	vmcb_mark_dirty(vmcb, VMCB_AVIC);
1206 }
1207 
avic_refresh_apicv_exec_ctrl(struct kvm_vcpu * vcpu)1208 void avic_refresh_apicv_exec_ctrl(struct kvm_vcpu *vcpu)
1209 {
1210 	if (!enable_apicv)
1211 		return;
1212 
1213 	/* APICv should only be toggled on/off while the vCPU is running. */
1214 	WARN_ON_ONCE(kvm_vcpu_is_blocking(vcpu));
1215 
1216 	avic_refresh_virtual_apic_mode(vcpu);
1217 
1218 	if (kvm_vcpu_apicv_active(vcpu))
1219 		__avic_vcpu_load(vcpu, vcpu->cpu, AVIC_ACTIVATE);
1220 	else
1221 		__avic_vcpu_put(vcpu, AVIC_DEACTIVATE);
1222 }
1223 
avic_vcpu_blocking(struct kvm_vcpu * vcpu)1224 void avic_vcpu_blocking(struct kvm_vcpu *vcpu)
1225 {
1226 	if (!kvm_vcpu_apicv_active(vcpu))
1227 		return;
1228 
1229 	/*
1230 	 * Unload the AVIC when the vCPU is about to block, _before_ the vCPU
1231 	 * actually blocks.
1232 	 *
1233 	 * Note, any IRQs that arrive before IsRunning=0 will not cause an
1234 	 * incomplete IPI vmexit on the source; kvm_vcpu_check_block() handles
1235 	 * this by checking vIRR one last time before blocking.  The memory
1236 	 * barrier implicit in set_current_state orders writing IsRunning=0
1237 	 * before reading the vIRR.  The processor needs a matching memory
1238 	 * barrier on interrupt delivery between writing IRR and reading
1239 	 * IsRunning; the lack of this barrier might be the cause of errata #1235).
1240 	 *
1241 	 * Clear IsRunning=0 even if guest IRQs are disabled, i.e. even if KVM
1242 	 * doesn't need to detect events for scheduling purposes.  The doorbell
1243 	 * used to signal running vCPUs cannot be blocked, i.e. will perturb the
1244 	 * CPU and cause noisy neighbor problems if the VM is sending interrupts
1245 	 * to the vCPU while it's scheduled out.
1246 	 */
1247 	__avic_vcpu_put(vcpu, AVIC_START_BLOCKING);
1248 }
1249 
avic_vcpu_unblocking(struct kvm_vcpu * vcpu)1250 void avic_vcpu_unblocking(struct kvm_vcpu *vcpu)
1251 {
1252 	if (!kvm_vcpu_apicv_active(vcpu))
1253 		return;
1254 
1255 	avic_vcpu_load(vcpu, vcpu->cpu);
1256 }
1257 
avic_want_avic_enabled(void)1258 static bool __init avic_want_avic_enabled(void)
1259 {
1260 	/*
1261 	 * In "auto" mode, enable AVIC by default for Zen4+ if x2AVIC is
1262 	 * supported (to avoid enabling partial support by default, and because
1263 	 * x2AVIC should be supported by all Zen4+ CPUs).  Explicitly check for
1264 	 * family 0x1A and later (Zen5+), as the kernel's synthetic ZenX flags
1265 	 * aren't inclusive of previous generations, i.e. the kernel will set
1266 	 * at most one ZenX feature flag.
1267 	 */
1268 	if (avic == AVIC_AUTO_MODE)
1269 		avic = boot_cpu_has(X86_FEATURE_X2AVIC) &&
1270 		       (cpu_feature_enabled(X86_FEATURE_ZEN4) || boot_cpu_data.x86 >= 0x1A);
1271 
1272 	if (!avic || !npt_enabled)
1273 		return false;
1274 
1275 	/* AVIC is a prerequisite for x2AVIC. */
1276 	if (!boot_cpu_has(X86_FEATURE_AVIC) && !force_avic) {
1277 		if (boot_cpu_has(X86_FEATURE_X2AVIC))
1278 			pr_warn(FW_BUG "Cannot enable x2AVIC, AVIC is unsupported\n");
1279 		return false;
1280 	}
1281 
1282 	if (cc_platform_has(CC_ATTR_HOST_SEV_SNP) &&
1283 	    !boot_cpu_has(X86_FEATURE_HV_INUSE_WR_ALLOWED)) {
1284 		pr_warn("AVIC disabled: missing HvInUseWrAllowed on SNP-enabled system\n");
1285 		return false;
1286 	}
1287 
1288 	/*
1289 	 * Print a scary message if AVIC is force enabled to make it abundantly
1290 	 * clear that ignoring CPUID could have repercussions.  See Revision
1291 	 * Guide for specific AMD processor for more details.
1292 	 */
1293 	if (!boot_cpu_has(X86_FEATURE_AVIC))
1294 		pr_warn("AVIC unsupported in CPUID but force enabled, your system might crash and burn\n");
1295 
1296 	return true;
1297 }
1298 
1299 /*
1300  * Note:
1301  * - The module param avic enable both xAPIC and x2APIC mode.
1302  * - Hypervisor can support both xAVIC and x2AVIC in the same guest.
1303  * - The mode can be switched at run-time.
1304  */
avic_hardware_setup(void)1305 bool __init avic_hardware_setup(void)
1306 {
1307 	avic = avic_want_avic_enabled();
1308 	if (!avic)
1309 		return false;
1310 
1311 	pr_info("AVIC enabled\n");
1312 
1313 	/* AVIC is a prerequisite for x2AVIC. */
1314 	x2avic_enabled = boot_cpu_has(X86_FEATURE_X2AVIC);
1315 	if (x2avic_enabled) {
1316 		if (cpu_feature_enabled(X86_FEATURE_X2AVIC_EXT))
1317 			x2avic_max_physical_id = X2AVIC_4K_MAX_PHYSICAL_ID;
1318 		else
1319 			x2avic_max_physical_id = X2AVIC_MAX_PHYSICAL_ID;
1320 		pr_info("x2AVIC enabled (max %u vCPUs)\n", x2avic_max_physical_id + 1);
1321 	} else {
1322 		svm_x86_ops.allow_apicv_in_x2apic_without_x2apic_virtualization = true;
1323 	}
1324 
1325 	/*
1326 	 * Disable IPI virtualization for AMD Family 17h (Zen1 and Zen2) and
1327 	 * Hygon Family 18h (derived from AMD Zen1) CPUs due to erratum 1235,
1328 	 * which results in missed VM-Exits on the sender and thus missed wake
1329 	 * events for blocking vCPUs due to the CPU failing to see a software
1330 	 * update to clear IsRunning.
1331 	 */
1332 	if (boot_cpu_data.x86 == 0x17 || boot_cpu_data.x86 == 0x18)
1333 		enable_ipiv = false;
1334 
1335 	amd_iommu_register_ga_log_notifier(&avic_ga_log_notifier);
1336 
1337 	return true;
1338 }
1339 
avic_hardware_unsetup(void)1340 void avic_hardware_unsetup(void)
1341 {
1342 	if (avic)
1343 		amd_iommu_register_ga_log_notifier(NULL);
1344 }
1345