xref: /linux/arch/arm64/kvm/vgic/vgic.c (revision 19d837bc881b2f9f72f9eb506b46c2e2d983896d)
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_cpu->ap_list_lock		must be taken with IRQs disabled
32  *             vgic_dist->lpi_xa.xa_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  * If you need to take multiple locks, always take the upper lock first,
40  * then the lower ones, e.g. first take the its_lock, then the irq_lock.
41  * If you are already holding a lock and need to take a higher one, you
42  * have to drop the lower ranking lock first and re-acquire it after having
43  * taken the upper one.
44  *
45  * When taking more than one ap_list_lock at the same time, always take the
46  * lowest numbered VCPU's ap_list_lock first, so:
47  *   vcpuX->vcpu_id < vcpuY->vcpu_id:
48  *     raw_spin_lock(vcpuX->arch.vgic_cpu.ap_list_lock);
49  *     raw_spin_lock(vcpuY->arch.vgic_cpu.ap_list_lock);
50  *
51  * Since the VGIC must support injecting virtual interrupts from ISRs, we have
52  * to use the raw_spin_lock_irqsave/raw_spin_unlock_irqrestore versions of outer
53  * spinlocks for any lock that may be taken while injecting an interrupt.
54  */
55 
56 /*
57  * Index the VM's xarray of mapped LPIs and return a reference to the IRQ
58  * structure. The caller is expected to call vgic_put_irq() later once it's
59  * finished with the IRQ.
60  */
61 static struct vgic_irq *vgic_get_lpi(struct kvm *kvm, u32 intid)
62 {
63 	struct vgic_dist *dist = &kvm->arch.vgic;
64 	struct vgic_irq *irq = NULL;
65 
66 	rcu_read_lock();
67 
68 	irq = xa_load(&dist->lpi_xa, intid);
69 	if (!vgic_try_get_irq_kref(irq))
70 		irq = NULL;
71 
72 	rcu_read_unlock();
73 
74 	return irq;
75 }
76 
77 /*
78  * This looks up the virtual interrupt ID to get the corresponding
79  * struct vgic_irq. It also increases the refcount, so any caller is expected
80  * to call vgic_put_irq() once it's finished with this IRQ.
81  */
82 struct vgic_irq *vgic_get_irq(struct kvm *kvm, struct kvm_vcpu *vcpu,
83 			      u32 intid)
84 {
85 	/* SGIs and PPIs */
86 	if (intid <= VGIC_MAX_PRIVATE) {
87 		intid = array_index_nospec(intid, VGIC_MAX_PRIVATE + 1);
88 		return &vcpu->arch.vgic_cpu.private_irqs[intid];
89 	}
90 
91 	/* SPIs */
92 	if (intid < (kvm->arch.vgic.nr_spis + VGIC_NR_PRIVATE_IRQS)) {
93 		intid = array_index_nospec(intid, kvm->arch.vgic.nr_spis + VGIC_NR_PRIVATE_IRQS);
94 		return &kvm->arch.vgic.spis[intid - VGIC_NR_PRIVATE_IRQS];
95 	}
96 
97 	/* LPIs */
98 	if (intid >= VGIC_MIN_LPI)
99 		return vgic_get_lpi(kvm, intid);
100 
101 	return NULL;
102 }
103 
104 /*
105  * We can't do anything in here, because we lack the kvm pointer to
106  * lock and remove the item from the lpi_list. So we keep this function
107  * empty and use the return value of kref_put() to trigger the freeing.
108  */
109 static void vgic_irq_release(struct kref *ref)
110 {
111 }
112 
113 void vgic_put_irq(struct kvm *kvm, struct vgic_irq *irq)
114 {
115 	struct vgic_dist *dist = &kvm->arch.vgic;
116 	unsigned long flags;
117 
118 	if (irq->intid < VGIC_MIN_LPI)
119 		return;
120 
121 	if (!kref_put(&irq->refcount, vgic_irq_release))
122 		return;
123 
124 	xa_lock_irqsave(&dist->lpi_xa, flags);
125 	__xa_erase(&dist->lpi_xa, irq->intid);
126 	xa_unlock_irqrestore(&dist->lpi_xa, flags);
127 
128 	kfree_rcu(irq, rcu);
129 }
130 
131 void vgic_flush_pending_lpis(struct kvm_vcpu *vcpu)
132 {
133 	struct vgic_cpu *vgic_cpu = &vcpu->arch.vgic_cpu;
134 	struct vgic_irq *irq, *tmp;
135 	unsigned long flags;
136 
137 	raw_spin_lock_irqsave(&vgic_cpu->ap_list_lock, flags);
138 
139 	list_for_each_entry_safe(irq, tmp, &vgic_cpu->ap_list_head, ap_list) {
140 		if (irq->intid >= VGIC_MIN_LPI) {
141 			raw_spin_lock(&irq->irq_lock);
142 			list_del(&irq->ap_list);
143 			irq->vcpu = NULL;
144 			raw_spin_unlock(&irq->irq_lock);
145 			vgic_put_irq(vcpu->kvm, irq);
146 		}
147 	}
148 
149 	raw_spin_unlock_irqrestore(&vgic_cpu->ap_list_lock, flags);
150 }
151 
152 void vgic_irq_set_phys_pending(struct vgic_irq *irq, bool pending)
153 {
154 	WARN_ON(irq_set_irqchip_state(irq->host_irq,
155 				      IRQCHIP_STATE_PENDING,
156 				      pending));
157 }
158 
159 bool vgic_get_phys_line_level(struct vgic_irq *irq)
160 {
161 	bool line_level;
162 
163 	BUG_ON(!irq->hw);
164 
165 	if (irq->ops && irq->ops->get_input_level)
166 		return irq->ops->get_input_level(irq->intid);
167 
168 	WARN_ON(irq_get_irqchip_state(irq->host_irq,
169 				      IRQCHIP_STATE_PENDING,
170 				      &line_level));
171 	return line_level;
172 }
173 
174 /* Set/Clear the physical active state */
175 void vgic_irq_set_phys_active(struct vgic_irq *irq, bool active)
176 {
177 
178 	BUG_ON(!irq->hw);
179 	WARN_ON(irq_set_irqchip_state(irq->host_irq,
180 				      IRQCHIP_STATE_ACTIVE,
181 				      active));
182 }
183 
184 /**
185  * vgic_target_oracle - compute the target vcpu for an irq
186  *
187  * @irq:	The irq to route. Must be already locked.
188  *
189  * Based on the current state of the interrupt (enabled, pending,
190  * active, vcpu and target_vcpu), compute the next vcpu this should be
191  * given to. Return NULL if this shouldn't be injected at all.
192  *
193  * Requires the IRQ lock to be held.
194  */
195 static struct kvm_vcpu *vgic_target_oracle(struct vgic_irq *irq)
196 {
197 	lockdep_assert_held(&irq->irq_lock);
198 
199 	/* If the interrupt is active, it must stay on the current vcpu */
200 	if (irq->active)
201 		return irq->vcpu ? : irq->target_vcpu;
202 
203 	/*
204 	 * If the IRQ is not active but enabled and pending, we should direct
205 	 * it to its configured target VCPU.
206 	 * If the distributor is disabled, pending interrupts shouldn't be
207 	 * forwarded.
208 	 */
209 	if (irq->enabled && irq_is_pending(irq)) {
210 		if (unlikely(irq->target_vcpu &&
211 			     !irq->target_vcpu->kvm->arch.vgic.enabled))
212 			return NULL;
213 
214 		return irq->target_vcpu;
215 	}
216 
217 	/* If neither active nor pending and enabled, then this IRQ should not
218 	 * be queued to any VCPU.
219 	 */
220 	return NULL;
221 }
222 
223 /*
224  * The order of items in the ap_lists defines how we'll pack things in LRs as
225  * well, the first items in the list being the first things populated in the
226  * LRs.
227  *
228  * A hard rule is that active interrupts can never be pushed out of the LRs
229  * (and therefore take priority) since we cannot reliably trap on deactivation
230  * of IRQs and therefore they have to be present in the LRs.
231  *
232  * Otherwise things should be sorted by the priority field and the GIC
233  * hardware support will take care of preemption of priority groups etc.
234  *
235  * Return negative if "a" sorts before "b", 0 to preserve order, and positive
236  * to sort "b" before "a".
237  */
238 static int vgic_irq_cmp(void *priv, const struct list_head *a,
239 			const struct list_head *b)
240 {
241 	struct vgic_irq *irqa = container_of(a, struct vgic_irq, ap_list);
242 	struct vgic_irq *irqb = container_of(b, struct vgic_irq, ap_list);
243 	bool penda, pendb;
244 	int ret;
245 
246 	/*
247 	 * list_sort may call this function with the same element when
248 	 * the list is fairly long.
249 	 */
250 	if (unlikely(irqa == irqb))
251 		return 0;
252 
253 	raw_spin_lock(&irqa->irq_lock);
254 	raw_spin_lock_nested(&irqb->irq_lock, SINGLE_DEPTH_NESTING);
255 
256 	if (irqa->active || irqb->active) {
257 		ret = (int)irqb->active - (int)irqa->active;
258 		goto out;
259 	}
260 
261 	penda = irqa->enabled && irq_is_pending(irqa);
262 	pendb = irqb->enabled && irq_is_pending(irqb);
263 
264 	if (!penda || !pendb) {
265 		ret = (int)pendb - (int)penda;
266 		goto out;
267 	}
268 
269 	/* Both pending and enabled, sort by priority */
270 	ret = irqa->priority - irqb->priority;
271 out:
272 	raw_spin_unlock(&irqb->irq_lock);
273 	raw_spin_unlock(&irqa->irq_lock);
274 	return ret;
275 }
276 
277 /* Must be called with the ap_list_lock held */
278 static void vgic_sort_ap_list(struct kvm_vcpu *vcpu)
279 {
280 	struct vgic_cpu *vgic_cpu = &vcpu->arch.vgic_cpu;
281 
282 	lockdep_assert_held(&vgic_cpu->ap_list_lock);
283 
284 	list_sort(NULL, &vgic_cpu->ap_list_head, vgic_irq_cmp);
285 }
286 
287 /*
288  * Only valid injection if changing level for level-triggered IRQs or for a
289  * rising edge, and in-kernel connected IRQ lines can only be controlled by
290  * their owner.
291  */
292 static bool vgic_validate_injection(struct vgic_irq *irq, bool level, void *owner)
293 {
294 	if (irq->owner != owner)
295 		return false;
296 
297 	switch (irq->config) {
298 	case VGIC_CONFIG_LEVEL:
299 		return irq->line_level != level;
300 	case VGIC_CONFIG_EDGE:
301 		return level;
302 	}
303 
304 	return false;
305 }
306 
307 /*
308  * Check whether an IRQ needs to (and can) be queued to a VCPU's ap list.
309  * Do the queuing if necessary, taking the right locks in the right order.
310  * Returns true when the IRQ was queued, false otherwise.
311  *
312  * Needs to be entered with the IRQ lock already held, but will return
313  * with all locks dropped.
314  */
315 bool vgic_queue_irq_unlock(struct kvm *kvm, struct vgic_irq *irq,
316 			   unsigned long flags) __releases(&irq->irq_lock)
317 {
318 	struct kvm_vcpu *vcpu;
319 
320 	lockdep_assert_held(&irq->irq_lock);
321 
322 retry:
323 	vcpu = vgic_target_oracle(irq);
324 	if (irq->vcpu || !vcpu) {
325 		/*
326 		 * If this IRQ is already on a VCPU's ap_list, then it
327 		 * cannot be moved or modified and there is no more work for
328 		 * us to do.
329 		 *
330 		 * Otherwise, if the irq is not pending and enabled, it does
331 		 * not need to be inserted into an ap_list and there is also
332 		 * no more work for us to do.
333 		 */
334 		raw_spin_unlock_irqrestore(&irq->irq_lock, flags);
335 
336 		/*
337 		 * We have to kick the VCPU here, because we could be
338 		 * queueing an edge-triggered interrupt for which we
339 		 * get no EOI maintenance interrupt. In that case,
340 		 * while the IRQ is already on the VCPU's AP list, the
341 		 * VCPU could have EOI'ed the original interrupt and
342 		 * won't see this one until it exits for some other
343 		 * reason.
344 		 */
345 		if (vcpu) {
346 			kvm_make_request(KVM_REQ_IRQ_PENDING, vcpu);
347 			kvm_vcpu_kick(vcpu);
348 		}
349 		return false;
350 	}
351 
352 	/*
353 	 * We must unlock the irq lock to take the ap_list_lock where
354 	 * we are going to insert this new pending interrupt.
355 	 */
356 	raw_spin_unlock_irqrestore(&irq->irq_lock, flags);
357 
358 	/* someone can do stuff here, which we re-check below */
359 
360 	raw_spin_lock_irqsave(&vcpu->arch.vgic_cpu.ap_list_lock, flags);
361 	raw_spin_lock(&irq->irq_lock);
362 
363 	/*
364 	 * Did something change behind our backs?
365 	 *
366 	 * There are two cases:
367 	 * 1) The irq lost its pending state or was disabled behind our
368 	 *    backs and/or it was queued to another VCPU's ap_list.
369 	 * 2) Someone changed the affinity on this irq behind our
370 	 *    backs and we are now holding the wrong ap_list_lock.
371 	 *
372 	 * In both cases, drop the locks and retry.
373 	 */
374 
375 	if (unlikely(irq->vcpu || vcpu != vgic_target_oracle(irq))) {
376 		raw_spin_unlock(&irq->irq_lock);
377 		raw_spin_unlock_irqrestore(&vcpu->arch.vgic_cpu.ap_list_lock,
378 					   flags);
379 
380 		raw_spin_lock_irqsave(&irq->irq_lock, flags);
381 		goto retry;
382 	}
383 
384 	/*
385 	 * Grab a reference to the irq to reflect the fact that it is
386 	 * now in the ap_list. This is safe as the caller must already hold a
387 	 * reference on the irq.
388 	 */
389 	vgic_get_irq_kref(irq);
390 	list_add_tail(&irq->ap_list, &vcpu->arch.vgic_cpu.ap_list_head);
391 	irq->vcpu = vcpu;
392 
393 	raw_spin_unlock(&irq->irq_lock);
394 	raw_spin_unlock_irqrestore(&vcpu->arch.vgic_cpu.ap_list_lock, flags);
395 
396 	kvm_make_request(KVM_REQ_IRQ_PENDING, vcpu);
397 	kvm_vcpu_kick(vcpu);
398 
399 	return true;
400 }
401 
402 /**
403  * kvm_vgic_inject_irq - Inject an IRQ from a device to the vgic
404  * @kvm:     The VM structure pointer
405  * @vcpu:    The CPU for PPIs or NULL for global interrupts
406  * @intid:   The INTID to inject a new state to.
407  * @level:   Edge-triggered:  true:  to trigger the interrupt
408  *			      false: to ignore the call
409  *	     Level-sensitive  true:  raise the input signal
410  *			      false: lower the input signal
411  * @owner:   The opaque pointer to the owner of the IRQ being raised to verify
412  *           that the caller is allowed to inject this IRQ.  Userspace
413  *           injections will have owner == NULL.
414  *
415  * The VGIC is not concerned with devices being active-LOW or active-HIGH for
416  * level-sensitive interrupts.  You can think of the level parameter as 1
417  * being HIGH and 0 being LOW and all devices being active-HIGH.
418  */
419 int kvm_vgic_inject_irq(struct kvm *kvm, struct kvm_vcpu *vcpu,
420 			unsigned int intid, bool level, void *owner)
421 {
422 	struct vgic_irq *irq;
423 	unsigned long flags;
424 	int ret;
425 
426 	ret = vgic_lazy_init(kvm);
427 	if (ret)
428 		return ret;
429 
430 	if (!vcpu && intid < VGIC_NR_PRIVATE_IRQS)
431 		return -EINVAL;
432 
433 	trace_vgic_update_irq_pending(vcpu ? vcpu->vcpu_idx : 0, intid, level);
434 
435 	irq = vgic_get_irq(kvm, vcpu, intid);
436 	if (!irq)
437 		return -EINVAL;
438 
439 	raw_spin_lock_irqsave(&irq->irq_lock, flags);
440 
441 	if (!vgic_validate_injection(irq, level, owner)) {
442 		/* Nothing to see here, move along... */
443 		raw_spin_unlock_irqrestore(&irq->irq_lock, flags);
444 		vgic_put_irq(kvm, irq);
445 		return 0;
446 	}
447 
448 	if (irq->config == VGIC_CONFIG_LEVEL)
449 		irq->line_level = level;
450 	else
451 		irq->pending_latch = true;
452 
453 	vgic_queue_irq_unlock(kvm, irq, flags);
454 	vgic_put_irq(kvm, irq);
455 
456 	return 0;
457 }
458 
459 /* @irq->irq_lock must be held */
460 static int kvm_vgic_map_irq(struct kvm_vcpu *vcpu, struct vgic_irq *irq,
461 			    unsigned int host_irq,
462 			    struct irq_ops *ops)
463 {
464 	struct irq_desc *desc;
465 	struct irq_data *data;
466 
467 	/*
468 	 * Find the physical IRQ number corresponding to @host_irq
469 	 */
470 	desc = irq_to_desc(host_irq);
471 	if (!desc) {
472 		kvm_err("%s: no interrupt descriptor\n", __func__);
473 		return -EINVAL;
474 	}
475 	data = irq_desc_get_irq_data(desc);
476 	while (data->parent_data)
477 		data = data->parent_data;
478 
479 	irq->hw = true;
480 	irq->host_irq = host_irq;
481 	irq->hwintid = data->hwirq;
482 	irq->ops = ops;
483 	return 0;
484 }
485 
486 /* @irq->irq_lock must be held */
487 static inline void kvm_vgic_unmap_irq(struct vgic_irq *irq)
488 {
489 	irq->hw = false;
490 	irq->hwintid = 0;
491 	irq->ops = NULL;
492 }
493 
494 int kvm_vgic_map_phys_irq(struct kvm_vcpu *vcpu, unsigned int host_irq,
495 			  u32 vintid, struct irq_ops *ops)
496 {
497 	struct vgic_irq *irq = vgic_get_irq(vcpu->kvm, vcpu, vintid);
498 	unsigned long flags;
499 	int ret;
500 
501 	BUG_ON(!irq);
502 
503 	raw_spin_lock_irqsave(&irq->irq_lock, flags);
504 	ret = kvm_vgic_map_irq(vcpu, irq, host_irq, ops);
505 	raw_spin_unlock_irqrestore(&irq->irq_lock, flags);
506 	vgic_put_irq(vcpu->kvm, irq);
507 
508 	return ret;
509 }
510 
511 /**
512  * kvm_vgic_reset_mapped_irq - Reset a mapped IRQ
513  * @vcpu: The VCPU pointer
514  * @vintid: The INTID of the interrupt
515  *
516  * Reset the active and pending states of a mapped interrupt.  Kernel
517  * subsystems injecting mapped interrupts should reset their interrupt lines
518  * when we are doing a reset of the VM.
519  */
520 void kvm_vgic_reset_mapped_irq(struct kvm_vcpu *vcpu, u32 vintid)
521 {
522 	struct vgic_irq *irq = vgic_get_irq(vcpu->kvm, vcpu, vintid);
523 	unsigned long flags;
524 
525 	if (!irq->hw)
526 		goto out;
527 
528 	raw_spin_lock_irqsave(&irq->irq_lock, flags);
529 	irq->active = false;
530 	irq->pending_latch = false;
531 	irq->line_level = false;
532 	raw_spin_unlock_irqrestore(&irq->irq_lock, flags);
533 out:
534 	vgic_put_irq(vcpu->kvm, irq);
535 }
536 
537 int kvm_vgic_unmap_phys_irq(struct kvm_vcpu *vcpu, unsigned int vintid)
538 {
539 	struct vgic_irq *irq;
540 	unsigned long flags;
541 
542 	if (!vgic_initialized(vcpu->kvm))
543 		return -EAGAIN;
544 
545 	irq = vgic_get_irq(vcpu->kvm, vcpu, vintid);
546 	BUG_ON(!irq);
547 
548 	raw_spin_lock_irqsave(&irq->irq_lock, flags);
549 	kvm_vgic_unmap_irq(irq);
550 	raw_spin_unlock_irqrestore(&irq->irq_lock, flags);
551 	vgic_put_irq(vcpu->kvm, irq);
552 
553 	return 0;
554 }
555 
556 int kvm_vgic_get_map(struct kvm_vcpu *vcpu, unsigned int vintid)
557 {
558 	struct vgic_irq *irq = vgic_get_irq(vcpu->kvm, vcpu, vintid);
559 	unsigned long flags;
560 	int ret = -1;
561 
562 	raw_spin_lock_irqsave(&irq->irq_lock, flags);
563 	if (irq->hw)
564 		ret = irq->hwintid;
565 	raw_spin_unlock_irqrestore(&irq->irq_lock, flags);
566 
567 	vgic_put_irq(vcpu->kvm, irq);
568 	return ret;
569 }
570 
571 /**
572  * kvm_vgic_set_owner - Set the owner of an interrupt for a VM
573  *
574  * @vcpu:   Pointer to the VCPU (used for PPIs)
575  * @intid:  The virtual INTID identifying the interrupt (PPI or SPI)
576  * @owner:  Opaque pointer to the owner
577  *
578  * Returns 0 if intid is not already used by another in-kernel device and the
579  * owner is set, otherwise returns an error code.
580  */
581 int kvm_vgic_set_owner(struct kvm_vcpu *vcpu, unsigned int intid, void *owner)
582 {
583 	struct vgic_irq *irq;
584 	unsigned long flags;
585 	int ret = 0;
586 
587 	if (!vgic_initialized(vcpu->kvm))
588 		return -EAGAIN;
589 
590 	/* SGIs and LPIs cannot be wired up to any device */
591 	if (!irq_is_ppi(intid) && !vgic_valid_spi(vcpu->kvm, intid))
592 		return -EINVAL;
593 
594 	irq = vgic_get_irq(vcpu->kvm, vcpu, intid);
595 	raw_spin_lock_irqsave(&irq->irq_lock, flags);
596 	if (irq->owner && irq->owner != owner)
597 		ret = -EEXIST;
598 	else
599 		irq->owner = owner;
600 	raw_spin_unlock_irqrestore(&irq->irq_lock, flags);
601 
602 	return ret;
603 }
604 
605 /**
606  * vgic_prune_ap_list - Remove non-relevant interrupts from the list
607  *
608  * @vcpu: The VCPU pointer
609  *
610  * Go over the list of "interesting" interrupts, and prune those that we
611  * won't have to consider in the near future.
612  */
613 static void vgic_prune_ap_list(struct kvm_vcpu *vcpu)
614 {
615 	struct vgic_cpu *vgic_cpu = &vcpu->arch.vgic_cpu;
616 	struct vgic_irq *irq, *tmp;
617 
618 	DEBUG_SPINLOCK_BUG_ON(!irqs_disabled());
619 
620 retry:
621 	raw_spin_lock(&vgic_cpu->ap_list_lock);
622 
623 	list_for_each_entry_safe(irq, tmp, &vgic_cpu->ap_list_head, ap_list) {
624 		struct kvm_vcpu *target_vcpu, *vcpuA, *vcpuB;
625 		bool target_vcpu_needs_kick = false;
626 
627 		raw_spin_lock(&irq->irq_lock);
628 
629 		BUG_ON(vcpu != irq->vcpu);
630 
631 		target_vcpu = vgic_target_oracle(irq);
632 
633 		if (!target_vcpu) {
634 			/*
635 			 * We don't need to process this interrupt any
636 			 * further, move it off the list.
637 			 */
638 			list_del(&irq->ap_list);
639 			irq->vcpu = NULL;
640 			raw_spin_unlock(&irq->irq_lock);
641 
642 			/*
643 			 * This vgic_put_irq call matches the
644 			 * vgic_get_irq_kref in vgic_queue_irq_unlock,
645 			 * where we added the LPI to the ap_list. As
646 			 * we remove the irq from the list, we drop
647 			 * also drop the refcount.
648 			 */
649 			vgic_put_irq(vcpu->kvm, irq);
650 			continue;
651 		}
652 
653 		if (target_vcpu == vcpu) {
654 			/* We're on the right CPU */
655 			raw_spin_unlock(&irq->irq_lock);
656 			continue;
657 		}
658 
659 		/* This interrupt looks like it has to be migrated. */
660 
661 		raw_spin_unlock(&irq->irq_lock);
662 		raw_spin_unlock(&vgic_cpu->ap_list_lock);
663 
664 		/*
665 		 * Ensure locking order by always locking the smallest
666 		 * ID first.
667 		 */
668 		if (vcpu->vcpu_id < target_vcpu->vcpu_id) {
669 			vcpuA = vcpu;
670 			vcpuB = target_vcpu;
671 		} else {
672 			vcpuA = target_vcpu;
673 			vcpuB = vcpu;
674 		}
675 
676 		raw_spin_lock(&vcpuA->arch.vgic_cpu.ap_list_lock);
677 		raw_spin_lock_nested(&vcpuB->arch.vgic_cpu.ap_list_lock,
678 				      SINGLE_DEPTH_NESTING);
679 		raw_spin_lock(&irq->irq_lock);
680 
681 		/*
682 		 * If the affinity has been preserved, move the
683 		 * interrupt around. Otherwise, it means things have
684 		 * changed while the interrupt was unlocked, and we
685 		 * need to replay this.
686 		 *
687 		 * In all cases, we cannot trust the list not to have
688 		 * changed, so we restart from the beginning.
689 		 */
690 		if (target_vcpu == vgic_target_oracle(irq)) {
691 			struct vgic_cpu *new_cpu = &target_vcpu->arch.vgic_cpu;
692 
693 			list_del(&irq->ap_list);
694 			irq->vcpu = target_vcpu;
695 			list_add_tail(&irq->ap_list, &new_cpu->ap_list_head);
696 			target_vcpu_needs_kick = true;
697 		}
698 
699 		raw_spin_unlock(&irq->irq_lock);
700 		raw_spin_unlock(&vcpuB->arch.vgic_cpu.ap_list_lock);
701 		raw_spin_unlock(&vcpuA->arch.vgic_cpu.ap_list_lock);
702 
703 		if (target_vcpu_needs_kick) {
704 			kvm_make_request(KVM_REQ_IRQ_PENDING, target_vcpu);
705 			kvm_vcpu_kick(target_vcpu);
706 		}
707 
708 		goto retry;
709 	}
710 
711 	raw_spin_unlock(&vgic_cpu->ap_list_lock);
712 }
713 
714 static inline void vgic_fold_lr_state(struct kvm_vcpu *vcpu)
715 {
716 	if (kvm_vgic_global_state.type == VGIC_V2)
717 		vgic_v2_fold_lr_state(vcpu);
718 	else
719 		vgic_v3_fold_lr_state(vcpu);
720 }
721 
722 /* Requires the irq_lock to be held. */
723 static inline void vgic_populate_lr(struct kvm_vcpu *vcpu,
724 				    struct vgic_irq *irq, int lr)
725 {
726 	lockdep_assert_held(&irq->irq_lock);
727 
728 	if (kvm_vgic_global_state.type == VGIC_V2)
729 		vgic_v2_populate_lr(vcpu, irq, lr);
730 	else
731 		vgic_v3_populate_lr(vcpu, irq, lr);
732 }
733 
734 static inline void vgic_clear_lr(struct kvm_vcpu *vcpu, int lr)
735 {
736 	if (kvm_vgic_global_state.type == VGIC_V2)
737 		vgic_v2_clear_lr(vcpu, lr);
738 	else
739 		vgic_v3_clear_lr(vcpu, lr);
740 }
741 
742 static inline void vgic_set_underflow(struct kvm_vcpu *vcpu)
743 {
744 	if (kvm_vgic_global_state.type == VGIC_V2)
745 		vgic_v2_set_underflow(vcpu);
746 	else
747 		vgic_v3_set_underflow(vcpu);
748 }
749 
750 /* Requires the ap_list_lock to be held. */
751 static int compute_ap_list_depth(struct kvm_vcpu *vcpu,
752 				 bool *multi_sgi)
753 {
754 	struct vgic_cpu *vgic_cpu = &vcpu->arch.vgic_cpu;
755 	struct vgic_irq *irq;
756 	int count = 0;
757 
758 	*multi_sgi = false;
759 
760 	lockdep_assert_held(&vgic_cpu->ap_list_lock);
761 
762 	list_for_each_entry(irq, &vgic_cpu->ap_list_head, ap_list) {
763 		int w;
764 
765 		raw_spin_lock(&irq->irq_lock);
766 		/* GICv2 SGIs can count for more than one... */
767 		w = vgic_irq_get_lr_count(irq);
768 		raw_spin_unlock(&irq->irq_lock);
769 
770 		count += w;
771 		*multi_sgi |= (w > 1);
772 	}
773 	return count;
774 }
775 
776 /* Requires the VCPU's ap_list_lock to be held. */
777 static void vgic_flush_lr_state(struct kvm_vcpu *vcpu)
778 {
779 	struct vgic_cpu *vgic_cpu = &vcpu->arch.vgic_cpu;
780 	struct vgic_irq *irq;
781 	int count;
782 	bool multi_sgi;
783 	u8 prio = 0xff;
784 	int i = 0;
785 
786 	lockdep_assert_held(&vgic_cpu->ap_list_lock);
787 
788 	count = compute_ap_list_depth(vcpu, &multi_sgi);
789 	if (count > kvm_vgic_global_state.nr_lr || multi_sgi)
790 		vgic_sort_ap_list(vcpu);
791 
792 	count = 0;
793 
794 	list_for_each_entry(irq, &vgic_cpu->ap_list_head, ap_list) {
795 		raw_spin_lock(&irq->irq_lock);
796 
797 		/*
798 		 * If we have multi-SGIs in the pipeline, we need to
799 		 * guarantee that they are all seen before any IRQ of
800 		 * lower priority. In that case, we need to filter out
801 		 * these interrupts by exiting early. This is easy as
802 		 * the AP list has been sorted already.
803 		 */
804 		if (multi_sgi && irq->priority > prio) {
805 			_raw_spin_unlock(&irq->irq_lock);
806 			break;
807 		}
808 
809 		if (likely(vgic_target_oracle(irq) == vcpu)) {
810 			vgic_populate_lr(vcpu, irq, count++);
811 
812 			if (irq->source)
813 				prio = irq->priority;
814 		}
815 
816 		raw_spin_unlock(&irq->irq_lock);
817 
818 		if (count == kvm_vgic_global_state.nr_lr) {
819 			if (!list_is_last(&irq->ap_list,
820 					  &vgic_cpu->ap_list_head))
821 				vgic_set_underflow(vcpu);
822 			break;
823 		}
824 	}
825 
826 	/* Nuke remaining LRs */
827 	for (i = count ; i < kvm_vgic_global_state.nr_lr; i++)
828 		vgic_clear_lr(vcpu, i);
829 
830 	if (!static_branch_unlikely(&kvm_vgic_global_state.gicv3_cpuif))
831 		vcpu->arch.vgic_cpu.vgic_v2.used_lrs = count;
832 	else
833 		vcpu->arch.vgic_cpu.vgic_v3.used_lrs = count;
834 }
835 
836 static inline bool can_access_vgic_from_kernel(void)
837 {
838 	/*
839 	 * GICv2 can always be accessed from the kernel because it is
840 	 * memory-mapped, and VHE systems can access GICv3 EL2 system
841 	 * registers.
842 	 */
843 	return !static_branch_unlikely(&kvm_vgic_global_state.gicv3_cpuif) || has_vhe();
844 }
845 
846 static inline void vgic_save_state(struct kvm_vcpu *vcpu)
847 {
848 	if (!static_branch_unlikely(&kvm_vgic_global_state.gicv3_cpuif))
849 		vgic_v2_save_state(vcpu);
850 	else
851 		__vgic_v3_save_state(&vcpu->arch.vgic_cpu.vgic_v3);
852 }
853 
854 /* Sync back the hardware VGIC state into our emulation after a guest's run. */
855 void kvm_vgic_sync_hwstate(struct kvm_vcpu *vcpu)
856 {
857 	int used_lrs;
858 
859 	/* An empty ap_list_head implies used_lrs == 0 */
860 	if (list_empty(&vcpu->arch.vgic_cpu.ap_list_head))
861 		return;
862 
863 	if (can_access_vgic_from_kernel())
864 		vgic_save_state(vcpu);
865 
866 	if (!static_branch_unlikely(&kvm_vgic_global_state.gicv3_cpuif))
867 		used_lrs = vcpu->arch.vgic_cpu.vgic_v2.used_lrs;
868 	else
869 		used_lrs = vcpu->arch.vgic_cpu.vgic_v3.used_lrs;
870 
871 	if (used_lrs)
872 		vgic_fold_lr_state(vcpu);
873 	vgic_prune_ap_list(vcpu);
874 }
875 
876 static inline void vgic_restore_state(struct kvm_vcpu *vcpu)
877 {
878 	if (!static_branch_unlikely(&kvm_vgic_global_state.gicv3_cpuif))
879 		vgic_v2_restore_state(vcpu);
880 	else
881 		__vgic_v3_restore_state(&vcpu->arch.vgic_cpu.vgic_v3);
882 }
883 
884 /* Flush our emulation state into the GIC hardware before entering the guest. */
885 void kvm_vgic_flush_hwstate(struct kvm_vcpu *vcpu)
886 {
887 	/*
888 	 * If there are no virtual interrupts active or pending for this
889 	 * VCPU, then there is no work to do and we can bail out without
890 	 * taking any lock.  There is a potential race with someone injecting
891 	 * interrupts to the VCPU, but it is a benign race as the VCPU will
892 	 * either observe the new interrupt before or after doing this check,
893 	 * and introducing additional synchronization mechanism doesn't change
894 	 * this.
895 	 *
896 	 * Note that we still need to go through the whole thing if anything
897 	 * can be directly injected (GICv4).
898 	 */
899 	if (list_empty(&vcpu->arch.vgic_cpu.ap_list_head) &&
900 	    !vgic_supports_direct_msis(vcpu->kvm))
901 		return;
902 
903 	DEBUG_SPINLOCK_BUG_ON(!irqs_disabled());
904 
905 	if (!list_empty(&vcpu->arch.vgic_cpu.ap_list_head)) {
906 		raw_spin_lock(&vcpu->arch.vgic_cpu.ap_list_lock);
907 		vgic_flush_lr_state(vcpu);
908 		raw_spin_unlock(&vcpu->arch.vgic_cpu.ap_list_lock);
909 	}
910 
911 	if (can_access_vgic_from_kernel())
912 		vgic_restore_state(vcpu);
913 
914 	if (vgic_supports_direct_msis(vcpu->kvm))
915 		vgic_v4_commit(vcpu);
916 }
917 
918 void kvm_vgic_load(struct kvm_vcpu *vcpu)
919 {
920 	if (unlikely(!vgic_initialized(vcpu->kvm)))
921 		return;
922 
923 	if (kvm_vgic_global_state.type == VGIC_V2)
924 		vgic_v2_load(vcpu);
925 	else
926 		vgic_v3_load(vcpu);
927 }
928 
929 void kvm_vgic_put(struct kvm_vcpu *vcpu)
930 {
931 	if (unlikely(!vgic_initialized(vcpu->kvm)))
932 		return;
933 
934 	if (kvm_vgic_global_state.type == VGIC_V2)
935 		vgic_v2_put(vcpu);
936 	else
937 		vgic_v3_put(vcpu);
938 }
939 
940 int kvm_vgic_vcpu_pending_irq(struct kvm_vcpu *vcpu)
941 {
942 	struct vgic_cpu *vgic_cpu = &vcpu->arch.vgic_cpu;
943 	struct vgic_irq *irq;
944 	bool pending = false;
945 	unsigned long flags;
946 	struct vgic_vmcr vmcr;
947 
948 	if (!vcpu->kvm->arch.vgic.enabled)
949 		return false;
950 
951 	if (vcpu->arch.vgic_cpu.vgic_v3.its_vpe.pending_last)
952 		return true;
953 
954 	vgic_get_vmcr(vcpu, &vmcr);
955 
956 	raw_spin_lock_irqsave(&vgic_cpu->ap_list_lock, flags);
957 
958 	list_for_each_entry(irq, &vgic_cpu->ap_list_head, ap_list) {
959 		raw_spin_lock(&irq->irq_lock);
960 		pending = irq_is_pending(irq) && irq->enabled &&
961 			  !irq->active &&
962 			  irq->priority < vmcr.pmr;
963 		raw_spin_unlock(&irq->irq_lock);
964 
965 		if (pending)
966 			break;
967 	}
968 
969 	raw_spin_unlock_irqrestore(&vgic_cpu->ap_list_lock, flags);
970 
971 	return pending;
972 }
973 
974 void vgic_kick_vcpus(struct kvm *kvm)
975 {
976 	struct kvm_vcpu *vcpu;
977 	unsigned long c;
978 
979 	/*
980 	 * We've injected an interrupt, time to find out who deserves
981 	 * a good kick...
982 	 */
983 	kvm_for_each_vcpu(c, vcpu, kvm) {
984 		if (kvm_vgic_vcpu_pending_irq(vcpu)) {
985 			kvm_make_request(KVM_REQ_IRQ_PENDING, vcpu);
986 			kvm_vcpu_kick(vcpu);
987 		}
988 	}
989 }
990 
991 bool kvm_vgic_map_is_active(struct kvm_vcpu *vcpu, unsigned int vintid)
992 {
993 	struct vgic_irq *irq;
994 	bool map_is_active;
995 	unsigned long flags;
996 
997 	if (!vgic_initialized(vcpu->kvm))
998 		return false;
999 
1000 	irq = vgic_get_irq(vcpu->kvm, vcpu, vintid);
1001 	raw_spin_lock_irqsave(&irq->irq_lock, flags);
1002 	map_is_active = irq->hw && irq->active;
1003 	raw_spin_unlock_irqrestore(&irq->irq_lock, flags);
1004 	vgic_put_irq(vcpu->kvm, irq);
1005 
1006 	return map_is_active;
1007 }
1008 
1009 /*
1010  * Level-triggered mapped IRQs are special because we only observe rising
1011  * edges as input to the VGIC.
1012  *
1013  * If the guest never acked the interrupt we have to sample the physical
1014  * line and set the line level, because the device state could have changed
1015  * or we simply need to process the still pending interrupt later.
1016  *
1017  * We could also have entered the guest with the interrupt active+pending.
1018  * On the next exit, we need to re-evaluate the pending state, as it could
1019  * otherwise result in a spurious interrupt by injecting a now potentially
1020  * stale pending state.
1021  *
1022  * If this causes us to lower the level, we have to also clear the physical
1023  * active state, since we will otherwise never be told when the interrupt
1024  * becomes asserted again.
1025  *
1026  * Another case is when the interrupt requires a helping hand on
1027  * deactivation (no HW deactivation, for example).
1028  */
1029 void vgic_irq_handle_resampling(struct vgic_irq *irq,
1030 				bool lr_deactivated, bool lr_pending)
1031 {
1032 	if (vgic_irq_is_mapped_level(irq)) {
1033 		bool resample = false;
1034 
1035 		if (unlikely(vgic_irq_needs_resampling(irq))) {
1036 			resample = !(irq->active || irq->pending_latch);
1037 		} else if (lr_pending || (lr_deactivated && irq->line_level)) {
1038 			irq->line_level = vgic_get_phys_line_level(irq);
1039 			resample = !irq->line_level;
1040 		}
1041 
1042 		if (resample)
1043 			vgic_irq_set_phys_active(irq, false);
1044 	}
1045 }
1046