326341a2215367301ba61ef001847ac645e4f391
[linux-block.git] / arch / x86 / kvm / svm / avic.c
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
22 #include <asm/irq_remapping.h>
23
24 #include "trace.h"
25 #include "lapic.h"
26 #include "x86.h"
27 #include "irq.h"
28 #include "svm.h"
29
30 /*
31  * Encode the arbitrary VM ID and the vCPU's default APIC ID, i.e the vCPU ID,
32  * into the GATag so that KVM can retrieve the correct vCPU from a GALog entry
33  * if an interrupt can't be delivered, e.g. because the vCPU isn't running.
34  *
35  * For the vCPU ID, use however many bits are currently allowed for the max
36  * guest physical APIC ID (limited by the size of the physical ID table), and
37  * use whatever bits remain to assign arbitrary AVIC IDs to VMs.  Note, the
38  * size of the GATag is defined by hardware (32 bits), but is an opaque value
39  * as far as hardware is concerned.
40  */
41 #define AVIC_VCPU_ID_MASK               AVIC_PHYSICAL_MAX_INDEX_MASK
42
43 #define AVIC_VM_ID_SHIFT                HWEIGHT32(AVIC_PHYSICAL_MAX_INDEX_MASK)
44 #define AVIC_VM_ID_MASK                 (GENMASK(31, AVIC_VM_ID_SHIFT) >> AVIC_VM_ID_SHIFT)
45
46 #define AVIC_GATAG(x, y)                (((x & AVIC_VM_ID_MASK) << AVIC_VM_ID_SHIFT) | \
47                                                 (y & AVIC_VCPU_ID_MASK))
48 #define AVIC_GATAG_TO_VMID(x)           ((x >> AVIC_VM_ID_SHIFT) & AVIC_VM_ID_MASK)
49 #define AVIC_GATAG_TO_VCPUID(x)         (x & AVIC_VCPU_ID_MASK)
50
51 static_assert(AVIC_GATAG(AVIC_VM_ID_MASK, AVIC_VCPU_ID_MASK) == -1u);
52
53 static bool force_avic;
54 module_param_unsafe(force_avic, bool, 0444);
55
56 /* Note:
57  * This hash table is used to map VM_ID to a struct kvm_svm,
58  * when handling AMD IOMMU GALOG notification to schedule in
59  * a particular vCPU.
60  */
61 #define SVM_VM_DATA_HASH_BITS   8
62 static DEFINE_HASHTABLE(svm_vm_data_hash, SVM_VM_DATA_HASH_BITS);
63 static u32 next_vm_id = 0;
64 static bool next_vm_id_wrapped = 0;
65 static DEFINE_SPINLOCK(svm_vm_data_hash_lock);
66 bool x2avic_enabled;
67
68 /*
69  * This is a wrapper of struct amd_iommu_ir_data.
70  */
71 struct amd_svm_iommu_ir {
72         struct list_head node;  /* Used by SVM for per-vcpu ir_list */
73         void *data;             /* Storing pointer to struct amd_ir_data */
74 };
75
76 static void avic_activate_vmcb(struct vcpu_svm *svm)
77 {
78         struct vmcb *vmcb = svm->vmcb01.ptr;
79
80         vmcb->control.int_ctl &= ~(AVIC_ENABLE_MASK | X2APIC_MODE_MASK);
81         vmcb->control.avic_physical_id &= ~AVIC_PHYSICAL_MAX_INDEX_MASK;
82
83         vmcb->control.int_ctl |= AVIC_ENABLE_MASK;
84
85         /*
86          * Note: KVM supports hybrid-AVIC mode, where KVM emulates x2APIC MSR
87          * accesses, while interrupt injection to a running vCPU can be
88          * achieved using AVIC doorbell.  KVM disables the APIC access page
89          * (deletes the memslot) if any vCPU has x2APIC enabled, thus enabling
90          * AVIC in hybrid mode activates only the doorbell mechanism.
91          */
92         if (x2avic_enabled && apic_x2apic_mode(svm->vcpu.arch.apic)) {
93                 vmcb->control.int_ctl |= X2APIC_MODE_MASK;
94                 vmcb->control.avic_physical_id |= X2AVIC_MAX_PHYSICAL_ID;
95                 /* Disabling MSR intercept for x2APIC registers */
96                 svm_set_x2apic_msr_interception(svm, false);
97         } else {
98                 /*
99                  * Flush the TLB, the guest may have inserted a non-APIC
100                  * mapping into the TLB while AVIC was disabled.
101                  */
102                 kvm_make_request(KVM_REQ_TLB_FLUSH_CURRENT, &svm->vcpu);
103
104                 /* For xAVIC and hybrid-xAVIC modes */
105                 vmcb->control.avic_physical_id |= AVIC_MAX_PHYSICAL_ID;
106                 /* Enabling MSR intercept for x2APIC registers */
107                 svm_set_x2apic_msr_interception(svm, true);
108         }
109 }
110
111 static void avic_deactivate_vmcb(struct vcpu_svm *svm)
112 {
113         struct vmcb *vmcb = svm->vmcb01.ptr;
114
115         vmcb->control.int_ctl &= ~(AVIC_ENABLE_MASK | X2APIC_MODE_MASK);
116         vmcb->control.avic_physical_id &= ~AVIC_PHYSICAL_MAX_INDEX_MASK;
117
118         /*
119          * If running nested and the guest uses its own MSR bitmap, there
120          * is no need to update L0's msr bitmap
121          */
122         if (is_guest_mode(&svm->vcpu) &&
123             vmcb12_is_intercept(&svm->nested.ctl, INTERCEPT_MSR_PROT))
124                 return;
125
126         /* Enabling MSR intercept for x2APIC registers */
127         svm_set_x2apic_msr_interception(svm, true);
128 }
129
130 /* Note:
131  * This function is called from IOMMU driver to notify
132  * SVM to schedule in a particular vCPU of a particular VM.
133  */
134 int avic_ga_log_notifier(u32 ga_tag)
135 {
136         unsigned long flags;
137         struct kvm_svm *kvm_svm;
138         struct kvm_vcpu *vcpu = NULL;
139         u32 vm_id = AVIC_GATAG_TO_VMID(ga_tag);
140         u32 vcpu_id = AVIC_GATAG_TO_VCPUID(ga_tag);
141
142         pr_debug("SVM: %s: vm_id=%#x, vcpu_id=%#x\n", __func__, vm_id, vcpu_id);
143         trace_kvm_avic_ga_log(vm_id, vcpu_id);
144
145         spin_lock_irqsave(&svm_vm_data_hash_lock, flags);
146         hash_for_each_possible(svm_vm_data_hash, kvm_svm, hnode, vm_id) {
147                 if (kvm_svm->avic_vm_id != vm_id)
148                         continue;
149                 vcpu = kvm_get_vcpu_by_id(&kvm_svm->kvm, vcpu_id);
150                 break;
151         }
152         spin_unlock_irqrestore(&svm_vm_data_hash_lock, flags);
153
154         /* Note:
155          * At this point, the IOMMU should have already set the pending
156          * bit in the vAPIC backing page. So, we just need to schedule
157          * in the vcpu.
158          */
159         if (vcpu)
160                 kvm_vcpu_wake_up(vcpu);
161
162         return 0;
163 }
164
165 void avic_vm_destroy(struct kvm *kvm)
166 {
167         unsigned long flags;
168         struct kvm_svm *kvm_svm = to_kvm_svm(kvm);
169
170         if (!enable_apicv)
171                 return;
172
173         if (kvm_svm->avic_logical_id_table_page)
174                 __free_page(kvm_svm->avic_logical_id_table_page);
175         if (kvm_svm->avic_physical_id_table_page)
176                 __free_page(kvm_svm->avic_physical_id_table_page);
177
178         spin_lock_irqsave(&svm_vm_data_hash_lock, flags);
179         hash_del(&kvm_svm->hnode);
180         spin_unlock_irqrestore(&svm_vm_data_hash_lock, flags);
181 }
182
183 int avic_vm_init(struct kvm *kvm)
184 {
185         unsigned long flags;
186         int err = -ENOMEM;
187         struct kvm_svm *kvm_svm = to_kvm_svm(kvm);
188         struct kvm_svm *k2;
189         struct page *p_page;
190         struct page *l_page;
191         u32 vm_id;
192
193         if (!enable_apicv)
194                 return 0;
195
196         /* Allocating physical APIC ID table (4KB) */
197         p_page = alloc_page(GFP_KERNEL_ACCOUNT | __GFP_ZERO);
198         if (!p_page)
199                 goto free_avic;
200
201         kvm_svm->avic_physical_id_table_page = p_page;
202
203         /* Allocating logical APIC ID table (4KB) */
204         l_page = alloc_page(GFP_KERNEL_ACCOUNT | __GFP_ZERO);
205         if (!l_page)
206                 goto free_avic;
207
208         kvm_svm->avic_logical_id_table_page = l_page;
209
210         spin_lock_irqsave(&svm_vm_data_hash_lock, flags);
211  again:
212         vm_id = next_vm_id = (next_vm_id + 1) & AVIC_VM_ID_MASK;
213         if (vm_id == 0) { /* id is 1-based, zero is not okay */
214                 next_vm_id_wrapped = 1;
215                 goto again;
216         }
217         /* Is it still in use? Only possible if wrapped at least once */
218         if (next_vm_id_wrapped) {
219                 hash_for_each_possible(svm_vm_data_hash, k2, hnode, vm_id) {
220                         if (k2->avic_vm_id == vm_id)
221                                 goto again;
222                 }
223         }
224         kvm_svm->avic_vm_id = vm_id;
225         hash_add(svm_vm_data_hash, &kvm_svm->hnode, kvm_svm->avic_vm_id);
226         spin_unlock_irqrestore(&svm_vm_data_hash_lock, flags);
227
228         return 0;
229
230 free_avic:
231         avic_vm_destroy(kvm);
232         return err;
233 }
234
235 void avic_init_vmcb(struct vcpu_svm *svm, struct vmcb *vmcb)
236 {
237         struct kvm_svm *kvm_svm = to_kvm_svm(svm->vcpu.kvm);
238         phys_addr_t bpa = __sme_set(page_to_phys(svm->avic_backing_page));
239         phys_addr_t lpa = __sme_set(page_to_phys(kvm_svm->avic_logical_id_table_page));
240         phys_addr_t ppa = __sme_set(page_to_phys(kvm_svm->avic_physical_id_table_page));
241
242         vmcb->control.avic_backing_page = bpa & AVIC_HPA_MASK;
243         vmcb->control.avic_logical_id = lpa & AVIC_HPA_MASK;
244         vmcb->control.avic_physical_id = ppa & AVIC_HPA_MASK;
245         vmcb->control.avic_vapic_bar = APIC_DEFAULT_PHYS_BASE & VMCB_AVIC_APIC_BAR_MASK;
246
247         if (kvm_apicv_activated(svm->vcpu.kvm))
248                 avic_activate_vmcb(svm);
249         else
250                 avic_deactivate_vmcb(svm);
251 }
252
253 static u64 *avic_get_physical_id_entry(struct kvm_vcpu *vcpu,
254                                        unsigned int index)
255 {
256         u64 *avic_physical_id_table;
257         struct kvm_svm *kvm_svm = to_kvm_svm(vcpu->kvm);
258
259         if ((!x2avic_enabled && index > AVIC_MAX_PHYSICAL_ID) ||
260             (index > X2AVIC_MAX_PHYSICAL_ID))
261                 return NULL;
262
263         avic_physical_id_table = page_address(kvm_svm->avic_physical_id_table_page);
264
265         return &avic_physical_id_table[index];
266 }
267
268 static int avic_init_backing_page(struct kvm_vcpu *vcpu)
269 {
270         u64 *entry, new_entry;
271         int id = vcpu->vcpu_id;
272         struct vcpu_svm *svm = to_svm(vcpu);
273
274         if ((!x2avic_enabled && id > AVIC_MAX_PHYSICAL_ID) ||
275             (id > X2AVIC_MAX_PHYSICAL_ID))
276                 return -EINVAL;
277
278         if (!vcpu->arch.apic->regs)
279                 return -EINVAL;
280
281         if (kvm_apicv_activated(vcpu->kvm)) {
282                 int ret;
283
284                 /*
285                  * Note, AVIC hardware walks the nested page table to check
286                  * permissions, but does not use the SPA address specified in
287                  * the leaf SPTE since it uses address in the AVIC_BACKING_PAGE
288                  * pointer field of the VMCB.
289                  */
290                 ret = kvm_alloc_apic_access_page(vcpu->kvm);
291                 if (ret)
292                         return ret;
293         }
294
295         svm->avic_backing_page = virt_to_page(vcpu->arch.apic->regs);
296
297         /* Setting AVIC backing page address in the phy APIC ID table */
298         entry = avic_get_physical_id_entry(vcpu, id);
299         if (!entry)
300                 return -EINVAL;
301
302         new_entry = __sme_set((page_to_phys(svm->avic_backing_page) &
303                               AVIC_PHYSICAL_ID_ENTRY_BACKING_PAGE_MASK) |
304                               AVIC_PHYSICAL_ID_ENTRY_VALID_MASK);
305         WRITE_ONCE(*entry, new_entry);
306
307         svm->avic_physical_id_cache = entry;
308
309         return 0;
310 }
311
312 void avic_ring_doorbell(struct kvm_vcpu *vcpu)
313 {
314         /*
315          * Note, the vCPU could get migrated to a different pCPU at any point,
316          * which could result in signalling the wrong/previous pCPU.  But if
317          * that happens the vCPU is guaranteed to do a VMRUN (after being
318          * migrated) and thus will process pending interrupts, i.e. a doorbell
319          * is not needed (and the spurious one is harmless).
320          */
321         int cpu = READ_ONCE(vcpu->cpu);
322
323         if (cpu != get_cpu()) {
324                 wrmsrl(MSR_AMD64_SVM_AVIC_DOORBELL, kvm_cpu_get_apicid(cpu));
325                 trace_kvm_avic_doorbell(vcpu->vcpu_id, kvm_cpu_get_apicid(cpu));
326         }
327         put_cpu();
328 }
329
330
331 static void avic_kick_vcpu(struct kvm_vcpu *vcpu, u32 icrl)
332 {
333         vcpu->arch.apic->irr_pending = true;
334         svm_complete_interrupt_delivery(vcpu,
335                                         icrl & APIC_MODE_MASK,
336                                         icrl & APIC_INT_LEVELTRIG,
337                                         icrl & APIC_VECTOR_MASK);
338 }
339
340 static void avic_kick_vcpu_by_physical_id(struct kvm *kvm, u32 physical_id,
341                                           u32 icrl)
342 {
343         /*
344          * KVM inhibits AVIC if any vCPU ID diverges from the vCPUs APIC ID,
345          * i.e. APIC ID == vCPU ID.
346          */
347         struct kvm_vcpu *target_vcpu = kvm_get_vcpu_by_id(kvm, physical_id);
348
349         /* Once again, nothing to do if the target vCPU doesn't exist. */
350         if (unlikely(!target_vcpu))
351                 return;
352
353         avic_kick_vcpu(target_vcpu, icrl);
354 }
355
356 static void avic_kick_vcpu_by_logical_id(struct kvm *kvm, u32 *avic_logical_id_table,
357                                          u32 logid_index, u32 icrl)
358 {
359         u32 physical_id;
360
361         if (avic_logical_id_table) {
362                 u32 logid_entry = avic_logical_id_table[logid_index];
363
364                 /* Nothing to do if the logical destination is invalid. */
365                 if (unlikely(!(logid_entry & AVIC_LOGICAL_ID_ENTRY_VALID_MASK)))
366                         return;
367
368                 physical_id = logid_entry &
369                               AVIC_LOGICAL_ID_ENTRY_GUEST_PHYSICAL_ID_MASK;
370         } else {
371                 /*
372                  * For x2APIC, the logical APIC ID is a read-only value that is
373                  * derived from the x2APIC ID, thus the x2APIC ID can be found
374                  * by reversing the calculation (stored in logid_index).  Note,
375                  * bits 31:20 of the x2APIC ID aren't propagated to the logical
376                  * ID, but KVM limits the x2APIC ID limited to KVM_MAX_VCPU_IDS.
377                  */
378                 physical_id = logid_index;
379         }
380
381         avic_kick_vcpu_by_physical_id(kvm, physical_id, icrl);
382 }
383
384 /*
385  * A fast-path version of avic_kick_target_vcpus(), which attempts to match
386  * destination APIC ID to vCPU without looping through all vCPUs.
387  */
388 static int avic_kick_target_vcpus_fast(struct kvm *kvm, struct kvm_lapic *source,
389                                        u32 icrl, u32 icrh, u32 index)
390 {
391         int dest_mode = icrl & APIC_DEST_MASK;
392         int shorthand = icrl & APIC_SHORT_MASK;
393         struct kvm_svm *kvm_svm = to_kvm_svm(kvm);
394         u32 dest;
395
396         if (shorthand != APIC_DEST_NOSHORT)
397                 return -EINVAL;
398
399         if (apic_x2apic_mode(source))
400                 dest = icrh;
401         else
402                 dest = GET_XAPIC_DEST_FIELD(icrh);
403
404         if (dest_mode == APIC_DEST_PHYSICAL) {
405                 /* broadcast destination, use slow path */
406                 if (apic_x2apic_mode(source) && dest == X2APIC_BROADCAST)
407                         return -EINVAL;
408                 if (!apic_x2apic_mode(source) && dest == APIC_BROADCAST)
409                         return -EINVAL;
410
411                 if (WARN_ON_ONCE(dest != index))
412                         return -EINVAL;
413
414                 avic_kick_vcpu_by_physical_id(kvm, dest, icrl);
415         } else {
416                 u32 *avic_logical_id_table;
417                 unsigned long bitmap, i;
418                 u32 cluster;
419
420                 if (apic_x2apic_mode(source)) {
421                         /* 16 bit dest mask, 16 bit cluster id */
422                         bitmap = dest & 0xFFFF;
423                         cluster = (dest >> 16) << 4;
424                 } else if (kvm_lapic_get_reg(source, APIC_DFR) == APIC_DFR_FLAT) {
425                         /* 8 bit dest mask*/
426                         bitmap = dest;
427                         cluster = 0;
428                 } else {
429                         /* 4 bit desk mask, 4 bit cluster id */
430                         bitmap = dest & 0xF;
431                         cluster = (dest >> 4) << 2;
432                 }
433
434                 /* Nothing to do if there are no destinations in the cluster. */
435                 if (unlikely(!bitmap))
436                         return 0;
437
438                 if (apic_x2apic_mode(source))
439                         avic_logical_id_table = NULL;
440                 else
441                         avic_logical_id_table = page_address(kvm_svm->avic_logical_id_table_page);
442
443                 /*
444                  * AVIC is inhibited if vCPUs aren't mapped 1:1 with logical
445                  * IDs, thus each bit in the destination is guaranteed to map
446                  * to at most one vCPU.
447                  */
448                 for_each_set_bit(i, &bitmap, 16)
449                         avic_kick_vcpu_by_logical_id(kvm, avic_logical_id_table,
450                                                      cluster + i, icrl);
451         }
452
453         return 0;
454 }
455
456 static void avic_kick_target_vcpus(struct kvm *kvm, struct kvm_lapic *source,
457                                    u32 icrl, u32 icrh, u32 index)
458 {
459         u32 dest = apic_x2apic_mode(source) ? icrh : GET_XAPIC_DEST_FIELD(icrh);
460         unsigned long i;
461         struct kvm_vcpu *vcpu;
462
463         if (!avic_kick_target_vcpus_fast(kvm, source, icrl, icrh, index))
464                 return;
465
466         trace_kvm_avic_kick_vcpu_slowpath(icrh, icrl, index);
467
468         /*
469          * Wake any target vCPUs that are blocking, i.e. waiting for a wake
470          * event.  There's no need to signal doorbells, as hardware has handled
471          * vCPUs that were in guest at the time of the IPI, and vCPUs that have
472          * since entered the guest will have processed pending IRQs at VMRUN.
473          */
474         kvm_for_each_vcpu(i, vcpu, kvm) {
475                 if (kvm_apic_match_dest(vcpu, source, icrl & APIC_SHORT_MASK,
476                                         dest, icrl & APIC_DEST_MASK))
477                         avic_kick_vcpu(vcpu, icrl);
478         }
479 }
480
481 int avic_incomplete_ipi_interception(struct kvm_vcpu *vcpu)
482 {
483         struct vcpu_svm *svm = to_svm(vcpu);
484         u32 icrh = svm->vmcb->control.exit_info_1 >> 32;
485         u32 icrl = svm->vmcb->control.exit_info_1;
486         u32 id = svm->vmcb->control.exit_info_2 >> 32;
487         u32 index = svm->vmcb->control.exit_info_2 & 0x1FF;
488         struct kvm_lapic *apic = vcpu->arch.apic;
489
490         trace_kvm_avic_incomplete_ipi(vcpu->vcpu_id, icrh, icrl, id, index);
491
492         switch (id) {
493         case AVIC_IPI_FAILURE_INVALID_TARGET:
494         case AVIC_IPI_FAILURE_INVALID_INT_TYPE:
495                 /*
496                  * Emulate IPIs that are not handled by AVIC hardware, which
497                  * only virtualizes Fixed, Edge-Triggered INTRs, and falls over
498                  * if _any_ targets are invalid, e.g. if the logical mode mask
499                  * is a superset of running vCPUs.
500                  *
501                  * The exit is a trap, e.g. ICR holds the correct value and RIP
502                  * has been advanced, KVM is responsible only for emulating the
503                  * IPI.  Sadly, hardware may sometimes leave the BUSY flag set,
504                  * in which case KVM needs to emulate the ICR write as well in
505                  * order to clear the BUSY flag.
506                  */
507                 if (icrl & APIC_ICR_BUSY)
508                         kvm_apic_write_nodecode(vcpu, APIC_ICR);
509                 else
510                         kvm_apic_send_ipi(apic, icrl, icrh);
511                 break;
512         case AVIC_IPI_FAILURE_TARGET_NOT_RUNNING:
513                 /*
514                  * At this point, we expect that the AVIC HW has already
515                  * set the appropriate IRR bits on the valid target
516                  * vcpus. So, we just need to kick the appropriate vcpu.
517                  */
518                 avic_kick_target_vcpus(vcpu->kvm, apic, icrl, icrh, index);
519                 break;
520         case AVIC_IPI_FAILURE_INVALID_BACKING_PAGE:
521                 WARN_ONCE(1, "Invalid backing page\n");
522                 break;
523         default:
524                 pr_err("Unknown IPI interception\n");
525         }
526
527         return 1;
528 }
529
530 unsigned long avic_vcpu_get_apicv_inhibit_reasons(struct kvm_vcpu *vcpu)
531 {
532         if (is_guest_mode(vcpu))
533                 return APICV_INHIBIT_REASON_NESTED;
534         return 0;
535 }
536
537 static u32 *avic_get_logical_id_entry(struct kvm_vcpu *vcpu, u32 ldr, bool flat)
538 {
539         struct kvm_svm *kvm_svm = to_kvm_svm(vcpu->kvm);
540         u32 *logical_apic_id_table;
541         u32 cluster, index;
542
543         ldr = GET_APIC_LOGICAL_ID(ldr);
544
545         if (flat) {
546                 cluster = 0;
547         } else {
548                 cluster = (ldr >> 4);
549                 if (cluster >= 0xf)
550                         return NULL;
551                 ldr &= 0xf;
552         }
553         if (!ldr || !is_power_of_2(ldr))
554                 return NULL;
555
556         index = __ffs(ldr);
557         if (WARN_ON_ONCE(index > 7))
558                 return NULL;
559         index += (cluster << 2);
560
561         logical_apic_id_table = (u32 *) page_address(kvm_svm->avic_logical_id_table_page);
562
563         return &logical_apic_id_table[index];
564 }
565
566 static void avic_ldr_write(struct kvm_vcpu *vcpu, u8 g_physical_id, u32 ldr)
567 {
568         bool flat;
569         u32 *entry, new_entry;
570
571         flat = kvm_lapic_get_reg(vcpu->arch.apic, APIC_DFR) == APIC_DFR_FLAT;
572         entry = avic_get_logical_id_entry(vcpu, ldr, flat);
573         if (!entry)
574                 return;
575
576         new_entry = READ_ONCE(*entry);
577         new_entry &= ~AVIC_LOGICAL_ID_ENTRY_GUEST_PHYSICAL_ID_MASK;
578         new_entry |= (g_physical_id & AVIC_LOGICAL_ID_ENTRY_GUEST_PHYSICAL_ID_MASK);
579         new_entry |= AVIC_LOGICAL_ID_ENTRY_VALID_MASK;
580         WRITE_ONCE(*entry, new_entry);
581 }
582
583 static void avic_invalidate_logical_id_entry(struct kvm_vcpu *vcpu)
584 {
585         struct vcpu_svm *svm = to_svm(vcpu);
586         bool flat = svm->dfr_reg == APIC_DFR_FLAT;
587         u32 *entry;
588
589         /* Note: x2AVIC does not use logical APIC ID table */
590         if (apic_x2apic_mode(vcpu->arch.apic))
591                 return;
592
593         entry = avic_get_logical_id_entry(vcpu, svm->ldr_reg, flat);
594         if (entry)
595                 clear_bit(AVIC_LOGICAL_ID_ENTRY_VALID_BIT, (unsigned long *)entry);
596 }
597
598 static void avic_handle_ldr_update(struct kvm_vcpu *vcpu)
599 {
600         struct vcpu_svm *svm = to_svm(vcpu);
601         u32 ldr = kvm_lapic_get_reg(vcpu->arch.apic, APIC_LDR);
602         u32 id = kvm_xapic_id(vcpu->arch.apic);
603
604         /* AVIC does not support LDR update for x2APIC */
605         if (apic_x2apic_mode(vcpu->arch.apic))
606                 return;
607
608         if (ldr == svm->ldr_reg)
609                 return;
610
611         avic_invalidate_logical_id_entry(vcpu);
612
613         svm->ldr_reg = ldr;
614         avic_ldr_write(vcpu, id, ldr);
615 }
616
617 static void avic_handle_dfr_update(struct kvm_vcpu *vcpu)
618 {
619         struct vcpu_svm *svm = to_svm(vcpu);
620         u32 dfr = kvm_lapic_get_reg(vcpu->arch.apic, APIC_DFR);
621
622         if (svm->dfr_reg == dfr)
623                 return;
624
625         avic_invalidate_logical_id_entry(vcpu);
626         svm->dfr_reg = dfr;
627 }
628
629 static int avic_unaccel_trap_write(struct kvm_vcpu *vcpu)
630 {
631         u32 offset = to_svm(vcpu)->vmcb->control.exit_info_1 &
632                                 AVIC_UNACCEL_ACCESS_OFFSET_MASK;
633
634         switch (offset) {
635         case APIC_LDR:
636                 avic_handle_ldr_update(vcpu);
637                 break;
638         case APIC_DFR:
639                 avic_handle_dfr_update(vcpu);
640                 break;
641         case APIC_RRR:
642                 /* Ignore writes to Read Remote Data, it's read-only. */
643                 return 1;
644         default:
645                 break;
646         }
647
648         kvm_apic_write_nodecode(vcpu, offset);
649         return 1;
650 }
651
652 static bool is_avic_unaccelerated_access_trap(u32 offset)
653 {
654         bool ret = false;
655
656         switch (offset) {
657         case APIC_ID:
658         case APIC_EOI:
659         case APIC_RRR:
660         case APIC_LDR:
661         case APIC_DFR:
662         case APIC_SPIV:
663         case APIC_ESR:
664         case APIC_ICR:
665         case APIC_LVTT:
666         case APIC_LVTTHMR:
667         case APIC_LVTPC:
668         case APIC_LVT0:
669         case APIC_LVT1:
670         case APIC_LVTERR:
671         case APIC_TMICT:
672         case APIC_TDCR:
673                 ret = true;
674                 break;
675         default:
676                 break;
677         }
678         return ret;
679 }
680
681 int avic_unaccelerated_access_interception(struct kvm_vcpu *vcpu)
682 {
683         struct vcpu_svm *svm = to_svm(vcpu);
684         int ret = 0;
685         u32 offset = svm->vmcb->control.exit_info_1 &
686                      AVIC_UNACCEL_ACCESS_OFFSET_MASK;
687         u32 vector = svm->vmcb->control.exit_info_2 &
688                      AVIC_UNACCEL_ACCESS_VECTOR_MASK;
689         bool write = (svm->vmcb->control.exit_info_1 >> 32) &
690                      AVIC_UNACCEL_ACCESS_WRITE_MASK;
691         bool trap = is_avic_unaccelerated_access_trap(offset);
692
693         trace_kvm_avic_unaccelerated_access(vcpu->vcpu_id, offset,
694                                             trap, write, vector);
695         if (trap) {
696                 /* Handling Trap */
697                 WARN_ONCE(!write, "svm: Handling trap read.\n");
698                 ret = avic_unaccel_trap_write(vcpu);
699         } else {
700                 /* Handling Fault */
701                 ret = kvm_emulate_instruction(vcpu, 0);
702         }
703
704         return ret;
705 }
706
707 int avic_init_vcpu(struct vcpu_svm *svm)
708 {
709         int ret;
710         struct kvm_vcpu *vcpu = &svm->vcpu;
711
712         if (!enable_apicv || !irqchip_in_kernel(vcpu->kvm))
713                 return 0;
714
715         ret = avic_init_backing_page(vcpu);
716         if (ret)
717                 return ret;
718
719         INIT_LIST_HEAD(&svm->ir_list);
720         spin_lock_init(&svm->ir_list_lock);
721         svm->dfr_reg = APIC_DFR_FLAT;
722
723         return ret;
724 }
725
726 void avic_apicv_post_state_restore(struct kvm_vcpu *vcpu)
727 {
728         avic_handle_dfr_update(vcpu);
729         avic_handle_ldr_update(vcpu);
730 }
731
732 static int avic_set_pi_irte_mode(struct kvm_vcpu *vcpu, bool activate)
733 {
734         int ret = 0;
735         unsigned long flags;
736         struct amd_svm_iommu_ir *ir;
737         struct vcpu_svm *svm = to_svm(vcpu);
738
739         if (!kvm_arch_has_assigned_device(vcpu->kvm))
740                 return 0;
741
742         /*
743          * Here, we go through the per-vcpu ir_list to update all existing
744          * interrupt remapping table entry targeting this vcpu.
745          */
746         spin_lock_irqsave(&svm->ir_list_lock, flags);
747
748         if (list_empty(&svm->ir_list))
749                 goto out;
750
751         list_for_each_entry(ir, &svm->ir_list, node) {
752                 if (activate)
753                         ret = amd_iommu_activate_guest_mode(ir->data);
754                 else
755                         ret = amd_iommu_deactivate_guest_mode(ir->data);
756                 if (ret)
757                         break;
758         }
759 out:
760         spin_unlock_irqrestore(&svm->ir_list_lock, flags);
761         return ret;
762 }
763
764 static void svm_ir_list_del(struct vcpu_svm *svm, struct amd_iommu_pi_data *pi)
765 {
766         unsigned long flags;
767         struct amd_svm_iommu_ir *cur;
768
769         spin_lock_irqsave(&svm->ir_list_lock, flags);
770         list_for_each_entry(cur, &svm->ir_list, node) {
771                 if (cur->data != pi->ir_data)
772                         continue;
773                 list_del(&cur->node);
774                 kfree(cur);
775                 break;
776         }
777         spin_unlock_irqrestore(&svm->ir_list_lock, flags);
778 }
779
780 static int svm_ir_list_add(struct vcpu_svm *svm, struct amd_iommu_pi_data *pi)
781 {
782         int ret = 0;
783         unsigned long flags;
784         struct amd_svm_iommu_ir *ir;
785
786         /**
787          * In some cases, the existing irte is updated and re-set,
788          * so we need to check here if it's already been * added
789          * to the ir_list.
790          */
791         if (pi->ir_data && (pi->prev_ga_tag != 0)) {
792                 struct kvm *kvm = svm->vcpu.kvm;
793                 u32 vcpu_id = AVIC_GATAG_TO_VCPUID(pi->prev_ga_tag);
794                 struct kvm_vcpu *prev_vcpu = kvm_get_vcpu_by_id(kvm, vcpu_id);
795                 struct vcpu_svm *prev_svm;
796
797                 if (!prev_vcpu) {
798                         ret = -EINVAL;
799                         goto out;
800                 }
801
802                 prev_svm = to_svm(prev_vcpu);
803                 svm_ir_list_del(prev_svm, pi);
804         }
805
806         /**
807          * Allocating new amd_iommu_pi_data, which will get
808          * add to the per-vcpu ir_list.
809          */
810         ir = kzalloc(sizeof(struct amd_svm_iommu_ir), GFP_KERNEL_ACCOUNT);
811         if (!ir) {
812                 ret = -ENOMEM;
813                 goto out;
814         }
815         ir->data = pi->ir_data;
816
817         spin_lock_irqsave(&svm->ir_list_lock, flags);
818         list_add(&ir->node, &svm->ir_list);
819         spin_unlock_irqrestore(&svm->ir_list_lock, flags);
820 out:
821         return ret;
822 }
823
824 /*
825  * Note:
826  * The HW cannot support posting multicast/broadcast
827  * interrupts to a vCPU. So, we still use legacy interrupt
828  * remapping for these kind of interrupts.
829  *
830  * For lowest-priority interrupts, we only support
831  * those with single CPU as the destination, e.g. user
832  * configures the interrupts via /proc/irq or uses
833  * irqbalance to make the interrupts single-CPU.
834  */
835 static int
836 get_pi_vcpu_info(struct kvm *kvm, struct kvm_kernel_irq_routing_entry *e,
837                  struct vcpu_data *vcpu_info, struct vcpu_svm **svm)
838 {
839         struct kvm_lapic_irq irq;
840         struct kvm_vcpu *vcpu = NULL;
841
842         kvm_set_msi_irq(kvm, e, &irq);
843
844         if (!kvm_intr_is_single_vcpu(kvm, &irq, &vcpu) ||
845             !kvm_irq_is_postable(&irq)) {
846                 pr_debug("SVM: %s: use legacy intr remap mode for irq %u\n",
847                          __func__, irq.vector);
848                 return -1;
849         }
850
851         pr_debug("SVM: %s: use GA mode for irq %u\n", __func__,
852                  irq.vector);
853         *svm = to_svm(vcpu);
854         vcpu_info->pi_desc_addr = __sme_set(page_to_phys((*svm)->avic_backing_page));
855         vcpu_info->vector = irq.vector;
856
857         return 0;
858 }
859
860 /*
861  * avic_pi_update_irte - set IRTE for Posted-Interrupts
862  *
863  * @kvm: kvm
864  * @host_irq: host irq of the interrupt
865  * @guest_irq: gsi of the interrupt
866  * @set: set or unset PI
867  * returns 0 on success, < 0 on failure
868  */
869 int avic_pi_update_irte(struct kvm *kvm, unsigned int host_irq,
870                         uint32_t guest_irq, bool set)
871 {
872         struct kvm_kernel_irq_routing_entry *e;
873         struct kvm_irq_routing_table *irq_rt;
874         int idx, ret = 0;
875
876         if (!kvm_arch_has_assigned_device(kvm) ||
877             !irq_remapping_cap(IRQ_POSTING_CAP))
878                 return 0;
879
880         pr_debug("SVM: %s: host_irq=%#x, guest_irq=%#x, set=%#x\n",
881                  __func__, host_irq, guest_irq, set);
882
883         idx = srcu_read_lock(&kvm->irq_srcu);
884         irq_rt = srcu_dereference(kvm->irq_routing, &kvm->irq_srcu);
885
886         if (guest_irq >= irq_rt->nr_rt_entries ||
887                 hlist_empty(&irq_rt->map[guest_irq])) {
888                 pr_warn_once("no route for guest_irq %u/%u (broken user space?)\n",
889                              guest_irq, irq_rt->nr_rt_entries);
890                 goto out;
891         }
892
893         hlist_for_each_entry(e, &irq_rt->map[guest_irq], link) {
894                 struct vcpu_data vcpu_info;
895                 struct vcpu_svm *svm = NULL;
896
897                 if (e->type != KVM_IRQ_ROUTING_MSI)
898                         continue;
899
900                 /**
901                  * Here, we setup with legacy mode in the following cases:
902                  * 1. When cannot target interrupt to a specific vcpu.
903                  * 2. Unsetting posted interrupt.
904                  * 3. APIC virtualization is disabled for the vcpu.
905                  * 4. IRQ has incompatible delivery mode (SMI, INIT, etc)
906                  */
907                 if (!get_pi_vcpu_info(kvm, e, &vcpu_info, &svm) && set &&
908                     kvm_vcpu_apicv_active(&svm->vcpu)) {
909                         struct amd_iommu_pi_data pi;
910
911                         /* Try to enable guest_mode in IRTE */
912                         pi.base = __sme_set(page_to_phys(svm->avic_backing_page) &
913                                             AVIC_HPA_MASK);
914                         pi.ga_tag = AVIC_GATAG(to_kvm_svm(kvm)->avic_vm_id,
915                                                      svm->vcpu.vcpu_id);
916                         pi.is_guest_mode = true;
917                         pi.vcpu_data = &vcpu_info;
918                         ret = irq_set_vcpu_affinity(host_irq, &pi);
919
920                         /**
921                          * Here, we successfully setting up vcpu affinity in
922                          * IOMMU guest mode. Now, we need to store the posted
923                          * interrupt information in a per-vcpu ir_list so that
924                          * we can reference to them directly when we update vcpu
925                          * scheduling information in IOMMU irte.
926                          */
927                         if (!ret && pi.is_guest_mode)
928                                 svm_ir_list_add(svm, &pi);
929                 } else {
930                         /* Use legacy mode in IRTE */
931                         struct amd_iommu_pi_data pi;
932
933                         /**
934                          * Here, pi is used to:
935                          * - Tell IOMMU to use legacy mode for this interrupt.
936                          * - Retrieve ga_tag of prior interrupt remapping data.
937                          */
938                         pi.prev_ga_tag = 0;
939                         pi.is_guest_mode = false;
940                         ret = irq_set_vcpu_affinity(host_irq, &pi);
941
942                         /**
943                          * Check if the posted interrupt was previously
944                          * setup with the guest_mode by checking if the ga_tag
945                          * was cached. If so, we need to clean up the per-vcpu
946                          * ir_list.
947                          */
948                         if (!ret && pi.prev_ga_tag) {
949                                 int id = AVIC_GATAG_TO_VCPUID(pi.prev_ga_tag);
950                                 struct kvm_vcpu *vcpu;
951
952                                 vcpu = kvm_get_vcpu_by_id(kvm, id);
953                                 if (vcpu)
954                                         svm_ir_list_del(to_svm(vcpu), &pi);
955                         }
956                 }
957
958                 if (!ret && svm) {
959                         trace_kvm_pi_irte_update(host_irq, svm->vcpu.vcpu_id,
960                                                  e->gsi, vcpu_info.vector,
961                                                  vcpu_info.pi_desc_addr, set);
962                 }
963
964                 if (ret < 0) {
965                         pr_err("%s: failed to update PI IRTE\n", __func__);
966                         goto out;
967                 }
968         }
969
970         ret = 0;
971 out:
972         srcu_read_unlock(&kvm->irq_srcu, idx);
973         return ret;
974 }
975
976 static inline int
977 avic_update_iommu_vcpu_affinity(struct kvm_vcpu *vcpu, int cpu, bool r)
978 {
979         int ret = 0;
980         unsigned long flags;
981         struct amd_svm_iommu_ir *ir;
982         struct vcpu_svm *svm = to_svm(vcpu);
983
984         if (!kvm_arch_has_assigned_device(vcpu->kvm))
985                 return 0;
986
987         /*
988          * Here, we go through the per-vcpu ir_list to update all existing
989          * interrupt remapping table entry targeting this vcpu.
990          */
991         spin_lock_irqsave(&svm->ir_list_lock, flags);
992
993         if (list_empty(&svm->ir_list))
994                 goto out;
995
996         list_for_each_entry(ir, &svm->ir_list, node) {
997                 ret = amd_iommu_update_ga(cpu, r, ir->data);
998                 if (ret)
999                         break;
1000         }
1001 out:
1002         spin_unlock_irqrestore(&svm->ir_list_lock, flags);
1003         return ret;
1004 }
1005
1006 void avic_vcpu_load(struct kvm_vcpu *vcpu, int cpu)
1007 {
1008         u64 entry;
1009         int h_physical_id = kvm_cpu_get_apicid(cpu);
1010         struct vcpu_svm *svm = to_svm(vcpu);
1011
1012         lockdep_assert_preemption_disabled();
1013
1014         if (WARN_ON(h_physical_id & ~AVIC_PHYSICAL_ID_ENTRY_HOST_PHYSICAL_ID_MASK))
1015                 return;
1016
1017         /*
1018          * No need to update anything if the vCPU is blocking, i.e. if the vCPU
1019          * is being scheduled in after being preempted.  The CPU entries in the
1020          * Physical APIC table and IRTE are consumed iff IsRun{ning} is '1'.
1021          * If the vCPU was migrated, its new CPU value will be stuffed when the
1022          * vCPU unblocks.
1023          */
1024         if (kvm_vcpu_is_blocking(vcpu))
1025                 return;
1026
1027         entry = READ_ONCE(*(svm->avic_physical_id_cache));
1028         WARN_ON_ONCE(entry & AVIC_PHYSICAL_ID_ENTRY_IS_RUNNING_MASK);
1029
1030         entry &= ~AVIC_PHYSICAL_ID_ENTRY_HOST_PHYSICAL_ID_MASK;
1031         entry |= (h_physical_id & AVIC_PHYSICAL_ID_ENTRY_HOST_PHYSICAL_ID_MASK);
1032         entry |= AVIC_PHYSICAL_ID_ENTRY_IS_RUNNING_MASK;
1033
1034         WRITE_ONCE(*(svm->avic_physical_id_cache), entry);
1035         avic_update_iommu_vcpu_affinity(vcpu, h_physical_id, true);
1036 }
1037
1038 void avic_vcpu_put(struct kvm_vcpu *vcpu)
1039 {
1040         u64 entry;
1041         struct vcpu_svm *svm = to_svm(vcpu);
1042
1043         lockdep_assert_preemption_disabled();
1044
1045         entry = READ_ONCE(*(svm->avic_physical_id_cache));
1046
1047         /* Nothing to do if IsRunning == '0' due to vCPU blocking. */
1048         if (!(entry & AVIC_PHYSICAL_ID_ENTRY_IS_RUNNING_MASK))
1049                 return;
1050
1051         avic_update_iommu_vcpu_affinity(vcpu, -1, 0);
1052
1053         entry &= ~AVIC_PHYSICAL_ID_ENTRY_IS_RUNNING_MASK;
1054         WRITE_ONCE(*(svm->avic_physical_id_cache), entry);
1055 }
1056
1057 void avic_refresh_virtual_apic_mode(struct kvm_vcpu *vcpu)
1058 {
1059         struct vcpu_svm *svm = to_svm(vcpu);
1060         struct vmcb *vmcb = svm->vmcb01.ptr;
1061
1062         if (!lapic_in_kernel(vcpu) || !enable_apicv)
1063                 return;
1064
1065         if (kvm_vcpu_apicv_active(vcpu)) {
1066                 /**
1067                  * During AVIC temporary deactivation, guest could update
1068                  * APIC ID, DFR and LDR registers, which would not be trapped
1069                  * by avic_unaccelerated_access_interception(). In this case,
1070                  * we need to check and update the AVIC logical APIC ID table
1071                  * accordingly before re-activating.
1072                  */
1073                 avic_apicv_post_state_restore(vcpu);
1074                 avic_activate_vmcb(svm);
1075         } else {
1076                 avic_deactivate_vmcb(svm);
1077         }
1078         vmcb_mark_dirty(vmcb, VMCB_AVIC);
1079 }
1080
1081 void avic_refresh_apicv_exec_ctrl(struct kvm_vcpu *vcpu)
1082 {
1083         bool activated = kvm_vcpu_apicv_active(vcpu);
1084
1085         if (!enable_apicv)
1086                 return;
1087
1088         avic_refresh_virtual_apic_mode(vcpu);
1089
1090         if (activated)
1091                 avic_vcpu_load(vcpu, vcpu->cpu);
1092         else
1093                 avic_vcpu_put(vcpu);
1094
1095         avic_set_pi_irte_mode(vcpu, activated);
1096 }
1097
1098 void avic_vcpu_blocking(struct kvm_vcpu *vcpu)
1099 {
1100         if (!kvm_vcpu_apicv_active(vcpu))
1101                 return;
1102
1103        /*
1104         * Unload the AVIC when the vCPU is about to block, _before_
1105         * the vCPU actually blocks.
1106         *
1107         * Any IRQs that arrive before IsRunning=0 will not cause an
1108         * incomplete IPI vmexit on the source, therefore vIRR will also
1109         * be checked by kvm_vcpu_check_block() before blocking.  The
1110         * memory barrier implicit in set_current_state orders writing
1111         * IsRunning=0 before reading the vIRR.  The processor needs a
1112         * matching memory barrier on interrupt delivery between writing
1113         * IRR and reading IsRunning; the lack of this barrier might be
1114         * the cause of errata #1235).
1115         */
1116         avic_vcpu_put(vcpu);
1117 }
1118
1119 void avic_vcpu_unblocking(struct kvm_vcpu *vcpu)
1120 {
1121         if (!kvm_vcpu_apicv_active(vcpu))
1122                 return;
1123
1124         avic_vcpu_load(vcpu, vcpu->cpu);
1125 }
1126
1127 /*
1128  * Note:
1129  * - The module param avic enable both xAPIC and x2APIC mode.
1130  * - Hypervisor can support both xAVIC and x2AVIC in the same guest.
1131  * - The mode can be switched at run-time.
1132  */
1133 bool avic_hardware_setup(void)
1134 {
1135         if (!npt_enabled)
1136                 return false;
1137
1138         /* AVIC is a prerequisite for x2AVIC. */
1139         if (!boot_cpu_has(X86_FEATURE_AVIC) && !force_avic) {
1140                 if (boot_cpu_has(X86_FEATURE_X2AVIC)) {
1141                         pr_warn(FW_BUG "Cannot support x2AVIC due to AVIC is disabled");
1142                         pr_warn(FW_BUG "Try enable AVIC using force_avic option");
1143                 }
1144                 return false;
1145         }
1146
1147         if (boot_cpu_has(X86_FEATURE_AVIC)) {
1148                 pr_info("AVIC enabled\n");
1149         } else if (force_avic) {
1150                 /*
1151                  * Some older systems does not advertise AVIC support.
1152                  * See Revision Guide for specific AMD processor for more detail.
1153                  */
1154                 pr_warn("AVIC is not supported in CPUID but force enabled");
1155                 pr_warn("Your system might crash and burn");
1156         }
1157
1158         /* AVIC is a prerequisite for x2AVIC. */
1159         x2avic_enabled = boot_cpu_has(X86_FEATURE_X2AVIC);
1160         if (x2avic_enabled)
1161                 pr_info("x2AVIC enabled\n");
1162
1163         amd_iommu_register_ga_log_notifier(&avic_ga_log_notifier);
1164
1165         return true;
1166 }