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