xref: /linux/arch/arm64/kvm/vgic/vgic.c (revision bf9c9ed5204fe8155bfff96a737faaae6afe07d8)
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  * Copyright (C) 2015, 2016 ARM Ltd.
4  */
5 
6 #include <linux/interrupt.h>
7 #include <linux/irq.h>
8 #include <linux/kvm.h>
9 #include <linux/kvm_host.h>
10 #include <linux/list_sort.h>
11 #include <linux/nospec.h>
12 
13 #include <asm/kvm_hyp.h>
14 
15 #include "vgic.h"
16 
17 #define CREATE_TRACE_POINTS
18 #include "trace.h"
19 
20 struct vgic_global kvm_vgic_global_state __ro_after_init = {
21 	.gicv3_cpuif = STATIC_KEY_FALSE_INIT,
22 };
23 
24 /*
25  * Locking order is always:
26  * kvm->lock (mutex)
27  *   vcpu->mutex (mutex)
28  *     kvm->arch.config_lock (mutex)
29  *       its->cmd_lock (mutex)
30  *         its->its_lock (mutex)
31  *           vgic_dist->lpi_xa.xa_lock		must be taken with IRQs disabled
32  *             vgic_cpu->ap_list_lock		must be taken with IRQs disabled
33  *               vgic_irq->irq_lock		must be taken with IRQs disabled
34  *
35  * As the ap_list_lock might be taken from the timer interrupt handler,
36  * we have to disable IRQs before taking this lock and everything lower
37  * than it.
38  *
39  * The config_lock has additional ordering requirements:
40  * kvm->slots_lock
41  *   kvm->srcu
42  *     kvm->arch.config_lock
43  *
44  * If you need to take multiple locks, always take the upper lock first,
45  * then the lower ones, e.g. first take the its_lock, then the irq_lock.
46  * If you are already holding a lock and need to take a higher one, you
47  * have to drop the lower ranking lock first and re-acquire it after having
48  * taken the upper one.
49  *
50  * When taking more than one ap_list_lock at the same time, always take the
51  * lowest numbered VCPU's ap_list_lock first, so:
52  *   vcpuX->vcpu_id < vcpuY->vcpu_id:
53  *     raw_spin_lock(vcpuX->arch.vgic_cpu.ap_list_lock);
54  *     raw_spin_lock(vcpuY->arch.vgic_cpu.ap_list_lock);
55  *
56  * Since the VGIC must support injecting virtual interrupts from ISRs, we have
57  * to use the raw_spin_lock_irqsave/raw_spin_unlock_irqrestore versions of outer
58  * spinlocks for any lock that may be taken while injecting an interrupt.
59  */
60 
61 /*
62  * Index the VM's xarray of mapped LPIs and return a reference to the IRQ
63  * structure. The caller is expected to call vgic_put_irq() later once it's
64  * finished with the IRQ.
65  */
66 static struct vgic_irq *vgic_get_lpi(struct kvm *kvm, u32 intid)
67 {
68 	struct vgic_dist *dist = &kvm->arch.vgic;
69 	struct vgic_irq *irq = NULL;
70 
71 	rcu_read_lock();
72 
73 	irq = xa_load(&dist->lpi_xa, intid);
74 	if (!vgic_try_get_irq_ref(irq))
75 		irq = NULL;
76 
77 	rcu_read_unlock();
78 
79 	return irq;
80 }
81 
82 /*
83  * This looks up the virtual interrupt ID to get the corresponding
84  * struct vgic_irq. It also increases the refcount, so any caller is expected
85  * to call vgic_put_irq() once it's finished with this IRQ.
86  */
87 struct vgic_irq *vgic_get_irq(struct kvm *kvm, u32 intid)
88 {
89 	enum kvm_device_type type = kvm->arch.vgic.vgic_model;
90 
91 	/* SPIs */
92 	if (__irq_is_spi(type, intid)) {
93 		switch (type) {
94 		case KVM_DEV_TYPE_ARM_VGIC_V5:
95 			intid = vgic_v5_get_hwirq_id(intid);
96 
97 			if (intid >= kvm->arch.vgic.nr_spis)
98 				return NULL;
99 
100 			intid = array_index_nospec(intid, kvm->arch.vgic.nr_spis);
101 			return &kvm->arch.vgic.spis[intid];
102 		default: {
103 			u32 max_intid = kvm->arch.vgic.nr_spis + VGIC_NR_PRIVATE_IRQS;
104 
105 			if (intid < max_intid) {
106 				intid -= VGIC_NR_PRIVATE_IRQS;
107 				intid = array_index_nospec(intid, kvm->arch.vgic.nr_spis);
108 				return &kvm->arch.vgic.spis[intid];
109 			}
110 		}}
111 	}
112 
113 	/* LPIs */
114 	if (__irq_is_lpi(type, intid))
115 		return vgic_get_lpi(kvm, intid);
116 
117 	return NULL;
118 }
119 
120 struct vgic_irq *vgic_get_vcpu_irq(struct kvm_vcpu *vcpu, u32 intid)
121 {
122 	enum kvm_device_type type;
123 
124 	if (WARN_ON(!vcpu))
125 		return NULL;
126 
127 	type = vcpu->kvm->arch.vgic.vgic_model;
128 
129 	if (__irq_is_sgi(type, intid) || __irq_is_ppi(type, intid)) {
130 		switch (type) {
131 		case KVM_DEV_TYPE_ARM_VGIC_V5:
132 			intid = vgic_v5_get_hwirq_id(intid);
133 			if (intid >= VGIC_V5_NR_PRIVATE_IRQS)
134 				return NULL;
135 			intid = array_index_nospec(intid, VGIC_V5_NR_PRIVATE_IRQS);
136 			break;
137 		default:
138 			intid = array_index_nospec(intid, VGIC_NR_PRIVATE_IRQS);
139 		}
140 
141 		return &vcpu->arch.vgic_cpu.private_irqs[intid];
142 	}
143 
144 	return vgic_get_irq(vcpu->kvm, intid);
145 }
146 
147 static void vgic_release_lpi_locked(struct vgic_dist *dist, struct vgic_irq *irq)
148 {
149 	lockdep_assert_held(&dist->lpi_xa.xa_lock);
150 	__xa_erase(&dist->lpi_xa, irq->intid);
151 	kfree_rcu(irq, rcu);
152 }
153 
154 static __must_check bool __vgic_put_irq(struct kvm *kvm, struct vgic_irq *irq)
155 {
156 	if (!irq_is_lpi(kvm, irq->intid))
157 		return false;
158 
159 	return refcount_dec_and_test(&irq->refcount);
160 }
161 
162 static __must_check bool vgic_put_irq_norelease(struct kvm *kvm, struct vgic_irq *irq)
163 {
164 	return __vgic_put_irq(kvm, irq);
165 }
166 
167 void vgic_put_irq(struct kvm *kvm, struct vgic_irq *irq)
168 {
169 	struct vgic_dist *dist = &kvm->arch.vgic;
170 	unsigned long flags;
171 
172 	/*
173 	 * Normally the lock is only taken when the refcount drops to 0.
174 	 * Acquire/release it early on lockdep kernels to make locking issues
175 	 * in rare release paths a bit more obvious.
176 	 */
177 	if (IS_ENABLED(CONFIG_LOCKDEP) && irq_is_lpi(kvm, irq->intid)) {
178 		guard(spinlock_irqsave)(&dist->lpi_xa.xa_lock);
179 	}
180 
181 	if (!irq_is_lpi(kvm, irq->intid))
182 		return;
183 
184 	if (refcount_dec_and_lock_irqsave(&irq->refcount,
185 					  &dist->lpi_xa.xa_lock, &flags)) {
186 		vgic_release_lpi_locked(dist, irq);
187 		xa_unlock_irqrestore(&dist->lpi_xa, flags);
188 	}
189 }
190 
191 static void vgic_release_deleted_lpis(struct kvm *kvm)
192 {
193 	struct vgic_dist *dist = &kvm->arch.vgic;
194 	unsigned long flags, intid;
195 	struct vgic_irq *irq;
196 
197 	xa_lock_irqsave(&dist->lpi_xa, flags);
198 
199 	xa_for_each(&dist->lpi_xa, intid, irq) {
200 		if (!refcount_read(&irq->refcount))
201 			vgic_release_lpi_locked(dist, irq);
202 	}
203 
204 	xa_unlock_irqrestore(&dist->lpi_xa, flags);
205 }
206 
207 void vgic_flush_pending_lpis(struct kvm_vcpu *vcpu)
208 {
209 	struct vgic_cpu *vgic_cpu = &vcpu->arch.vgic_cpu;
210 	struct vgic_irq *irq, *tmp;
211 	bool deleted = false;
212 	unsigned long flags;
213 
214 	raw_spin_lock_irqsave(&vgic_cpu->ap_list_lock, flags);
215 
216 	list_for_each_entry_safe(irq, tmp, &vgic_cpu->ap_list_head, ap_list) {
217 		if (irq_is_lpi(vcpu->kvm, irq->intid)) {
218 			raw_spin_lock(&irq->irq_lock);
219 			irq->pending_latch = false;
220 			list_del(&irq->ap_list);
221 			irq->vcpu = NULL;
222 			raw_spin_unlock(&irq->irq_lock);
223 			deleted |= vgic_put_irq_norelease(vcpu->kvm, irq);
224 		}
225 	}
226 
227 	raw_spin_unlock_irqrestore(&vgic_cpu->ap_list_lock, flags);
228 
229 	if (deleted)
230 		vgic_release_deleted_lpis(vcpu->kvm);
231 }
232 
233 void vgic_irq_set_phys_pending(struct vgic_irq *irq, bool pending)
234 {
235 	WARN_ON(irq_set_irqchip_state(irq->host_irq,
236 				      IRQCHIP_STATE_PENDING,
237 				      pending));
238 }
239 
240 bool vgic_get_phys_line_level(struct vgic_irq *irq)
241 {
242 	bool line_level;
243 
244 	BUG_ON(!irq->hw);
245 
246 	if (irq->ops && irq->ops->get_input_level)
247 		return irq->ops->get_input_level(irq->intid);
248 
249 	WARN_ON(irq_get_irqchip_state(irq->host_irq,
250 				      IRQCHIP_STATE_PENDING,
251 				      &line_level));
252 	return line_level;
253 }
254 
255 /* Set/Clear the physical active state */
256 void vgic_irq_set_phys_active(struct vgic_irq *irq, bool active)
257 {
258 
259 	BUG_ON(!irq->hw);
260 	WARN_ON(irq_set_irqchip_state(irq->host_irq,
261 				      IRQCHIP_STATE_ACTIVE,
262 				      active));
263 }
264 
265 /**
266  * vgic_target_oracle - compute the target vcpu for an irq
267  *
268  * @irq:	The irq to route. Must be already locked.
269  *
270  * Based on the current state of the interrupt (enabled, pending,
271  * active, vcpu and target_vcpu), compute the next vcpu this should be
272  * given to. Return NULL if this shouldn't be injected at all.
273  *
274  * Requires the IRQ lock to be held.
275  */
276 struct kvm_vcpu *vgic_target_oracle(struct vgic_irq *irq)
277 {
278 	lockdep_assert_held(&irq->irq_lock);
279 
280 	/* If the interrupt is active, it must stay on the current vcpu */
281 	if (irq->active)
282 		return irq->vcpu ? : irq->target_vcpu;
283 
284 	/*
285 	 * If the IRQ is not active but enabled and pending, we should direct
286 	 * it to its configured target VCPU.
287 	 * If the distributor is disabled, pending interrupts shouldn't be
288 	 * forwarded, nor should LPIs whose redistributor has them disabled.
289 	 */
290 	if (irq->enabled && irq_is_pending(irq)) {
291 		struct kvm_vcpu *vcpu = irq->target_vcpu;
292 
293 		if (unlikely(vcpu && !vcpu->kvm->arch.vgic.enabled))
294 			return NULL;
295 
296 		if (unlikely(vcpu && irq_is_lpi(vcpu->kvm, irq->intid) && !vgic_lpis_enabled(vcpu)))
297 			return NULL;
298 
299 		return vcpu;
300 	}
301 
302 	/* If neither active nor pending and enabled, then this IRQ should not
303 	 * be queued to any VCPU.
304 	 */
305 	return NULL;
306 }
307 
308 struct vgic_sort_info {
309 	struct kvm_vcpu *vcpu;
310 	struct vgic_vmcr vmcr;
311 };
312 
313 /*
314  * The order of items in the ap_lists defines how we'll pack things in LRs as
315  * well, the first items in the list being the first things populated in the
316  * LRs.
317  *
318  * Pending, non-active interrupts must be placed at the head of the list.
319  * Otherwise things should be sorted by the priority field and the GIC
320  * hardware support will take care of preemption of priority groups etc.
321  * Interrupts that are not deliverable should be at the end of the list.
322  *
323  * Return negative if "a" sorts before "b", 0 to preserve order, and positive
324  * to sort "b" before "a".
325  */
326 static int vgic_irq_cmp(void *priv, const struct list_head *a,
327 			const struct list_head *b)
328 {
329 	struct vgic_irq *irqa = container_of(a, struct vgic_irq, ap_list);
330 	struct vgic_irq *irqb = container_of(b, struct vgic_irq, ap_list);
331 	struct vgic_sort_info *info = priv;
332 	struct kvm_vcpu *vcpu = info->vcpu;
333 	bool penda, pendb;
334 	int ret;
335 
336 	/*
337 	 * list_sort may call this function with the same element when
338 	 * the list is fairly long.
339 	 */
340 	if (unlikely(irqa == irqb))
341 		return 0;
342 
343 	raw_spin_lock(&irqa->irq_lock);
344 	raw_spin_lock_nested(&irqb->irq_lock, SINGLE_DEPTH_NESTING);
345 
346 	/* Undeliverable interrupts should be last */
347 	ret = (int)(vgic_target_oracle(irqb) == vcpu) - (int)(vgic_target_oracle(irqa) == vcpu);
348 	if (ret)
349 		goto out;
350 
351 	/* Same thing for interrupts targeting a disabled group */
352 	ret =  (int)(irqb->group ? info->vmcr.grpen1 : info->vmcr.grpen0);
353 	ret -= (int)(irqa->group ? info->vmcr.grpen1 : info->vmcr.grpen0);
354 	if (ret)
355 		goto out;
356 
357 	penda = irqa->enabled && irq_is_pending(irqa) && !irqa->active;
358 	pendb = irqb->enabled && irq_is_pending(irqb) && !irqb->active;
359 
360 	ret = (int)pendb - (int)penda;
361 	if (ret)
362 		goto out;
363 
364 	/* Both pending and enabled, sort by priority (lower number first) */
365 	ret = (int)irqa->priority - (int)irqb->priority;
366 	if (ret)
367 		goto out;
368 
369 	/* Finally, HW bit active interrupts have priority over non-HW ones */
370 	ret = (int)irqb->hw - (int)irqa->hw;
371 
372 out:
373 	raw_spin_unlock(&irqb->irq_lock);
374 	raw_spin_unlock(&irqa->irq_lock);
375 	return ret;
376 }
377 
378 /* Must be called with the ap_list_lock held */
379 static void vgic_sort_ap_list(struct kvm_vcpu *vcpu)
380 {
381 	struct vgic_cpu *vgic_cpu = &vcpu->arch.vgic_cpu;
382 	struct vgic_sort_info info = { .vcpu = vcpu, };
383 
384 	lockdep_assert_held(&vgic_cpu->ap_list_lock);
385 
386 	vgic_get_vmcr(vcpu, &info.vmcr);
387 	list_sort(&info, &vgic_cpu->ap_list_head, vgic_irq_cmp);
388 }
389 
390 /*
391  * Only valid injection if changing level for level-triggered IRQs or for a
392  * rising edge, and in-kernel connected IRQ lines can only be controlled by
393  * their owner.
394  */
395 static bool vgic_validate_injection(struct vgic_irq *irq, bool level, void *owner)
396 {
397 	if (irq->owner != owner)
398 		return false;
399 
400 	switch (irq->config) {
401 	case VGIC_CONFIG_LEVEL:
402 		return irq->line_level != level;
403 	case VGIC_CONFIG_EDGE:
404 		return level;
405 	}
406 
407 	return false;
408 }
409 
410 static bool vgic_model_needs_bcst_kick(struct kvm *kvm)
411 {
412 	/*
413 	 * A GICv3 (or GICv3-like) system exposing a GICv3 to the guest
414 	 * needs a broadcast kick to set TDIR globally.
415 	 *
416 	 * For systems that do not have TDIR (ARM's own v8.0 CPUs), the
417 	 * shadow TDIR bit is always set, and so is the register's TC bit,
418 	 * so no need to kick the CPUs.
419 	 */
420 	return (cpus_have_final_cap(ARM64_HAS_ICH_HCR_EL2_TDIR) &&
421 		kvm->arch.vgic.vgic_model == KVM_DEV_TYPE_ARM_VGIC_V3);
422 }
423 
424 /*
425  * Check whether an IRQ needs to (and can) be queued to a VCPU's ap list.
426  * Do the queuing if necessary, taking the right locks in the right order.
427  * Returns true when the IRQ was queued, false otherwise.
428  *
429  * Needs to be entered with the IRQ lock already held, but will return
430  * with all locks dropped.
431  */
432 bool vgic_queue_irq_unlock(struct kvm *kvm, struct vgic_irq *irq,
433 			   unsigned long flags) __releases(&irq->irq_lock)
434 {
435 	struct kvm_vcpu *vcpu;
436 	bool bcast;
437 
438 	lockdep_assert_held(&irq->irq_lock);
439 
440 	if (irq->ops && irq->ops->queue_irq_unlock)
441 		return irq->ops->queue_irq_unlock(kvm, irq, flags);
442 
443 retry:
444 	vcpu = vgic_target_oracle(irq);
445 	if (irq->vcpu || !vcpu) {
446 		/*
447 		 * If this IRQ is already on a VCPU's ap_list, then it
448 		 * cannot be moved or modified and there is no more work for
449 		 * us to do.
450 		 *
451 		 * Otherwise, if the irq is not pending and enabled, it does
452 		 * not need to be inserted into an ap_list and there is also
453 		 * no more work for us to do.
454 		 */
455 		raw_spin_unlock_irqrestore(&irq->irq_lock, flags);
456 
457 		/*
458 		 * We have to kick the VCPU here, because we could be
459 		 * queueing an edge-triggered interrupt for which we
460 		 * get no EOI maintenance interrupt. In that case,
461 		 * while the IRQ is already on the VCPU's AP list, the
462 		 * VCPU could have EOI'ed the original interrupt and
463 		 * won't see this one until it exits for some other
464 		 * reason.
465 		 */
466 		if (vcpu) {
467 			kvm_make_request(KVM_REQ_IRQ_PENDING, vcpu);
468 			kvm_vcpu_kick(vcpu);
469 		}
470 		return false;
471 	}
472 
473 	/*
474 	 * We must unlock the irq lock to take the ap_list_lock where
475 	 * we are going to insert this new pending interrupt.
476 	 */
477 	raw_spin_unlock_irqrestore(&irq->irq_lock, flags);
478 
479 	/* someone can do stuff here, which we re-check below */
480 
481 	raw_spin_lock_irqsave(&vcpu->arch.vgic_cpu.ap_list_lock, flags);
482 	raw_spin_lock(&irq->irq_lock);
483 
484 	/*
485 	 * Did something change behind our backs?
486 	 *
487 	 * There are two cases:
488 	 * 1) The irq lost its pending state or was disabled behind our
489 	 *    backs and/or it was queued to another VCPU's ap_list.
490 	 * 2) Someone changed the affinity on this irq behind our
491 	 *    backs and we are now holding the wrong ap_list_lock.
492 	 *
493 	 * In both cases, drop the locks and retry.
494 	 */
495 
496 	if (unlikely(irq->vcpu || vcpu != vgic_target_oracle(irq))) {
497 		raw_spin_unlock(&irq->irq_lock);
498 		raw_spin_unlock_irqrestore(&vcpu->arch.vgic_cpu.ap_list_lock,
499 					   flags);
500 
501 		raw_spin_lock_irqsave(&irq->irq_lock, flags);
502 		goto retry;
503 	}
504 
505 	/*
506 	 * Grab a reference to the irq to reflect the fact that it is
507 	 * now in the ap_list. This is safe as the caller must already hold a
508 	 * reference on the irq.
509 	 */
510 	vgic_get_irq_ref(irq);
511 	list_add_tail(&irq->ap_list, &vcpu->arch.vgic_cpu.ap_list_head);
512 	irq->vcpu = vcpu;
513 
514 	/* A new SPI may result in deactivation trapping on all vcpus */
515 	bcast = (vgic_model_needs_bcst_kick(vcpu->kvm) &&
516 		 vgic_valid_spi(vcpu->kvm, irq->intid) &&
517 		 atomic_fetch_inc(&vcpu->kvm->arch.vgic.active_spis) == 0);
518 
519 	raw_spin_unlock(&irq->irq_lock);
520 	raw_spin_unlock_irqrestore(&vcpu->arch.vgic_cpu.ap_list_lock, flags);
521 
522 	if (!bcast) {
523 		kvm_make_request(KVM_REQ_IRQ_PENDING, vcpu);
524 		kvm_vcpu_kick(vcpu);
525 	} else {
526 		kvm_make_all_cpus_request(vcpu->kvm, KVM_REQ_IRQ_PENDING);
527 	}
528 
529 	return true;
530 }
531 
532 /**
533  * kvm_vgic_inject_irq - Inject an IRQ from a device to the vgic
534  * @kvm:     The VM structure pointer
535  * @vcpu:    The CPU for PPIs or NULL for global interrupts
536  * @intid:   The INTID to inject a new state to.
537  * @level:   Edge-triggered:  true:  to trigger the interrupt
538  *			      false: to ignore the call
539  *	     Level-sensitive  true:  raise the input signal
540  *			      false: lower the input signal
541  * @owner:   The opaque pointer to the owner of the IRQ being raised to verify
542  *           that the caller is allowed to inject this IRQ.  Userspace
543  *           injections will have owner == NULL.
544  *
545  * The VGIC is not concerned with devices being active-LOW or active-HIGH for
546  * level-sensitive interrupts.  You can think of the level parameter as 1
547  * being HIGH and 0 being LOW and all devices being active-HIGH.
548  */
549 int kvm_vgic_inject_irq(struct kvm *kvm, struct kvm_vcpu *vcpu,
550 			unsigned int intid, bool level, void *owner)
551 {
552 	struct vgic_irq *irq;
553 	unsigned long flags;
554 
555 	if (unlikely(!vgic_initialized(kvm)))
556 		return 0;
557 
558 	if (!vcpu && irq_is_private(kvm, intid))
559 		return -EINVAL;
560 
561 	trace_vgic_update_irq_pending(vcpu ? vcpu->vcpu_idx : 0, intid, level);
562 
563 	if (irq_is_private(kvm, intid))
564 		irq = vgic_get_vcpu_irq(vcpu, intid);
565 	else
566 		irq = vgic_get_irq(kvm, intid);
567 	if (!irq)
568 		return -EINVAL;
569 
570 	raw_spin_lock_irqsave(&irq->irq_lock, flags);
571 
572 	if (!vgic_validate_injection(irq, level, owner)) {
573 		/* Nothing to see here, move along... */
574 		raw_spin_unlock_irqrestore(&irq->irq_lock, flags);
575 		vgic_put_irq(kvm, irq);
576 		return 0;
577 	}
578 
579 	if (irq->config == VGIC_CONFIG_LEVEL)
580 		irq->line_level = level;
581 	else
582 		irq->pending_latch = true;
583 
584 	if (irq->ops && irq->ops->set_pending_state)
585 		WARN_ON_ONCE(!irq->ops->set_pending_state(vcpu, irq));
586 
587 	vgic_queue_irq_unlock(kvm, irq, flags);
588 	vgic_put_irq(kvm, irq);
589 
590 	return 0;
591 }
592 
593 void kvm_vgic_set_irq_ops(struct kvm_vcpu *vcpu, u32 vintid,
594 			  const struct irq_ops *ops)
595 {
596 	struct vgic_irq *irq = vgic_get_vcpu_irq(vcpu, vintid);
597 
598 	BUG_ON(!irq);
599 
600 	scoped_guard(raw_spinlock_irqsave, &irq->irq_lock)
601 		irq->ops = ops;
602 
603 	vgic_put_irq(vcpu->kvm, irq);
604 }
605 
606 void kvm_vgic_clear_irq_ops(struct kvm_vcpu *vcpu, u32 vintid)
607 {
608 	kvm_vgic_set_irq_ops(vcpu, vintid, NULL);
609 }
610 
611 /* @irq->irq_lock must be held */
612 static int kvm_vgic_map_irq(struct kvm_vcpu *vcpu, struct vgic_irq *irq,
613 			    unsigned int host_irq)
614 {
615 	struct irq_desc *desc;
616 	struct irq_data *data;
617 
618 	/*
619 	 * Find the physical IRQ number corresponding to @host_irq
620 	 */
621 	desc = irq_to_desc(host_irq);
622 	if (!desc) {
623 		kvm_err("%s: no interrupt descriptor\n", __func__);
624 		return -EINVAL;
625 	}
626 	data = irq_desc_get_irq_data(desc);
627 	while (data->parent_data)
628 		data = data->parent_data;
629 
630 	irq->hw = true;
631 	irq->host_irq = host_irq;
632 	irq->hwintid = data->hwirq;
633 
634 	if (irq->ops && irq->ops->set_direct_injection)
635 		irq->ops->set_direct_injection(vcpu, irq, true);
636 
637 	return 0;
638 }
639 
640 /* @irq->irq_lock must be held */
641 static inline void kvm_vgic_unmap_irq(struct vgic_irq *irq)
642 {
643 	if (irq->ops && irq->ops->set_direct_injection)
644 		irq->ops->set_direct_injection(irq->target_vcpu, irq, false);
645 
646 	irq->hw = false;
647 	irq->hwintid = 0;
648 }
649 
650 int kvm_vgic_map_phys_irq(struct kvm_vcpu *vcpu, unsigned int host_irq,
651 			  u32 vintid)
652 {
653 	struct vgic_irq *irq = vgic_get_vcpu_irq(vcpu, vintid);
654 	unsigned long flags;
655 	int ret;
656 
657 	BUG_ON(!irq);
658 
659 	raw_spin_lock_irqsave(&irq->irq_lock, flags);
660 	ret = kvm_vgic_map_irq(vcpu, irq, host_irq);
661 	raw_spin_unlock_irqrestore(&irq->irq_lock, flags);
662 	vgic_put_irq(vcpu->kvm, irq);
663 
664 	return ret;
665 }
666 
667 /**
668  * kvm_vgic_reset_mapped_irq - Reset a mapped IRQ
669  * @vcpu: The VCPU pointer
670  * @vintid: The INTID of the interrupt
671  *
672  * Reset the active and pending states of a mapped interrupt.  Kernel
673  * subsystems injecting mapped interrupts should reset their interrupt lines
674  * when we are doing a reset of the VM.
675  */
676 void kvm_vgic_reset_mapped_irq(struct kvm_vcpu *vcpu, u32 vintid)
677 {
678 	struct vgic_irq *irq = vgic_get_vcpu_irq(vcpu, vintid);
679 	unsigned long flags;
680 
681 	if (!irq->hw)
682 		goto out;
683 
684 	raw_spin_lock_irqsave(&irq->irq_lock, flags);
685 	irq->active = false;
686 	irq->pending_latch = false;
687 	irq->line_level = false;
688 	raw_spin_unlock_irqrestore(&irq->irq_lock, flags);
689 out:
690 	vgic_put_irq(vcpu->kvm, irq);
691 }
692 
693 int kvm_vgic_unmap_phys_irq(struct kvm_vcpu *vcpu, unsigned int vintid)
694 {
695 	struct vgic_irq *irq;
696 	unsigned long flags;
697 
698 	if (!vgic_initialized(vcpu->kvm))
699 		return -EAGAIN;
700 
701 	irq = vgic_get_vcpu_irq(vcpu, vintid);
702 	BUG_ON(!irq);
703 
704 	raw_spin_lock_irqsave(&irq->irq_lock, flags);
705 	kvm_vgic_unmap_irq(irq);
706 	raw_spin_unlock_irqrestore(&irq->irq_lock, flags);
707 	vgic_put_irq(vcpu->kvm, irq);
708 
709 	return 0;
710 }
711 
712 int kvm_vgic_get_map(struct kvm_vcpu *vcpu, unsigned int vintid)
713 {
714 	struct vgic_irq *irq = vgic_get_vcpu_irq(vcpu, vintid);
715 	unsigned long flags;
716 	int ret = -1;
717 
718 	raw_spin_lock_irqsave(&irq->irq_lock, flags);
719 	if (irq->hw)
720 		ret = irq->hwintid;
721 	raw_spin_unlock_irqrestore(&irq->irq_lock, flags);
722 
723 	vgic_put_irq(vcpu->kvm, irq);
724 	return ret;
725 }
726 
727 /**
728  * kvm_vgic_set_owner - Set the owner of an interrupt for a VM
729  *
730  * @vcpu:   Pointer to the VCPU (used for PPIs)
731  * @intid:  The virtual INTID identifying the interrupt (PPI or SPI)
732  * @owner:  Opaque pointer to the owner
733  *
734  * Returns 0 if intid is not already used by another in-kernel device and the
735  * owner is set, otherwise returns an error code.
736  */
737 int kvm_vgic_set_owner(struct kvm_vcpu *vcpu, unsigned int intid, void *owner)
738 {
739 	struct vgic_irq *irq;
740 	unsigned long flags;
741 	int ret = 0;
742 
743 	if (!vgic_initialized(vcpu->kvm))
744 		return -EAGAIN;
745 
746 	/* SGIs and LPIs cannot be wired up to any device */
747 	if (!irq_is_ppi(vcpu->kvm, intid) && !vgic_valid_spi(vcpu->kvm, intid))
748 		return -EINVAL;
749 
750 	irq = vgic_get_vcpu_irq(vcpu, intid);
751 	raw_spin_lock_irqsave(&irq->irq_lock, flags);
752 	if (irq->owner && irq->owner != owner)
753 		ret = -EEXIST;
754 	else
755 		irq->owner = owner;
756 	raw_spin_unlock_irqrestore(&irq->irq_lock, flags);
757 
758 	return ret;
759 }
760 
761 /**
762  * vgic_prune_ap_list - Remove non-relevant interrupts from the list
763  *
764  * @vcpu: The VCPU pointer
765  *
766  * Go over the list of "interesting" interrupts, and prune those that we
767  * won't have to consider in the near future.
768  */
769 static void vgic_prune_ap_list(struct kvm_vcpu *vcpu)
770 {
771 	struct vgic_cpu *vgic_cpu = &vcpu->arch.vgic_cpu;
772 	struct vgic_irq *irq, *tmp;
773 	bool deleted_lpis = false;
774 
775 	DEBUG_SPINLOCK_BUG_ON(!irqs_disabled());
776 
777 retry:
778 	raw_spin_lock(&vgic_cpu->ap_list_lock);
779 
780 	list_for_each_entry_safe(irq, tmp, &vgic_cpu->ap_list_head, ap_list) {
781 		struct kvm_vcpu *target_vcpu, *vcpuA, *vcpuB;
782 		bool target_vcpu_needs_kick = false;
783 
784 		raw_spin_lock(&irq->irq_lock);
785 
786 		BUG_ON(vcpu != irq->vcpu);
787 
788 		target_vcpu = vgic_target_oracle(irq);
789 
790 		if (!target_vcpu) {
791 			/*
792 			 * We don't need to process this interrupt any
793 			 * further, move it off the list.
794 			 */
795 			list_del(&irq->ap_list);
796 			irq->vcpu = NULL;
797 			raw_spin_unlock(&irq->irq_lock);
798 
799 			/*
800 			 * This vgic_put_irq call matches the
801 			 * vgic_get_irq_ref in vgic_queue_irq_unlock,
802 			 * where we added the LPI to the ap_list. As
803 			 * we remove the irq from the list, we drop
804 			 * also drop the refcount.
805 			 */
806 			deleted_lpis |= vgic_put_irq_norelease(vcpu->kvm, irq);
807 			continue;
808 		}
809 
810 		if (target_vcpu == vcpu) {
811 			/* We're on the right CPU */
812 			raw_spin_unlock(&irq->irq_lock);
813 			continue;
814 		}
815 
816 		/*
817 		 * This interrupt looks like it has to be migrated,
818 		 * make sure it is kept alive while locks are dropped.
819 		 */
820 		vgic_get_irq_ref(irq);
821 
822 		raw_spin_unlock(&irq->irq_lock);
823 		raw_spin_unlock(&vgic_cpu->ap_list_lock);
824 
825 		/*
826 		 * Ensure locking order by always locking the smallest
827 		 * ID first.
828 		 */
829 		if (vcpu->vcpu_id < target_vcpu->vcpu_id) {
830 			vcpuA = vcpu;
831 			vcpuB = target_vcpu;
832 		} else {
833 			vcpuA = target_vcpu;
834 			vcpuB = vcpu;
835 		}
836 
837 		raw_spin_lock(&vcpuA->arch.vgic_cpu.ap_list_lock);
838 		raw_spin_lock_nested(&vcpuB->arch.vgic_cpu.ap_list_lock,
839 				      SINGLE_DEPTH_NESTING);
840 		raw_spin_lock(&irq->irq_lock);
841 
842 		/*
843 		 * If the interrupt is still ours and its affinity has
844 		 * been preserved, move it around. Otherwise, it means
845 		 * things have changed while the interrupt was unlocked
846 		 * (it may even have been taken off the list with its
847 		 * affinity left untouched), and we need to replay this.
848 		 *
849 		 * In all cases, we cannot trust the list not to have
850 		 * changed, so we restart from the beginning.
851 		 */
852 		if (irq->vcpu == vcpu && target_vcpu == vgic_target_oracle(irq)) {
853 			struct vgic_cpu *new_cpu = &target_vcpu->arch.vgic_cpu;
854 
855 			list_del(&irq->ap_list);
856 			irq->vcpu = target_vcpu;
857 			list_add_tail(&irq->ap_list, &new_cpu->ap_list_head);
858 			target_vcpu_needs_kick = true;
859 		}
860 
861 		raw_spin_unlock(&irq->irq_lock);
862 		raw_spin_unlock(&vcpuB->arch.vgic_cpu.ap_list_lock);
863 		raw_spin_unlock(&vcpuA->arch.vgic_cpu.ap_list_lock);
864 
865 		deleted_lpis |= vgic_put_irq_norelease(vcpu->kvm, irq);
866 
867 		if (target_vcpu_needs_kick) {
868 			kvm_make_request(KVM_REQ_IRQ_PENDING, target_vcpu);
869 			kvm_vcpu_kick(target_vcpu);
870 		}
871 
872 		goto retry;
873 	}
874 
875 	/*
876 	 * Fix the last_lr_irq refcount which was obtained while
877 	 * populating the LRs. This can also result in the LPI being
878 	 * deleted.
879 	 */
880 	irq = *host_data_ptr(last_lr_irq);
881 	if (irq) {
882 		deleted_lpis |= vgic_put_irq_norelease(vcpu->kvm, irq);
883 		*host_data_ptr(last_lr_irq) = NULL;
884 	}
885 
886 	raw_spin_unlock(&vgic_cpu->ap_list_lock);
887 
888 	if (unlikely(deleted_lpis))
889 		vgic_release_deleted_lpis(vcpu->kvm);
890 }
891 
892 static void vgic_fold_state(struct kvm_vcpu *vcpu)
893 {
894 	if (vgic_is_v5(vcpu->kvm)) {
895 		vgic_v5_fold_ppi_state(vcpu);
896 		return;
897 	}
898 
899 	if (kvm_vgic_global_state.type == VGIC_V2)
900 		vgic_v2_fold_lr_state(vcpu);
901 	else
902 		vgic_v3_fold_lr_state(vcpu);
903 }
904 
905 /* Requires the irq_lock to be held. */
906 static inline void vgic_populate_lr(struct kvm_vcpu *vcpu,
907 				    struct vgic_irq *irq, int lr)
908 {
909 	lockdep_assert_held(&irq->irq_lock);
910 
911 	if (kvm_vgic_global_state.type == VGIC_V2)
912 		vgic_v2_populate_lr(vcpu, irq, lr);
913 	else
914 		vgic_v3_populate_lr(vcpu, irq, lr);
915 }
916 
917 static inline void vgic_clear_lr(struct kvm_vcpu *vcpu, int lr)
918 {
919 	if (kvm_vgic_global_state.type == VGIC_V2)
920 		vgic_v2_clear_lr(vcpu, lr);
921 	else
922 		vgic_v3_clear_lr(vcpu, lr);
923 }
924 
925 static void summarize_ap_list(struct kvm_vcpu *vcpu,
926 			      struct ap_list_summary *als)
927 {
928 	struct vgic_cpu *vgic_cpu = &vcpu->arch.vgic_cpu;
929 	struct vgic_irq *irq;
930 
931 	lockdep_assert_held(&vgic_cpu->ap_list_lock);
932 
933 	*als = (typeof(*als)){};
934 
935 	list_for_each_entry(irq, &vgic_cpu->ap_list_head, ap_list) {
936 		guard(raw_spinlock)(&irq->irq_lock);
937 
938 		if (unlikely(vgic_target_oracle(irq) != vcpu))
939 			continue;
940 
941 		if (!irq->active)
942 			als->nr_pend++;
943 		else
944 			als->nr_act++;
945 
946 		if (irq->intid < VGIC_NR_SGIS)
947 			als->nr_sgi++;
948 	}
949 }
950 
951 /*
952  * Dealing with LR overflow is close to black magic -- dress accordingly.
953  *
954  * We have to present an almost infinite number of interrupts through a very
955  * limited number of registers. Therefore crucial decisions must be made to
956  * ensure we feed the most relevant interrupts into the LRs, and yet have
957  * some facilities to let the guest interact with those that are not there.
958  *
959  * All considerations below are in the context of interrupts targeting a
960  * single vcpu with non-idle state (either pending, active, or both),
961  * colloquially called the ap_list:
962  *
963  * - Pending interrupts must have priority over active interrupts. This also
964  *   excludes pending+active interrupts. This ensures that a guest can
965  *   perform priority drops on any number of interrupts, and yet be
966  *   presented the next pending one.
967  *
968  * - Deactivation of interrupts outside of the LRs must be tracked by using
969  *   either the EOIcount-driven maintenance interrupt, and sometimes by
970  *   trapping the DIR register.
971  *
972  * - For EOImode=0, a non-zero EOIcount means walking the ap_list past the
973  *   point that made it into the LRs, and deactivate interrupts that would
974  *   have made it onto the LRs if we had the space.
975  *
976  * - The MI-generation bits must be used to try and force an exit when the
977  *   guest has done enough changes to the LRs that we want to reevaluate the
978  *   situation:
979  *
980  *	- if the total number of pending interrupts exceeds the number of
981  *	  LR, NPIE must be set in order to exit once no pending interrupts
982  *	  are present in the LRs, allowing us to populate the next batch.
983  *
984  *	- if there are active interrupts outside of the LRs, then LRENPIE
985  *	  must be set so that we exit on deactivation of one of these, and
986  *	  work out which one is to be deactivated.  Note that this is not
987  *	  enough to deal with EOImode=1, see below.
988  *
989  *	- if the overall number of interrupts exceeds the number of LRs,
990  *	  then UIE must be set to allow refilling of the LRs once the
991  *	  majority of them has been processed.
992  *
993  *	- as usual, MI triggers are only an optimisation, since we cannot
994  *        rely on the MI being delivered in timely manner...
995  *
996  * - EOImode=1 creates some additional problems:
997  *
998  *      - deactivation can happen in any order, and we cannot rely on
999  *	  EOImode=0's coupling of priority-drop and deactivation which
1000  *	  imposes strict reverse Ack order. This means that DIR must
1001  *	  trap if we have active interrupts outside of the LRs.
1002  *
1003  *      - deactivation of SPIs can occur on any CPU, while the SPI is only
1004  *	  present in the ap_list of the CPU that actually ack-ed it. In that
1005  *	  case, EOIcount doesn't provide enough information, and we must
1006  *	  resort to trapping DIR even if we don't overflow the LRs. Bonus
1007  *	  point for not trapping DIR when no SPIs are pending or active in
1008  *	  the whole VM.
1009  *
1010  *	- LPIs do not suffer the same problem as SPIs on deactivation, as we
1011  *	  have to essentially discard the active state, see below.
1012  *
1013  * - Virtual LPIs have an active state (surprise!), which gets removed on
1014  *   priority drop (EOI). However, EOIcount doesn't get bumped when the LPI
1015  *   is not present in the LR (surprise again!). Special care must therefore
1016  *   be taken to remove the active state from any activated LPI when exiting
1017  *   from the guest. This is in a way no different from what happens on the
1018  *   physical side. We still rely on the running priority to have been
1019  *   removed from the APRs, irrespective of the LPI being present in the LRs
1020  *   or not.
1021  *
1022  * - Virtual SGIs directly injected via GICv4.1 must not affect EOIcount, as
1023  *   they are not managed in SW and don't have a true active state. So only
1024  *   set vSGIEOICount when no SGIs are in the ap_list.
1025  *
1026  * - GICv2 SGIs with multiple sources are injected one source at a time, as
1027  *   if they were made pending sequentially. This may mean that we don't
1028  *   always present the HPPI if other interrupts with lower priority are
1029  *   pending in the LRs. Big deal.
1030  */
1031 static void vgic_flush_lr_state(struct kvm_vcpu *vcpu)
1032 {
1033 	struct vgic_cpu *vgic_cpu = &vcpu->arch.vgic_cpu;
1034 	struct ap_list_summary als;
1035 	struct vgic_irq *irq;
1036 	int count = 0;
1037 
1038 	lockdep_assert_held(&vgic_cpu->ap_list_lock);
1039 
1040 	summarize_ap_list(vcpu, &als);
1041 
1042 	if (irqs_outside_lrs(&als))
1043 		vgic_sort_ap_list(vcpu);
1044 
1045 	*host_data_ptr(last_lr_irq) = NULL;
1046 
1047 	list_for_each_entry(irq, &vgic_cpu->ap_list_head, ap_list) {
1048 		scoped_guard(raw_spinlock,  &irq->irq_lock) {
1049 			if (likely(vgic_target_oracle(irq) == vcpu)) {
1050 				vgic_populate_lr(vcpu, irq, count++);
1051 				if (count == kvm_vgic_global_state.nr_lr) {
1052 					vgic_get_irq_ref(irq);
1053 					*host_data_ptr(last_lr_irq) = irq;
1054 				}
1055 			}
1056 		}
1057 
1058 		if (*host_data_ptr(last_lr_irq))
1059 			break;
1060 	}
1061 
1062 	/* Nuke remaining LRs */
1063 	for (int i = count ; i < kvm_vgic_global_state.nr_lr; i++)
1064 		vgic_clear_lr(vcpu, i);
1065 
1066 	if (!static_branch_unlikely(&kvm_vgic_global_state.gicv3_cpuif)) {
1067 		vcpu->arch.vgic_cpu.vgic_v2.used_lrs = count;
1068 		vgic_v2_configure_hcr(vcpu, &als);
1069 	} else {
1070 		vcpu->arch.vgic_cpu.vgic_v3.used_lrs = count;
1071 		vgic_v3_configure_hcr(vcpu, &als);
1072 	}
1073 }
1074 
1075 static inline bool can_access_vgic_from_kernel(void)
1076 {
1077 	/*
1078 	 * GICv2 is memory-mapped. Every other CPU interface uses EL2 system
1079 	 * registers, which only VHE can access from the kernel.
1080 	 */
1081 	return has_vhe() || kvm_vgic_global_state.type == VGIC_V2;
1082 }
1083 
1084 static inline void vgic_save_state(struct kvm_vcpu *vcpu)
1085 {
1086 	/* No switch statement here. See comment in vgic_restore_state() */
1087 	if (vgic_is_v5(vcpu->kvm))
1088 		vgic_v5_save_state(vcpu);
1089 	else if (!static_branch_unlikely(&kvm_vgic_global_state.gicv3_cpuif))
1090 		vgic_v2_save_state(vcpu);
1091 	else
1092 		__vgic_v3_save_state(&vcpu->arch.vgic_cpu.vgic_v3);
1093 }
1094 
1095 /* Sync back the hardware VGIC state into our emulation after a guest's run. */
1096 void kvm_vgic_sync_hwstate(struct kvm_vcpu *vcpu)
1097 {
1098 	if (vgic_is_v3(vcpu->kvm)) {
1099 		/* If nesting, emulate the HW effect from L0 to L1 */
1100 		if (vgic_state_is_nested(vcpu)) {
1101 			vgic_v3_sync_nested(vcpu);
1102 			return;
1103 		}
1104 
1105 		if (vcpu_has_nv(vcpu))
1106 			vgic_v3_nested_update_mi(vcpu);
1107 	}
1108 
1109 	if (can_access_vgic_from_kernel())
1110 		vgic_save_state(vcpu);
1111 
1112 	vgic_fold_state(vcpu);
1113 
1114 	if (!vgic_is_v5(vcpu->kvm))
1115 		vgic_prune_ap_list(vcpu);
1116 }
1117 
1118 /* Sync interrupts that were deactivated through a DIR trap */
1119 void kvm_vgic_process_async_update(struct kvm_vcpu *vcpu)
1120 {
1121 	unsigned long flags;
1122 
1123 	/* Make sure we're in the same context as LR handling */
1124 	local_irq_save(flags);
1125 	vgic_prune_ap_list(vcpu);
1126 	local_irq_restore(flags);
1127 }
1128 
1129 static inline void vgic_restore_state(struct kvm_vcpu *vcpu)
1130 {
1131 	/*
1132 	 * As nice as it would be to restructure this code into a switch
1133 	 * statement as can be found elsewhere, the logic quickly gets ugly.
1134 	 *
1135 	 * __vgic_v3_restore_state() is doing a lot of heavy lifting here. It is
1136 	 * required for GICv3-on-GICv3, GICv2-on-GICv3, GICv3-on-GICv5, and the
1137 	 * no-in-kernel-irqchip case on GICv3 hardware. Hence, adding a switch
1138 	 * here results in much more complex code.
1139 	 */
1140 	if (vgic_is_v5(vcpu->kvm))
1141 		vgic_v5_restore_state(vcpu);
1142 	else if (!static_branch_unlikely(&kvm_vgic_global_state.gicv3_cpuif))
1143 		vgic_v2_restore_state(vcpu);
1144 	else
1145 		__vgic_v3_restore_state(&vcpu->arch.vgic_cpu.vgic_v3);
1146 }
1147 
1148 static void vgic_flush_state(struct kvm_vcpu *vcpu)
1149 {
1150 	if (vgic_is_v5(vcpu->kvm)) {
1151 		vgic_v5_flush_ppi_state(vcpu);
1152 		return;
1153 	}
1154 
1155 	scoped_guard(raw_spinlock, &vcpu->arch.vgic_cpu.ap_list_lock)
1156 		vgic_flush_lr_state(vcpu);
1157 }
1158 
1159 /* Flush our emulation state into the GIC hardware before entering the guest. */
1160 void kvm_vgic_flush_hwstate(struct kvm_vcpu *vcpu)
1161 {
1162 	/*
1163 	 * If in a nested state, we must return early. Two possibilities:
1164 	 *
1165 	 * - If we have any pending IRQ for the guest and the guest
1166 	 *   expects IRQs to be handled in its virtual EL2 mode (the
1167 	 *   virtual IMO bit is set) and it is not already running in
1168 	 *   virtual EL2 mode, then we have to emulate an IRQ
1169 	 *   exception to virtual EL2.
1170 	 *
1171 	 *   We do that by placing a request to ourselves which will
1172 	 *   abort the entry procedure and inject the exception at the
1173 	 *   beginning of the run loop (see kvm_nested_flush_hwstate()).
1174 	 *
1175 	 * - Otherwise, do exactly *NOTHING* apart from enabling the virtual
1176 	 *   CPU interface. The guest state is already loaded, and we can
1177 	 *   carry on with running it.
1178 	 *
1179 	 * If we have NV, but are not in a nested state, compute the
1180 	 * maintenance interrupt state, as it may fire.
1181 	 */
1182 	if (vgic_state_is_nested(vcpu)) {
1183 		vgic_v3_flush_nested(vcpu);
1184 		return;
1185 	}
1186 
1187 	DEBUG_SPINLOCK_BUG_ON(!irqs_disabled());
1188 
1189 	vgic_flush_state(vcpu);
1190 
1191 	if (can_access_vgic_from_kernel())
1192 		vgic_restore_state(vcpu);
1193 
1194 	if (vgic_supports_direct_irqs(vcpu->kvm) && kvm_vgic_global_state.has_gicv4)
1195 		vgic_v4_commit(vcpu);
1196 }
1197 
1198 void kvm_vgic_load(struct kvm_vcpu *vcpu)
1199 {
1200 	const struct vgic_dist *dist = &vcpu->kvm->arch.vgic;
1201 
1202 	if (unlikely(!irqchip_in_kernel(vcpu->kvm) || !vgic_initialized(vcpu->kvm))) {
1203 		if (has_vhe() && static_branch_unlikely(&kvm_vgic_global_state.gicv3_cpuif))
1204 			__vgic_v3_activate_traps(&vcpu->arch.vgic_cpu.vgic_v3);
1205 		return;
1206 	}
1207 
1208 	switch (dist->vgic_model) {
1209 	case KVM_DEV_TYPE_ARM_VGIC_V5:
1210 		vgic_v5_load(vcpu);
1211 		break;
1212 	case KVM_DEV_TYPE_ARM_VGIC_V3:
1213 		vgic_v3_load(vcpu);
1214 		break;
1215 	case KVM_DEV_TYPE_ARM_VGIC_V2:
1216 		if (static_branch_unlikely(&kvm_vgic_global_state.gicv3_cpuif))
1217 			vgic_v3_load(vcpu);
1218 		else
1219 			vgic_v2_load(vcpu);
1220 		break;
1221 	default:
1222 		BUG();
1223 	}
1224 }
1225 
1226 void kvm_vgic_put(struct kvm_vcpu *vcpu)
1227 {
1228 	const struct vgic_dist *dist = &vcpu->kvm->arch.vgic;
1229 
1230 	if (unlikely(!irqchip_in_kernel(vcpu->kvm) || !vgic_initialized(vcpu->kvm))) {
1231 		if (has_vhe() && static_branch_unlikely(&kvm_vgic_global_state.gicv3_cpuif))
1232 			__vgic_v3_deactivate_traps(&vcpu->arch.vgic_cpu.vgic_v3);
1233 		return;
1234 	}
1235 
1236 	switch (dist->vgic_model) {
1237 	case KVM_DEV_TYPE_ARM_VGIC_V5:
1238 		vgic_v5_put(vcpu);
1239 		break;
1240 	case KVM_DEV_TYPE_ARM_VGIC_V3:
1241 		vgic_v3_put(vcpu);
1242 		break;
1243 	case KVM_DEV_TYPE_ARM_VGIC_V2:
1244 		if (static_branch_unlikely(&kvm_vgic_global_state.gicv3_cpuif))
1245 			vgic_v3_put(vcpu);
1246 		else
1247 			vgic_v2_put(vcpu);
1248 		break;
1249 	default:
1250 		BUG();
1251 	}
1252 }
1253 
1254 int kvm_vgic_vcpu_pending_irq(struct kvm_vcpu *vcpu)
1255 {
1256 	struct vgic_cpu *vgic_cpu = &vcpu->arch.vgic_cpu;
1257 	struct vgic_irq *irq;
1258 	bool pending = false;
1259 	unsigned long flags;
1260 	struct vgic_vmcr vmcr;
1261 
1262 	if (vgic_is_v5(vcpu->kvm)) {
1263 		if (READ_ONCE(vcpu->arch.vgic_cpu.vgic_v5.gicv5_vpe.db_fired))
1264 			return true;
1265 
1266 		return vgic_v5_has_pending_ppi(vcpu);
1267 	}
1268 
1269 	if (!vcpu->kvm->arch.vgic.enabled)
1270 		return false;
1271 
1272 	if (vcpu->arch.vgic_cpu.vgic_v3.its_vpe.pending_last)
1273 		return true;
1274 
1275 	vgic_get_vmcr(vcpu, &vmcr);
1276 
1277 	raw_spin_lock_irqsave(&vgic_cpu->ap_list_lock, flags);
1278 
1279 	list_for_each_entry(irq, &vgic_cpu->ap_list_head, ap_list) {
1280 		raw_spin_lock(&irq->irq_lock);
1281 		pending = irq_is_pending(irq) && irq->enabled &&
1282 			  !irq->active &&
1283 			  irq->priority < vmcr.pmr;
1284 		raw_spin_unlock(&irq->irq_lock);
1285 
1286 		if (pending)
1287 			break;
1288 	}
1289 
1290 	raw_spin_unlock_irqrestore(&vgic_cpu->ap_list_lock, flags);
1291 
1292 	return pending;
1293 }
1294 
1295 void vgic_kick_vcpus(struct kvm *kvm)
1296 {
1297 	struct kvm_vcpu *vcpu;
1298 	unsigned long c;
1299 
1300 	/*
1301 	 * We've injected an interrupt, time to find out who deserves
1302 	 * a good kick...
1303 	 */
1304 	kvm_for_each_vcpu(c, vcpu, kvm) {
1305 		if (kvm_vgic_vcpu_pending_irq(vcpu)) {
1306 			kvm_make_request(KVM_REQ_IRQ_PENDING, vcpu);
1307 			kvm_vcpu_kick(vcpu);
1308 		}
1309 	}
1310 }
1311 
1312 bool kvm_vgic_map_is_active(struct kvm_vcpu *vcpu, unsigned int vintid)
1313 {
1314 	struct vgic_irq *irq;
1315 	bool map_is_active;
1316 	unsigned long flags;
1317 
1318 	if (!vgic_initialized(vcpu->kvm))
1319 		return false;
1320 
1321 	irq = vgic_get_vcpu_irq(vcpu, vintid);
1322 	raw_spin_lock_irqsave(&irq->irq_lock, flags);
1323 	map_is_active = irq->hw && irq->active;
1324 	raw_spin_unlock_irqrestore(&irq->irq_lock, flags);
1325 	vgic_put_irq(vcpu->kvm, irq);
1326 
1327 	return map_is_active;
1328 }
1329 
1330 /*
1331  * Level-triggered mapped IRQs are special because we only observe rising
1332  * edges as input to the VGIC.
1333  *
1334  * If the guest never acked the interrupt we have to sample the physical
1335  * line and set the line level, because the device state could have changed
1336  * or we simply need to process the still pending interrupt later.
1337  *
1338  * We could also have entered the guest with the interrupt active+pending.
1339  * On the next exit, we need to re-evaluate the pending state, as it could
1340  * otherwise result in a spurious interrupt by injecting a now potentially
1341  * stale pending state.
1342  *
1343  * If this causes us to lower the level, we have to also clear the physical
1344  * active state, since we will otherwise never be told when the interrupt
1345  * becomes asserted again.
1346  *
1347  * Another case is when the interrupt requires a helping hand on
1348  * deactivation (no HW deactivation, for example).
1349  */
1350 void vgic_irq_handle_resampling(struct vgic_irq *irq,
1351 				bool lr_deactivated, bool lr_pending)
1352 {
1353 	if (vgic_irq_is_mapped_level(irq)) {
1354 		bool resample = false;
1355 
1356 		if (unlikely(vgic_irq_needs_resampling(irq))) {
1357 			resample = !(irq->active || irq->pending_latch);
1358 		} else if (lr_pending || (lr_deactivated && irq->line_level)) {
1359 			irq->line_level = vgic_get_phys_line_level(irq);
1360 			resample = !irq->line_level;
1361 		}
1362 
1363 		if (resample)
1364 			vgic_irq_set_phys_active(irq, false);
1365 	}
1366 }
1367