// SPDX-License-Identifier: GPL-2.0-only1/*2* Copyright (C) 2015, 2016 ARM Ltd.3*/45#include <linux/interrupt.h>6#include <linux/irq.h>7#include <linux/kvm.h>8#include <linux/kvm_host.h>9#include <linux/list_sort.h>10#include <linux/nospec.h>1112#include <asm/kvm_hyp.h>1314#include "vgic.h"1516#define CREATE_TRACE_POINTS17#include "trace.h"1819struct vgic_global kvm_vgic_global_state __ro_after_init = {20.gicv3_cpuif = STATIC_KEY_FALSE_INIT,21};2223/*24* Locking order is always:25* kvm->lock (mutex)26* vcpu->mutex (mutex)27* kvm->arch.config_lock (mutex)28* its->cmd_lock (mutex)29* its->its_lock (mutex)30* vgic_dist->lpi_xa.xa_lock must be taken with IRQs disabled31* vgic_cpu->ap_list_lock must be taken with IRQs disabled32* vgic_irq->irq_lock must be taken with IRQs disabled33*34* As the ap_list_lock might be taken from the timer interrupt handler,35* we have to disable IRQs before taking this lock and everything lower36* than it.37*38* The config_lock has additional ordering requirements:39* kvm->slots_lock40* kvm->srcu41* kvm->arch.config_lock42*43* If you need to take multiple locks, always take the upper lock first,44* then the lower ones, e.g. first take the its_lock, then the irq_lock.45* If you are already holding a lock and need to take a higher one, you46* have to drop the lower ranking lock first and re-acquire it after having47* taken the upper one.48*49* When taking more than one ap_list_lock at the same time, always take the50* lowest numbered VCPU's ap_list_lock first, so:51* vcpuX->vcpu_id < vcpuY->vcpu_id:52* raw_spin_lock(vcpuX->arch.vgic_cpu.ap_list_lock);53* raw_spin_lock(vcpuY->arch.vgic_cpu.ap_list_lock);54*55* Since the VGIC must support injecting virtual interrupts from ISRs, we have56* to use the raw_spin_lock_irqsave/raw_spin_unlock_irqrestore versions of outer57* spinlocks for any lock that may be taken while injecting an interrupt.58*/5960/*61* Index the VM's xarray of mapped LPIs and return a reference to the IRQ62* structure. The caller is expected to call vgic_put_irq() later once it's63* finished with the IRQ.64*/65static struct vgic_irq *vgic_get_lpi(struct kvm *kvm, u32 intid)66{67struct vgic_dist *dist = &kvm->arch.vgic;68struct vgic_irq *irq = NULL;6970rcu_read_lock();7172irq = xa_load(&dist->lpi_xa, intid);73if (!vgic_try_get_irq_ref(irq))74irq = NULL;7576rcu_read_unlock();7778return irq;79}8081/*82* This looks up the virtual interrupt ID to get the corresponding83* struct vgic_irq. It also increases the refcount, so any caller is expected84* to call vgic_put_irq() once it's finished with this IRQ.85*/86struct vgic_irq *vgic_get_irq(struct kvm *kvm, u32 intid)87{88/* SPIs */89if (intid >= VGIC_NR_PRIVATE_IRQS &&90intid < (kvm->arch.vgic.nr_spis + VGIC_NR_PRIVATE_IRQS)) {91intid = array_index_nospec(intid, kvm->arch.vgic.nr_spis + VGIC_NR_PRIVATE_IRQS);92return &kvm->arch.vgic.spis[intid - VGIC_NR_PRIVATE_IRQS];93}9495/* LPIs */96if (intid >= VGIC_MIN_LPI)97return vgic_get_lpi(kvm, intid);9899return NULL;100}101102struct vgic_irq *vgic_get_vcpu_irq(struct kvm_vcpu *vcpu, u32 intid)103{104if (WARN_ON(!vcpu))105return NULL;106107/* SGIs and PPIs */108if (intid < VGIC_NR_PRIVATE_IRQS) {109intid = array_index_nospec(intid, VGIC_NR_PRIVATE_IRQS);110return &vcpu->arch.vgic_cpu.private_irqs[intid];111}112113return vgic_get_irq(vcpu->kvm, intid);114}115116static void vgic_release_lpi_locked(struct vgic_dist *dist, struct vgic_irq *irq)117{118lockdep_assert_held(&dist->lpi_xa.xa_lock);119__xa_erase(&dist->lpi_xa, irq->intid);120kfree_rcu(irq, rcu);121}122123static __must_check bool __vgic_put_irq(struct kvm *kvm, struct vgic_irq *irq)124{125if (irq->intid < VGIC_MIN_LPI)126return false;127128return refcount_dec_and_test(&irq->refcount);129}130131static __must_check bool vgic_put_irq_norelease(struct kvm *kvm, struct vgic_irq *irq)132{133if (!__vgic_put_irq(kvm, irq))134return false;135136irq->pending_release = true;137return true;138}139140void vgic_put_irq(struct kvm *kvm, struct vgic_irq *irq)141{142struct vgic_dist *dist = &kvm->arch.vgic;143unsigned long flags;144145/*146* Normally the lock is only taken when the refcount drops to 0.147* Acquire/release it early on lockdep kernels to make locking issues148* in rare release paths a bit more obvious.149*/150if (IS_ENABLED(CONFIG_LOCKDEP) && irq->intid >= VGIC_MIN_LPI) {151guard(spinlock_irqsave)(&dist->lpi_xa.xa_lock);152}153154if (!__vgic_put_irq(kvm, irq))155return;156157xa_lock_irqsave(&dist->lpi_xa, flags);158vgic_release_lpi_locked(dist, irq);159xa_unlock_irqrestore(&dist->lpi_xa, flags);160}161162static void vgic_release_deleted_lpis(struct kvm *kvm)163{164struct vgic_dist *dist = &kvm->arch.vgic;165unsigned long flags, intid;166struct vgic_irq *irq;167168xa_lock_irqsave(&dist->lpi_xa, flags);169170xa_for_each(&dist->lpi_xa, intid, irq) {171if (irq->pending_release)172vgic_release_lpi_locked(dist, irq);173}174175xa_unlock_irqrestore(&dist->lpi_xa, flags);176}177178void vgic_flush_pending_lpis(struct kvm_vcpu *vcpu)179{180struct vgic_cpu *vgic_cpu = &vcpu->arch.vgic_cpu;181struct vgic_irq *irq, *tmp;182bool deleted = false;183unsigned long flags;184185raw_spin_lock_irqsave(&vgic_cpu->ap_list_lock, flags);186187list_for_each_entry_safe(irq, tmp, &vgic_cpu->ap_list_head, ap_list) {188if (irq->intid >= VGIC_MIN_LPI) {189raw_spin_lock(&irq->irq_lock);190list_del(&irq->ap_list);191irq->vcpu = NULL;192raw_spin_unlock(&irq->irq_lock);193deleted |= vgic_put_irq_norelease(vcpu->kvm, irq);194}195}196197raw_spin_unlock_irqrestore(&vgic_cpu->ap_list_lock, flags);198199if (deleted)200vgic_release_deleted_lpis(vcpu->kvm);201}202203void vgic_irq_set_phys_pending(struct vgic_irq *irq, bool pending)204{205WARN_ON(irq_set_irqchip_state(irq->host_irq,206IRQCHIP_STATE_PENDING,207pending));208}209210bool vgic_get_phys_line_level(struct vgic_irq *irq)211{212bool line_level;213214BUG_ON(!irq->hw);215216if (irq->ops && irq->ops->get_input_level)217return irq->ops->get_input_level(irq->intid);218219WARN_ON(irq_get_irqchip_state(irq->host_irq,220IRQCHIP_STATE_PENDING,221&line_level));222return line_level;223}224225/* Set/Clear the physical active state */226void vgic_irq_set_phys_active(struct vgic_irq *irq, bool active)227{228229BUG_ON(!irq->hw);230WARN_ON(irq_set_irqchip_state(irq->host_irq,231IRQCHIP_STATE_ACTIVE,232active));233}234235/**236* vgic_target_oracle - compute the target vcpu for an irq237*238* @irq: The irq to route. Must be already locked.239*240* Based on the current state of the interrupt (enabled, pending,241* active, vcpu and target_vcpu), compute the next vcpu this should be242* given to. Return NULL if this shouldn't be injected at all.243*244* Requires the IRQ lock to be held.245*/246struct kvm_vcpu *vgic_target_oracle(struct vgic_irq *irq)247{248lockdep_assert_held(&irq->irq_lock);249250/* If the interrupt is active, it must stay on the current vcpu */251if (irq->active)252return irq->vcpu ? : irq->target_vcpu;253254/*255* If the IRQ is not active but enabled and pending, we should direct256* it to its configured target VCPU.257* If the distributor is disabled, pending interrupts shouldn't be258* forwarded.259*/260if (irq->enabled && irq_is_pending(irq)) {261if (unlikely(irq->target_vcpu &&262!irq->target_vcpu->kvm->arch.vgic.enabled))263return NULL;264265return irq->target_vcpu;266}267268/* If neither active nor pending and enabled, then this IRQ should not269* be queued to any VCPU.270*/271return NULL;272}273274struct vgic_sort_info {275struct kvm_vcpu *vcpu;276struct vgic_vmcr vmcr;277};278279/*280* The order of items in the ap_lists defines how we'll pack things in LRs as281* well, the first items in the list being the first things populated in the282* LRs.283*284* Pending, non-active interrupts must be placed at the head of the list.285* Otherwise things should be sorted by the priority field and the GIC286* hardware support will take care of preemption of priority groups etc.287* Interrupts that are not deliverable should be at the end of the list.288*289* Return negative if "a" sorts before "b", 0 to preserve order, and positive290* to sort "b" before "a".291*/292static int vgic_irq_cmp(void *priv, const struct list_head *a,293const struct list_head *b)294{295struct vgic_irq *irqa = container_of(a, struct vgic_irq, ap_list);296struct vgic_irq *irqb = container_of(b, struct vgic_irq, ap_list);297struct vgic_sort_info *info = priv;298struct kvm_vcpu *vcpu = info->vcpu;299bool penda, pendb;300int ret;301302/*303* list_sort may call this function with the same element when304* the list is fairly long.305*/306if (unlikely(irqa == irqb))307return 0;308309raw_spin_lock(&irqa->irq_lock);310raw_spin_lock_nested(&irqb->irq_lock, SINGLE_DEPTH_NESTING);311312/* Undeliverable interrupts should be last */313ret = (int)(vgic_target_oracle(irqb) == vcpu) - (int)(vgic_target_oracle(irqa) == vcpu);314if (ret)315goto out;316317/* Same thing for interrupts targeting a disabled group */318ret = (int)(irqb->group ? info->vmcr.grpen1 : info->vmcr.grpen0);319ret -= (int)(irqa->group ? info->vmcr.grpen1 : info->vmcr.grpen0);320if (ret)321goto out;322323penda = irqa->enabled && irq_is_pending(irqa) && !irqa->active;324pendb = irqb->enabled && irq_is_pending(irqb) && !irqb->active;325326ret = (int)pendb - (int)penda;327if (ret)328goto out;329330/* Both pending and enabled, sort by priority (lower number first) */331ret = (int)irqa->priority - (int)irqb->priority;332if (ret)333goto out;334335/* Finally, HW bit active interrupts have priority over non-HW ones */336ret = (int)irqb->hw - (int)irqa->hw;337338out:339raw_spin_unlock(&irqb->irq_lock);340raw_spin_unlock(&irqa->irq_lock);341return ret;342}343344/* Must be called with the ap_list_lock held */345static void vgic_sort_ap_list(struct kvm_vcpu *vcpu)346{347struct vgic_cpu *vgic_cpu = &vcpu->arch.vgic_cpu;348struct vgic_sort_info info = { .vcpu = vcpu, };349350lockdep_assert_held(&vgic_cpu->ap_list_lock);351352vgic_get_vmcr(vcpu, &info.vmcr);353list_sort(&info, &vgic_cpu->ap_list_head, vgic_irq_cmp);354}355356/*357* Only valid injection if changing level for level-triggered IRQs or for a358* rising edge, and in-kernel connected IRQ lines can only be controlled by359* their owner.360*/361static bool vgic_validate_injection(struct vgic_irq *irq, bool level, void *owner)362{363if (irq->owner != owner)364return false;365366switch (irq->config) {367case VGIC_CONFIG_LEVEL:368return irq->line_level != level;369case VGIC_CONFIG_EDGE:370return level;371}372373return false;374}375376static bool vgic_model_needs_bcst_kick(struct kvm *kvm)377{378/*379* A GICv3 (or GICv3-like) system exposing a GICv3 to the guest380* needs a broadcast kick to set TDIR globally.381*382* For systems that do not have TDIR (ARM's own v8.0 CPUs), the383* shadow TDIR bit is always set, and so is the register's TC bit,384* so no need to kick the CPUs.385*/386return (cpus_have_final_cap(ARM64_HAS_ICH_HCR_EL2_TDIR) &&387kvm->arch.vgic.vgic_model == KVM_DEV_TYPE_ARM_VGIC_V3);388}389390/*391* Check whether an IRQ needs to (and can) be queued to a VCPU's ap list.392* Do the queuing if necessary, taking the right locks in the right order.393* Returns true when the IRQ was queued, false otherwise.394*395* Needs to be entered with the IRQ lock already held, but will return396* with all locks dropped.397*/398bool vgic_queue_irq_unlock(struct kvm *kvm, struct vgic_irq *irq,399unsigned long flags) __releases(&irq->irq_lock)400{401struct kvm_vcpu *vcpu;402bool bcast;403404lockdep_assert_held(&irq->irq_lock);405406retry:407vcpu = vgic_target_oracle(irq);408if (irq->vcpu || !vcpu) {409/*410* If this IRQ is already on a VCPU's ap_list, then it411* cannot be moved or modified and there is no more work for412* us to do.413*414* Otherwise, if the irq is not pending and enabled, it does415* not need to be inserted into an ap_list and there is also416* no more work for us to do.417*/418raw_spin_unlock_irqrestore(&irq->irq_lock, flags);419420/*421* We have to kick the VCPU here, because we could be422* queueing an edge-triggered interrupt for which we423* get no EOI maintenance interrupt. In that case,424* while the IRQ is already on the VCPU's AP list, the425* VCPU could have EOI'ed the original interrupt and426* won't see this one until it exits for some other427* reason.428*/429if (vcpu) {430kvm_make_request(KVM_REQ_IRQ_PENDING, vcpu);431kvm_vcpu_kick(vcpu);432}433return false;434}435436/*437* We must unlock the irq lock to take the ap_list_lock where438* we are going to insert this new pending interrupt.439*/440raw_spin_unlock_irqrestore(&irq->irq_lock, flags);441442/* someone can do stuff here, which we re-check below */443444raw_spin_lock_irqsave(&vcpu->arch.vgic_cpu.ap_list_lock, flags);445raw_spin_lock(&irq->irq_lock);446447/*448* Did something change behind our backs?449*450* There are two cases:451* 1) The irq lost its pending state or was disabled behind our452* backs and/or it was queued to another VCPU's ap_list.453* 2) Someone changed the affinity on this irq behind our454* backs and we are now holding the wrong ap_list_lock.455*456* In both cases, drop the locks and retry.457*/458459if (unlikely(irq->vcpu || vcpu != vgic_target_oracle(irq))) {460raw_spin_unlock(&irq->irq_lock);461raw_spin_unlock_irqrestore(&vcpu->arch.vgic_cpu.ap_list_lock,462flags);463464raw_spin_lock_irqsave(&irq->irq_lock, flags);465goto retry;466}467468/*469* Grab a reference to the irq to reflect the fact that it is470* now in the ap_list. This is safe as the caller must already hold a471* reference on the irq.472*/473vgic_get_irq_ref(irq);474list_add_tail(&irq->ap_list, &vcpu->arch.vgic_cpu.ap_list_head);475irq->vcpu = vcpu;476477/* A new SPI may result in deactivation trapping on all vcpus */478bcast = (vgic_model_needs_bcst_kick(vcpu->kvm) &&479vgic_valid_spi(vcpu->kvm, irq->intid) &&480atomic_fetch_inc(&vcpu->kvm->arch.vgic.active_spis) == 0);481482raw_spin_unlock(&irq->irq_lock);483raw_spin_unlock_irqrestore(&vcpu->arch.vgic_cpu.ap_list_lock, flags);484485if (!bcast) {486kvm_make_request(KVM_REQ_IRQ_PENDING, vcpu);487kvm_vcpu_kick(vcpu);488} else {489kvm_make_all_cpus_request(vcpu->kvm, KVM_REQ_IRQ_PENDING);490}491492return true;493}494495/**496* kvm_vgic_inject_irq - Inject an IRQ from a device to the vgic497* @kvm: The VM structure pointer498* @vcpu: The CPU for PPIs or NULL for global interrupts499* @intid: The INTID to inject a new state to.500* @level: Edge-triggered: true: to trigger the interrupt501* false: to ignore the call502* Level-sensitive true: raise the input signal503* false: lower the input signal504* @owner: The opaque pointer to the owner of the IRQ being raised to verify505* that the caller is allowed to inject this IRQ. Userspace506* injections will have owner == NULL.507*508* The VGIC is not concerned with devices being active-LOW or active-HIGH for509* level-sensitive interrupts. You can think of the level parameter as 1510* being HIGH and 0 being LOW and all devices being active-HIGH.511*/512int kvm_vgic_inject_irq(struct kvm *kvm, struct kvm_vcpu *vcpu,513unsigned int intid, bool level, void *owner)514{515struct vgic_irq *irq;516unsigned long flags;517int ret;518519ret = vgic_lazy_init(kvm);520if (ret)521return ret;522523if (!vcpu && intid < VGIC_NR_PRIVATE_IRQS)524return -EINVAL;525526trace_vgic_update_irq_pending(vcpu ? vcpu->vcpu_idx : 0, intid, level);527528if (intid < VGIC_NR_PRIVATE_IRQS)529irq = vgic_get_vcpu_irq(vcpu, intid);530else531irq = vgic_get_irq(kvm, intid);532if (!irq)533return -EINVAL;534535raw_spin_lock_irqsave(&irq->irq_lock, flags);536537if (!vgic_validate_injection(irq, level, owner)) {538/* Nothing to see here, move along... */539raw_spin_unlock_irqrestore(&irq->irq_lock, flags);540vgic_put_irq(kvm, irq);541return 0;542}543544if (irq->config == VGIC_CONFIG_LEVEL)545irq->line_level = level;546else547irq->pending_latch = true;548549vgic_queue_irq_unlock(kvm, irq, flags);550vgic_put_irq(kvm, irq);551552return 0;553}554555/* @irq->irq_lock must be held */556static int kvm_vgic_map_irq(struct kvm_vcpu *vcpu, struct vgic_irq *irq,557unsigned int host_irq,558struct irq_ops *ops)559{560struct irq_desc *desc;561struct irq_data *data;562563/*564* Find the physical IRQ number corresponding to @host_irq565*/566desc = irq_to_desc(host_irq);567if (!desc) {568kvm_err("%s: no interrupt descriptor\n", __func__);569return -EINVAL;570}571data = irq_desc_get_irq_data(desc);572while (data->parent_data)573data = data->parent_data;574575irq->hw = true;576irq->host_irq = host_irq;577irq->hwintid = data->hwirq;578irq->ops = ops;579return 0;580}581582/* @irq->irq_lock must be held */583static inline void kvm_vgic_unmap_irq(struct vgic_irq *irq)584{585irq->hw = false;586irq->hwintid = 0;587irq->ops = NULL;588}589590int kvm_vgic_map_phys_irq(struct kvm_vcpu *vcpu, unsigned int host_irq,591u32 vintid, struct irq_ops *ops)592{593struct vgic_irq *irq = vgic_get_vcpu_irq(vcpu, vintid);594unsigned long flags;595int ret;596597BUG_ON(!irq);598599raw_spin_lock_irqsave(&irq->irq_lock, flags);600ret = kvm_vgic_map_irq(vcpu, irq, host_irq, ops);601raw_spin_unlock_irqrestore(&irq->irq_lock, flags);602vgic_put_irq(vcpu->kvm, irq);603604return ret;605}606607/**608* kvm_vgic_reset_mapped_irq - Reset a mapped IRQ609* @vcpu: The VCPU pointer610* @vintid: The INTID of the interrupt611*612* Reset the active and pending states of a mapped interrupt. Kernel613* subsystems injecting mapped interrupts should reset their interrupt lines614* when we are doing a reset of the VM.615*/616void kvm_vgic_reset_mapped_irq(struct kvm_vcpu *vcpu, u32 vintid)617{618struct vgic_irq *irq = vgic_get_vcpu_irq(vcpu, vintid);619unsigned long flags;620621if (!irq->hw)622goto out;623624raw_spin_lock_irqsave(&irq->irq_lock, flags);625irq->active = false;626irq->pending_latch = false;627irq->line_level = false;628raw_spin_unlock_irqrestore(&irq->irq_lock, flags);629out:630vgic_put_irq(vcpu->kvm, irq);631}632633int kvm_vgic_unmap_phys_irq(struct kvm_vcpu *vcpu, unsigned int vintid)634{635struct vgic_irq *irq;636unsigned long flags;637638if (!vgic_initialized(vcpu->kvm))639return -EAGAIN;640641irq = vgic_get_vcpu_irq(vcpu, vintid);642BUG_ON(!irq);643644raw_spin_lock_irqsave(&irq->irq_lock, flags);645kvm_vgic_unmap_irq(irq);646raw_spin_unlock_irqrestore(&irq->irq_lock, flags);647vgic_put_irq(vcpu->kvm, irq);648649return 0;650}651652int kvm_vgic_get_map(struct kvm_vcpu *vcpu, unsigned int vintid)653{654struct vgic_irq *irq = vgic_get_vcpu_irq(vcpu, vintid);655unsigned long flags;656int ret = -1;657658raw_spin_lock_irqsave(&irq->irq_lock, flags);659if (irq->hw)660ret = irq->hwintid;661raw_spin_unlock_irqrestore(&irq->irq_lock, flags);662663vgic_put_irq(vcpu->kvm, irq);664return ret;665}666667/**668* kvm_vgic_set_owner - Set the owner of an interrupt for a VM669*670* @vcpu: Pointer to the VCPU (used for PPIs)671* @intid: The virtual INTID identifying the interrupt (PPI or SPI)672* @owner: Opaque pointer to the owner673*674* Returns 0 if intid is not already used by another in-kernel device and the675* owner is set, otherwise returns an error code.676*/677int kvm_vgic_set_owner(struct kvm_vcpu *vcpu, unsigned int intid, void *owner)678{679struct vgic_irq *irq;680unsigned long flags;681int ret = 0;682683if (!vgic_initialized(vcpu->kvm))684return -EAGAIN;685686/* SGIs and LPIs cannot be wired up to any device */687if (!irq_is_ppi(intid) && !vgic_valid_spi(vcpu->kvm, intid))688return -EINVAL;689690irq = vgic_get_vcpu_irq(vcpu, intid);691raw_spin_lock_irqsave(&irq->irq_lock, flags);692if (irq->owner && irq->owner != owner)693ret = -EEXIST;694else695irq->owner = owner;696raw_spin_unlock_irqrestore(&irq->irq_lock, flags);697698return ret;699}700701/**702* vgic_prune_ap_list - Remove non-relevant interrupts from the list703*704* @vcpu: The VCPU pointer705*706* Go over the list of "interesting" interrupts, and prune those that we707* won't have to consider in the near future.708*/709static void vgic_prune_ap_list(struct kvm_vcpu *vcpu)710{711struct vgic_cpu *vgic_cpu = &vcpu->arch.vgic_cpu;712struct vgic_irq *irq, *tmp;713bool deleted_lpis = false;714715DEBUG_SPINLOCK_BUG_ON(!irqs_disabled());716717retry:718raw_spin_lock(&vgic_cpu->ap_list_lock);719720list_for_each_entry_safe(irq, tmp, &vgic_cpu->ap_list_head, ap_list) {721struct kvm_vcpu *target_vcpu, *vcpuA, *vcpuB;722bool target_vcpu_needs_kick = false;723724raw_spin_lock(&irq->irq_lock);725726BUG_ON(vcpu != irq->vcpu);727728target_vcpu = vgic_target_oracle(irq);729730if (!target_vcpu) {731/*732* We don't need to process this interrupt any733* further, move it off the list.734*/735list_del(&irq->ap_list);736irq->vcpu = NULL;737raw_spin_unlock(&irq->irq_lock);738739/*740* This vgic_put_irq call matches the741* vgic_get_irq_ref in vgic_queue_irq_unlock,742* where we added the LPI to the ap_list. As743* we remove the irq from the list, we drop744* also drop the refcount.745*/746deleted_lpis |= vgic_put_irq_norelease(vcpu->kvm, irq);747continue;748}749750if (target_vcpu == vcpu) {751/* We're on the right CPU */752raw_spin_unlock(&irq->irq_lock);753continue;754}755756/* This interrupt looks like it has to be migrated. */757758raw_spin_unlock(&irq->irq_lock);759raw_spin_unlock(&vgic_cpu->ap_list_lock);760761/*762* Ensure locking order by always locking the smallest763* ID first.764*/765if (vcpu->vcpu_id < target_vcpu->vcpu_id) {766vcpuA = vcpu;767vcpuB = target_vcpu;768} else {769vcpuA = target_vcpu;770vcpuB = vcpu;771}772773raw_spin_lock(&vcpuA->arch.vgic_cpu.ap_list_lock);774raw_spin_lock_nested(&vcpuB->arch.vgic_cpu.ap_list_lock,775SINGLE_DEPTH_NESTING);776raw_spin_lock(&irq->irq_lock);777778/*779* If the affinity has been preserved, move the780* interrupt around. Otherwise, it means things have781* changed while the interrupt was unlocked, and we782* need to replay this.783*784* In all cases, we cannot trust the list not to have785* changed, so we restart from the beginning.786*/787if (target_vcpu == vgic_target_oracle(irq)) {788struct vgic_cpu *new_cpu = &target_vcpu->arch.vgic_cpu;789790list_del(&irq->ap_list);791irq->vcpu = target_vcpu;792list_add_tail(&irq->ap_list, &new_cpu->ap_list_head);793target_vcpu_needs_kick = true;794}795796raw_spin_unlock(&irq->irq_lock);797raw_spin_unlock(&vcpuB->arch.vgic_cpu.ap_list_lock);798raw_spin_unlock(&vcpuA->arch.vgic_cpu.ap_list_lock);799800if (target_vcpu_needs_kick) {801kvm_make_request(KVM_REQ_IRQ_PENDING, target_vcpu);802kvm_vcpu_kick(target_vcpu);803}804805goto retry;806}807808raw_spin_unlock(&vgic_cpu->ap_list_lock);809810if (unlikely(deleted_lpis))811vgic_release_deleted_lpis(vcpu->kvm);812}813814static inline void vgic_fold_lr_state(struct kvm_vcpu *vcpu)815{816if (kvm_vgic_global_state.type == VGIC_V2)817vgic_v2_fold_lr_state(vcpu);818else819vgic_v3_fold_lr_state(vcpu);820}821822/* Requires the irq_lock to be held. */823static inline void vgic_populate_lr(struct kvm_vcpu *vcpu,824struct vgic_irq *irq, int lr)825{826lockdep_assert_held(&irq->irq_lock);827828if (kvm_vgic_global_state.type == VGIC_V2)829vgic_v2_populate_lr(vcpu, irq, lr);830else831vgic_v3_populate_lr(vcpu, irq, lr);832}833834static inline void vgic_clear_lr(struct kvm_vcpu *vcpu, int lr)835{836if (kvm_vgic_global_state.type == VGIC_V2)837vgic_v2_clear_lr(vcpu, lr);838else839vgic_v3_clear_lr(vcpu, lr);840}841842static void summarize_ap_list(struct kvm_vcpu *vcpu,843struct ap_list_summary *als)844{845struct vgic_cpu *vgic_cpu = &vcpu->arch.vgic_cpu;846struct vgic_irq *irq;847848lockdep_assert_held(&vgic_cpu->ap_list_lock);849850*als = (typeof(*als)){};851852list_for_each_entry(irq, &vgic_cpu->ap_list_head, ap_list) {853guard(raw_spinlock)(&irq->irq_lock);854855if (unlikely(vgic_target_oracle(irq) != vcpu))856continue;857858if (!irq->active)859als->nr_pend++;860else861als->nr_act++;862863if (irq->intid < VGIC_NR_SGIS)864als->nr_sgi++;865}866}867868/*869* Dealing with LR overflow is close to black magic -- dress accordingly.870*871* We have to present an almost infinite number of interrupts through a very872* limited number of registers. Therefore crucial decisions must be made to873* ensure we feed the most relevant interrupts into the LRs, and yet have874* some facilities to let the guest interact with those that are not there.875*876* All considerations below are in the context of interrupts targeting a877* single vcpu with non-idle state (either pending, active, or both),878* colloquially called the ap_list:879*880* - Pending interrupts must have priority over active interrupts. This also881* excludes pending+active interrupts. This ensures that a guest can882* perform priority drops on any number of interrupts, and yet be883* presented the next pending one.884*885* - Deactivation of interrupts outside of the LRs must be tracked by using886* either the EOIcount-driven maintenance interrupt, and sometimes by887* trapping the DIR register.888*889* - For EOImode=0, a non-zero EOIcount means walking the ap_list past the890* point that made it into the LRs, and deactivate interrupts that would891* have made it onto the LRs if we had the space.892*893* - The MI-generation bits must be used to try and force an exit when the894* guest has done enough changes to the LRs that we want to reevaluate the895* situation:896*897* - if the total number of pending interrupts exceeds the number of898* LR, NPIE must be set in order to exit once no pending interrupts899* are present in the LRs, allowing us to populate the next batch.900*901* - if there are active interrupts outside of the LRs, then LRENPIE902* must be set so that we exit on deactivation of one of these, and903* work out which one is to be deactivated. Note that this is not904* enough to deal with EOImode=1, see below.905*906* - if the overall number of interrupts exceeds the number of LRs,907* then UIE must be set to allow refilling of the LRs once the908* majority of them has been processed.909*910* - as usual, MI triggers are only an optimisation, since we cannot911* rely on the MI being delivered in timely manner...912*913* - EOImode=1 creates some additional problems:914*915* - deactivation can happen in any order, and we cannot rely on916* EOImode=0's coupling of priority-drop and deactivation which917* imposes strict reverse Ack order. This means that DIR must918* trap if we have active interrupts outside of the LRs.919*920* - deactivation of SPIs can occur on any CPU, while the SPI is only921* present in the ap_list of the CPU that actually ack-ed it. In that922* case, EOIcount doesn't provide enough information, and we must923* resort to trapping DIR even if we don't overflow the LRs. Bonus924* point for not trapping DIR when no SPIs are pending or active in925* the whole VM.926*927* - LPIs do not suffer the same problem as SPIs on deactivation, as we928* have to essentially discard the active state, see below.929*930* - Virtual LPIs have an active state (surprise!), which gets removed on931* priority drop (EOI). However, EOIcount doesn't get bumped when the LPI932* is not present in the LR (surprise again!). Special care must therefore933* be taken to remove the active state from any activated LPI when exiting934* from the guest. This is in a way no different from what happens on the935* physical side. We still rely on the running priority to have been936* removed from the APRs, irrespective of the LPI being present in the LRs937* or not.938*939* - Virtual SGIs directly injected via GICv4.1 must not affect EOIcount, as940* they are not managed in SW and don't have a true active state. So only941* set vSGIEOICount when no SGIs are in the ap_list.942*943* - GICv2 SGIs with multiple sources are injected one source at a time, as944* if they were made pending sequentially. This may mean that we don't945* always present the HPPI if other interrupts with lower priority are946* pending in the LRs. Big deal.947*/948static void vgic_flush_lr_state(struct kvm_vcpu *vcpu)949{950struct vgic_cpu *vgic_cpu = &vcpu->arch.vgic_cpu;951struct ap_list_summary als;952struct vgic_irq *irq;953int count = 0;954955lockdep_assert_held(&vgic_cpu->ap_list_lock);956957summarize_ap_list(vcpu, &als);958959if (irqs_outside_lrs(&als))960vgic_sort_ap_list(vcpu);961962list_for_each_entry(irq, &vgic_cpu->ap_list_head, ap_list) {963scoped_guard(raw_spinlock, &irq->irq_lock) {964if (likely(vgic_target_oracle(irq) == vcpu)) {965vgic_populate_lr(vcpu, irq, count++);966}967}968969if (count == kvm_vgic_global_state.nr_lr)970break;971}972973/* Nuke remaining LRs */974for (int i = count ; i < kvm_vgic_global_state.nr_lr; i++)975vgic_clear_lr(vcpu, i);976977if (!static_branch_unlikely(&kvm_vgic_global_state.gicv3_cpuif)) {978vcpu->arch.vgic_cpu.vgic_v2.used_lrs = count;979vgic_v2_configure_hcr(vcpu, &als);980} else {981vcpu->arch.vgic_cpu.vgic_v3.used_lrs = count;982vgic_v3_configure_hcr(vcpu, &als);983}984}985986static inline bool can_access_vgic_from_kernel(void)987{988/*989* GICv2 can always be accessed from the kernel because it is990* memory-mapped, and VHE systems can access GICv3 EL2 system991* registers.992*/993return !static_branch_unlikely(&kvm_vgic_global_state.gicv3_cpuif) || has_vhe();994}995996static inline void vgic_save_state(struct kvm_vcpu *vcpu)997{998if (!static_branch_unlikely(&kvm_vgic_global_state.gicv3_cpuif))999vgic_v2_save_state(vcpu);1000else1001__vgic_v3_save_state(&vcpu->arch.vgic_cpu.vgic_v3);1002}10031004/* Sync back the hardware VGIC state into our emulation after a guest's run. */1005void kvm_vgic_sync_hwstate(struct kvm_vcpu *vcpu)1006{1007/* If nesting, emulate the HW effect from L0 to L1 */1008if (vgic_state_is_nested(vcpu)) {1009vgic_v3_sync_nested(vcpu);1010return;1011}10121013if (vcpu_has_nv(vcpu))1014vgic_v3_nested_update_mi(vcpu);10151016if (can_access_vgic_from_kernel())1017vgic_save_state(vcpu);10181019vgic_fold_lr_state(vcpu);1020vgic_prune_ap_list(vcpu);1021}10221023/* Sync interrupts that were deactivated through a DIR trap */1024void kvm_vgic_process_async_update(struct kvm_vcpu *vcpu)1025{1026unsigned long flags;10271028/* Make sure we're in the same context as LR handling */1029local_irq_save(flags);1030vgic_prune_ap_list(vcpu);1031local_irq_restore(flags);1032}10331034static inline void vgic_restore_state(struct kvm_vcpu *vcpu)1035{1036if (!static_branch_unlikely(&kvm_vgic_global_state.gicv3_cpuif))1037vgic_v2_restore_state(vcpu);1038else1039__vgic_v3_restore_state(&vcpu->arch.vgic_cpu.vgic_v3);1040}10411042/* Flush our emulation state into the GIC hardware before entering the guest. */1043void kvm_vgic_flush_hwstate(struct kvm_vcpu *vcpu)1044{1045/*1046* If in a nested state, we must return early. Two possibilities:1047*1048* - If we have any pending IRQ for the guest and the guest1049* expects IRQs to be handled in its virtual EL2 mode (the1050* virtual IMO bit is set) and it is not already running in1051* virtual EL2 mode, then we have to emulate an IRQ1052* exception to virtual EL2.1053*1054* We do that by placing a request to ourselves which will1055* abort the entry procedure and inject the exception at the1056* beginning of the run loop.1057*1058* - Otherwise, do exactly *NOTHING* apart from enabling the virtual1059* CPU interface. The guest state is already loaded, and we can1060* carry on with running it.1061*1062* If we have NV, but are not in a nested state, compute the1063* maintenance interrupt state, as it may fire.1064*/1065if (vgic_state_is_nested(vcpu)) {1066if (kvm_vgic_vcpu_pending_irq(vcpu))1067kvm_make_request(KVM_REQ_GUEST_HYP_IRQ_PENDING, vcpu);10681069vgic_v3_flush_nested(vcpu);1070return;1071}10721073if (vcpu_has_nv(vcpu))1074vgic_v3_nested_update_mi(vcpu);10751076DEBUG_SPINLOCK_BUG_ON(!irqs_disabled());10771078scoped_guard(raw_spinlock, &vcpu->arch.vgic_cpu.ap_list_lock)1079vgic_flush_lr_state(vcpu);10801081if (can_access_vgic_from_kernel())1082vgic_restore_state(vcpu);10831084if (vgic_supports_direct_irqs(vcpu->kvm))1085vgic_v4_commit(vcpu);1086}10871088void kvm_vgic_load(struct kvm_vcpu *vcpu)1089{1090if (unlikely(!irqchip_in_kernel(vcpu->kvm) || !vgic_initialized(vcpu->kvm))) {1091if (has_vhe() && static_branch_unlikely(&kvm_vgic_global_state.gicv3_cpuif))1092__vgic_v3_activate_traps(&vcpu->arch.vgic_cpu.vgic_v3);1093return;1094}10951096if (!static_branch_unlikely(&kvm_vgic_global_state.gicv3_cpuif))1097vgic_v2_load(vcpu);1098else1099vgic_v3_load(vcpu);1100}11011102void kvm_vgic_put(struct kvm_vcpu *vcpu)1103{1104if (unlikely(!irqchip_in_kernel(vcpu->kvm) || !vgic_initialized(vcpu->kvm))) {1105if (has_vhe() && static_branch_unlikely(&kvm_vgic_global_state.gicv3_cpuif))1106__vgic_v3_deactivate_traps(&vcpu->arch.vgic_cpu.vgic_v3);1107return;1108}11091110if (!static_branch_unlikely(&kvm_vgic_global_state.gicv3_cpuif))1111vgic_v2_put(vcpu);1112else1113vgic_v3_put(vcpu);1114}11151116int kvm_vgic_vcpu_pending_irq(struct kvm_vcpu *vcpu)1117{1118struct vgic_cpu *vgic_cpu = &vcpu->arch.vgic_cpu;1119struct vgic_irq *irq;1120bool pending = false;1121unsigned long flags;1122struct vgic_vmcr vmcr;11231124if (!vcpu->kvm->arch.vgic.enabled)1125return false;11261127if (vcpu->arch.vgic_cpu.vgic_v3.its_vpe.pending_last)1128return true;11291130vgic_get_vmcr(vcpu, &vmcr);11311132raw_spin_lock_irqsave(&vgic_cpu->ap_list_lock, flags);11331134list_for_each_entry(irq, &vgic_cpu->ap_list_head, ap_list) {1135raw_spin_lock(&irq->irq_lock);1136pending = irq_is_pending(irq) && irq->enabled &&1137!irq->active &&1138irq->priority < vmcr.pmr;1139raw_spin_unlock(&irq->irq_lock);11401141if (pending)1142break;1143}11441145raw_spin_unlock_irqrestore(&vgic_cpu->ap_list_lock, flags);11461147return pending;1148}11491150void vgic_kick_vcpus(struct kvm *kvm)1151{1152struct kvm_vcpu *vcpu;1153unsigned long c;11541155/*1156* We've injected an interrupt, time to find out who deserves1157* a good kick...1158*/1159kvm_for_each_vcpu(c, vcpu, kvm) {1160if (kvm_vgic_vcpu_pending_irq(vcpu)) {1161kvm_make_request(KVM_REQ_IRQ_PENDING, vcpu);1162kvm_vcpu_kick(vcpu);1163}1164}1165}11661167bool kvm_vgic_map_is_active(struct kvm_vcpu *vcpu, unsigned int vintid)1168{1169struct vgic_irq *irq;1170bool map_is_active;1171unsigned long flags;11721173if (!vgic_initialized(vcpu->kvm))1174return false;11751176irq = vgic_get_vcpu_irq(vcpu, vintid);1177raw_spin_lock_irqsave(&irq->irq_lock, flags);1178map_is_active = irq->hw && irq->active;1179raw_spin_unlock_irqrestore(&irq->irq_lock, flags);1180vgic_put_irq(vcpu->kvm, irq);11811182return map_is_active;1183}11841185/*1186* Level-triggered mapped IRQs are special because we only observe rising1187* edges as input to the VGIC.1188*1189* If the guest never acked the interrupt we have to sample the physical1190* line and set the line level, because the device state could have changed1191* or we simply need to process the still pending interrupt later.1192*1193* We could also have entered the guest with the interrupt active+pending.1194* On the next exit, we need to re-evaluate the pending state, as it could1195* otherwise result in a spurious interrupt by injecting a now potentially1196* stale pending state.1197*1198* If this causes us to lower the level, we have to also clear the physical1199* active state, since we will otherwise never be told when the interrupt1200* becomes asserted again.1201*1202* Another case is when the interrupt requires a helping hand on1203* deactivation (no HW deactivation, for example).1204*/1205void vgic_irq_handle_resampling(struct vgic_irq *irq,1206bool lr_deactivated, bool lr_pending)1207{1208if (vgic_irq_is_mapped_level(irq)) {1209bool resample = false;12101211if (unlikely(vgic_irq_needs_resampling(irq))) {1212resample = !(irq->active || irq->pending_latch);1213} else if (lr_pending || (lr_deactivated && irq->line_level)) {1214irq->line_level = vgic_get_phys_line_level(irq);1215resample = !irq->line_level;1216}12171218if (resample)1219vgic_irq_set_phys_active(irq, false);1220}1221}122212231224