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