xref: /linux/arch/arm64/kvm/vgic/vgic-its.c (revision af3a65d20dbfedc2a4779833597ec133fa612e86)
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  * GICv3 ITS emulation
4  *
5  * Copyright (C) 2015,2016 ARM Ltd.
6  * Author: Andre Przywara <andre.przywara@arm.com>
7  */
8 
9 #include <linux/cpu.h>
10 #include <linux/kvm.h>
11 #include <linux/kvm_host.h>
12 #include <linux/interrupt.h>
13 #include <linux/list.h>
14 #include <linux/uaccess.h>
15 #include <linux/list_sort.h>
16 
17 #include <linux/irqchip/arm-gic-v3.h>
18 
19 #include <asm/kvm_emulate.h>
20 #include <asm/kvm_arm.h>
21 #include <asm/kvm_mmu.h>
22 
23 #include "vgic.h"
24 #include "vgic-mmio.h"
25 
26 static struct kvm_device_ops kvm_arm_vgic_its_ops;
27 
28 static int vgic_its_save_tables_v0(struct vgic_its *its);
29 static int vgic_its_restore_tables_v0(struct vgic_its *its);
30 static void vgic_its_commit_v0(struct vgic_its *its);
31 static int update_lpi_config(struct kvm *kvm, struct vgic_irq *irq,
32 			     struct kvm_vcpu *filter_vcpu, bool needs_inv);
33 
34 #define vgic_its_read_entry_lock(i, g, valp, t)				\
35 	({								\
36 		int __sz = vgic_its_get_abi(i)->t##_esz;		\
37 		struct kvm *__k = (i)->dev->kvm;			\
38 		int __ret;						\
39 									\
40 		BUILD_BUG_ON(NR_ITS_ABIS == 1 &&			\
41 			     sizeof(*(valp)) != ABI_0_ESZ);		\
42 		if (NR_ITS_ABIS > 1 &&					\
43 		    KVM_BUG_ON(__sz != sizeof(*(valp)), __k))		\
44 			__ret = -EINVAL;				\
45 		else							\
46 			__ret = kvm_read_guest_lock(__k, (g),		\
47 						    valp, __sz);	\
48 		__ret;							\
49 	})
50 
51 #define vgic_its_write_entry_lock(i, g, val, t)				\
52 	({								\
53 		int __sz = vgic_its_get_abi(i)->t##_esz;		\
54 		struct kvm *__k = (i)->dev->kvm;			\
55 		typeof(val) __v = (val);				\
56 		int __ret;						\
57 									\
58 		BUILD_BUG_ON(NR_ITS_ABIS == 1 &&			\
59 			     sizeof(__v) != ABI_0_ESZ);			\
60 		if (NR_ITS_ABIS > 1 &&					\
61 		    KVM_BUG_ON(__sz != sizeof(__v), __k))		\
62 			__ret = -EINVAL;				\
63 		else							\
64 			__ret = vgic_write_guest_lock(__k, (g),		\
65 						      &__v, __sz);	\
66 		__ret;							\
67 	})
68 
69 /*
70  * Creates a new (reference to a) struct vgic_irq for a given LPI.
71  * If this LPI is already mapped on another ITS, we increase its refcount
72  * and return a pointer to the existing structure.
73  * If this is a "new" LPI, we allocate and initialize a new struct vgic_irq.
74  * This function returns a pointer to the _unlocked_ structure.
75  */
76 static struct vgic_irq *vgic_add_lpi(struct kvm *kvm, u32 intid,
77 				     struct kvm_vcpu *vcpu)
78 {
79 	struct vgic_dist *dist = &kvm->arch.vgic;
80 	struct vgic_irq *irq = vgic_get_irq(kvm, intid), *oldirq;
81 	unsigned long flags;
82 	int ret;
83 
84 	/* In this case there is no put, since we keep the reference. */
85 	if (irq)
86 		return irq;
87 
88 	irq = kzalloc_obj(struct vgic_irq, GFP_KERNEL_ACCOUNT);
89 	if (!irq)
90 		return ERR_PTR(-ENOMEM);
91 
92 	ret = xa_reserve_irq(&dist->lpi_xa, intid, GFP_KERNEL_ACCOUNT);
93 	if (ret) {
94 		kfree(irq);
95 		return ERR_PTR(ret);
96 	}
97 
98 	INIT_LIST_HEAD(&irq->ap_list);
99 	raw_spin_lock_init(&irq->irq_lock);
100 
101 	irq->config = VGIC_CONFIG_EDGE;
102 	refcount_set(&irq->refcount, 1);
103 	irq->intid = intid;
104 	irq->target_vcpu = vcpu;
105 	irq->group = 1;
106 
107 	xa_lock_irqsave(&dist->lpi_xa, flags);
108 
109 	/*
110 	 * There could be a race with another vgic_add_lpi(), so we need to
111 	 * check that we don't add a second list entry with the same LPI.
112 	 */
113 	oldirq = xa_load(&dist->lpi_xa, intid);
114 	if (vgic_try_get_irq_ref(oldirq)) {
115 		/* Someone was faster with adding this LPI, lets use that. */
116 		kfree(irq);
117 		irq = oldirq;
118 	} else {
119 		/*
120 		 * The entry is either empty or contains a dead LPI (refcount=0)
121 		 * from the deferred release path, pending cleanup by
122 		 * vgic_release_deleted_lpis(). Evict and free it if present.
123 		 */
124 		oldirq = __xa_store(&dist->lpi_xa, intid, irq,
125 				    GFP_NOWAIT | __GFP_ACCOUNT);
126 		ret = xa_err(oldirq);
127 		if (ret) {
128 			xa_unlock_irqrestore(&dist->lpi_xa, flags);
129 			kfree(irq);
130 
131 			return ERR_PTR(ret);
132 		}
133 
134 		if (oldirq && !WARN_ON_ONCE(refcount_read(&oldirq->refcount)))
135 			kfree_rcu(oldirq, rcu);
136 	}
137 
138 	xa_unlock_irqrestore(&dist->lpi_xa, flags);
139 
140 	/*
141 	 * We "cache" the configuration table entries in our struct vgic_irq's.
142 	 * However we only have those structs for mapped IRQs, so we read in
143 	 * the respective config data from memory here upon mapping the LPI.
144 	 *
145 	 * Should any of these fail, behave as if we couldn't create the LPI
146 	 * by dropping the refcount and returning the error.
147 	 */
148 	ret = update_lpi_config(kvm, irq, NULL, false);
149 	if (ret) {
150 		vgic_put_irq(kvm, irq);
151 		return ERR_PTR(ret);
152 	}
153 
154 	ret = vgic_v3_lpi_sync_pending_status(kvm, irq);
155 	if (ret) {
156 		vgic_put_irq(kvm, irq);
157 		return ERR_PTR(ret);
158 	}
159 
160 	return irq;
161 }
162 
163 /**
164  * struct vgic_its_abi - ITS abi ops and settings
165  * @cte_esz: collection table entry size
166  * @dte_esz: device table entry size
167  * @ite_esz: interrupt translation table entry size
168  * @save_tables: save the ITS tables into guest RAM
169  * @restore_tables: restore the ITS internal structs from tables
170  *  stored in guest RAM
171  * @commit: initialize the registers which expose the ABI settings,
172  *  especially the entry sizes
173  */
174 struct vgic_its_abi {
175 	int cte_esz;
176 	int dte_esz;
177 	int ite_esz;
178 	int (*save_tables)(struct vgic_its *its);
179 	int (*restore_tables)(struct vgic_its *its);
180 	void (*commit)(struct vgic_its *its);
181 };
182 
183 #define ABI_0_ESZ	8
184 #define ESZ_MAX		ABI_0_ESZ
185 
186 static const struct vgic_its_abi its_table_abi_versions[] = {
187 	[0] = {
188 	 .cte_esz = ABI_0_ESZ,
189 	 .dte_esz = ABI_0_ESZ,
190 	 .ite_esz = ABI_0_ESZ,
191 	 .save_tables = vgic_its_save_tables_v0,
192 	 .restore_tables = vgic_its_restore_tables_v0,
193 	 .commit = vgic_its_commit_v0,
194 	},
195 };
196 
197 #define NR_ITS_ABIS	ARRAY_SIZE(its_table_abi_versions)
198 
199 inline const struct vgic_its_abi *vgic_its_get_abi(struct vgic_its *its)
200 {
201 	return &its_table_abi_versions[its->abi_rev];
202 }
203 
204 static void vgic_its_set_abi(struct vgic_its *its, u32 rev)
205 {
206 	const struct vgic_its_abi *abi;
207 
208 	its->abi_rev = rev;
209 	abi = vgic_its_get_abi(its);
210 	abi->commit(its);
211 }
212 
213 /*
214  * Find and returns a device in the device table for an ITS.
215  * Must be called with the its_lock mutex held.
216  */
217 static struct its_device *find_its_device(struct vgic_its *its, u32 device_id)
218 {
219 	struct its_device *device;
220 
221 	list_for_each_entry(device, &its->device_list, dev_list)
222 		if (device_id == device->device_id)
223 			return device;
224 
225 	return NULL;
226 }
227 
228 /*
229  * Find and returns an interrupt translation table entry (ITTE) for a given
230  * Device ID/Event ID pair on an ITS.
231  * Must be called with the its_lock mutex held.
232  */
233 static struct its_ite *find_ite(struct vgic_its *its, u32 device_id,
234 				  u32 event_id)
235 {
236 	struct its_device *device;
237 	struct its_ite *ite;
238 
239 	device = find_its_device(its, device_id);
240 	if (device == NULL)
241 		return NULL;
242 
243 	list_for_each_entry(ite, &device->itt_head, ite_list)
244 		if (ite->event_id == event_id)
245 			return ite;
246 
247 	return NULL;
248 }
249 
250 /* To be used as an iterator this macro misses the enclosing parentheses */
251 #define for_each_lpi_its(dev, ite, its) \
252 	list_for_each_entry(dev, &(its)->device_list, dev_list) \
253 		list_for_each_entry(ite, &(dev)->itt_head, ite_list)
254 
255 #define GIC_LPI_OFFSET 8192
256 
257 #define VITS_TYPER_IDBITS		16
258 #define VITS_MAX_EVENTID		(BIT(VITS_TYPER_IDBITS) - 1)
259 #define VITS_TYPER_DEVBITS		16
260 #define VITS_MAX_DEVID			(BIT(VITS_TYPER_DEVBITS) - 1)
261 #define VITS_DTE_MAX_DEVID_OFFSET	(BIT(14) - 1)
262 #define VITS_ITE_MAX_EVENTID_OFFSET	(BIT(16) - 1)
263 
264 /*
265  * Finds and returns a collection in the ITS collection table.
266  * Must be called with the its_lock mutex held.
267  */
268 static struct its_collection *find_collection(struct vgic_its *its, int coll_id)
269 {
270 	struct its_collection *collection;
271 
272 	list_for_each_entry(collection, &its->collection_list, coll_list) {
273 		if (coll_id == collection->collection_id)
274 			return collection;
275 	}
276 
277 	return NULL;
278 }
279 
280 #define LPI_PROP_ENABLE_BIT(p)	((p) & LPI_PROP_ENABLED)
281 #define LPI_PROP_PRIORITY(p)	((p) & 0xfc)
282 
283 /*
284  * Reads the configuration data for a given LPI from guest memory and
285  * updates the fields in struct vgic_irq.
286  * If filter_vcpu is not NULL, applies only if the IRQ is targeting this
287  * VCPU. Unconditionally applies if filter_vcpu is NULL.
288  */
289 static int update_lpi_config(struct kvm *kvm, struct vgic_irq *irq,
290 			     struct kvm_vcpu *filter_vcpu, bool needs_inv)
291 {
292 	u64 propbase = GICR_PROPBASER_ADDRESS(kvm->arch.vgic.propbaser);
293 	u8 prop;
294 	int ret;
295 	unsigned long flags;
296 
297 	ret = kvm_read_guest_lock(kvm, propbase + irq->intid - GIC_LPI_OFFSET,
298 				  &prop, 1);
299 
300 	if (ret)
301 		return ret;
302 
303 	raw_spin_lock_irqsave(&irq->irq_lock, flags);
304 
305 	if (!filter_vcpu || filter_vcpu == irq->target_vcpu) {
306 		irq->priority = LPI_PROP_PRIORITY(prop);
307 		irq->enabled = LPI_PROP_ENABLE_BIT(prop);
308 
309 		if (!irq->hw) {
310 			vgic_queue_irq_unlock(kvm, irq, flags);
311 			return 0;
312 		}
313 	}
314 
315 	if (irq->hw)
316 		ret = its_prop_update_vlpi(irq->host_irq, prop, needs_inv);
317 
318 	raw_spin_unlock_irqrestore(&irq->irq_lock, flags);
319 	return ret;
320 }
321 
322 static int update_affinity(struct vgic_irq *irq,
323 			   struct kvm_vcpu *from_vcpu, struct kvm_vcpu *vcpu)
324 {
325 	struct its_vlpi_map map;
326 	int ret;
327 
328 	guard(raw_spinlock_irqsave)(&irq->irq_lock);
329 	if (from_vcpu && irq->target_vcpu != from_vcpu)
330 		return 0;
331 
332 	irq->target_vcpu = vcpu;
333 
334 	if (!irq->hw)
335 		return 0;
336 
337 	ret = its_get_vlpi(irq->host_irq, &map);
338 	if (ret)
339 		return ret;
340 
341 	if (map.vpe)
342 		atomic_dec(&map.vpe->vlpi_count);
343 
344 	map.vpe = &vcpu->arch.vgic_cpu.vgic_v3.its_vpe;
345 	atomic_inc(&map.vpe->vlpi_count);
346 	return its_map_vlpi(irq->host_irq, &map);
347 }
348 
349 static struct kvm_vcpu *collection_to_vcpu(struct kvm *kvm,
350 					   struct its_collection *col)
351 {
352 	return kvm_get_vcpu_by_id(kvm, col->target_addr);
353 }
354 
355 /*
356  * Promotes the ITS view of affinity of an ITTE (which redistributor this LPI
357  * is targeting) to the VGIC's view, which deals with target VCPUs.
358  * Needs to be called whenever either the collection for a LPIs has
359  * changed or the collection itself got retargeted.
360  */
361 static void update_affinity_ite(struct kvm *kvm, struct its_ite *ite)
362 {
363 	struct kvm_vcpu *vcpu;
364 
365 	if (!its_is_collection_mapped(ite->collection))
366 		return;
367 
368 	vcpu = collection_to_vcpu(kvm, ite->collection);
369 	update_affinity(ite->irq, NULL, vcpu);
370 }
371 
372 /*
373  * Updates the target VCPU for every LPI targeting this collection.
374  * Must be called with the its_lock mutex held.
375  */
376 static void update_affinity_collection(struct kvm *kvm, struct vgic_its *its,
377 				       struct its_collection *coll)
378 {
379 	struct its_device *device;
380 	struct its_ite *ite;
381 
382 	for_each_lpi_its(device, ite, its) {
383 		if (ite->collection != coll)
384 			continue;
385 
386 		update_affinity_ite(kvm, ite);
387 	}
388 }
389 
390 static u32 max_lpis_propbaser(u64 propbaser)
391 {
392 	int nr_idbits = (propbaser & 0x1f) + 1;
393 
394 	return 1U << min(nr_idbits, INTERRUPT_ID_BITS_ITS);
395 }
396 
397 /*
398  * Sync the pending table pending bit of LPIs targeting @vcpu
399  * with our own data structures. This relies on the LPI being
400  * mapped before.
401  */
402 static int its_sync_lpi_pending_table(struct kvm_vcpu *vcpu)
403 {
404 	gpa_t pendbase = GICR_PENDBASER_ADDRESS(vcpu->arch.vgic_cpu.pendbaser);
405 	struct vgic_dist *dist = &vcpu->kvm->arch.vgic;
406 	unsigned long intid, flags;
407 	struct vgic_irq *irq;
408 	int last_byte_offset = -1;
409 	int ret = 0;
410 	u8 pendmask;
411 
412 	xa_for_each(&dist->lpi_xa, intid, irq) {
413 		int byte_offset, bit_nr;
414 
415 		byte_offset = intid / BITS_PER_BYTE;
416 		bit_nr = intid % BITS_PER_BYTE;
417 
418 		/*
419 		 * For contiguously allocated LPIs chances are we just read
420 		 * this very same byte in the last iteration. Reuse that.
421 		 */
422 		if (byte_offset != last_byte_offset) {
423 			ret = kvm_read_guest_lock(vcpu->kvm,
424 						  pendbase + byte_offset,
425 						  &pendmask, 1);
426 			if (ret)
427 				return ret;
428 
429 			last_byte_offset = byte_offset;
430 		}
431 
432 		irq = vgic_get_irq(vcpu->kvm, intid);
433 		if (!irq)
434 			continue;
435 
436 		raw_spin_lock_irqsave(&irq->irq_lock, flags);
437 		if (irq->target_vcpu == vcpu)
438 			irq->pending_latch = pendmask & (1U << bit_nr);
439 		vgic_queue_irq_unlock(vcpu->kvm, irq, flags);
440 		vgic_put_irq(vcpu->kvm, irq);
441 	}
442 
443 	return ret;
444 }
445 
446 static unsigned long vgic_mmio_read_its_typer(struct kvm *kvm,
447 					      struct vgic_its *its,
448 					      gpa_t addr, unsigned int len)
449 {
450 	const struct vgic_its_abi *abi = vgic_its_get_abi(its);
451 	u64 reg = GITS_TYPER_PLPIS;
452 
453 	/*
454 	 * We use linear CPU numbers for redistributor addressing,
455 	 * so GITS_TYPER.PTA is 0.
456 	 * Also we force all PROPBASER registers to be the same, so
457 	 * CommonLPIAff is 0 as well.
458 	 * To avoid memory waste in the guest, we keep the number of IDBits and
459 	 * DevBits low - as least for the time being.
460 	 */
461 	reg |= GIC_ENCODE_SZ(VITS_TYPER_DEVBITS, 5) << GITS_TYPER_DEVBITS_SHIFT;
462 	reg |= GIC_ENCODE_SZ(VITS_TYPER_IDBITS, 5) << GITS_TYPER_IDBITS_SHIFT;
463 	reg |= GIC_ENCODE_SZ(abi->ite_esz, 4) << GITS_TYPER_ITT_ENTRY_SIZE_SHIFT;
464 
465 	return extract_bytes(reg, addr & 7, len);
466 }
467 
468 static unsigned long vgic_mmio_read_its_iidr(struct kvm *kvm,
469 					     struct vgic_its *its,
470 					     gpa_t addr, unsigned int len)
471 {
472 	u32 val;
473 
474 	val = (its->abi_rev << GITS_IIDR_REV_SHIFT) & GITS_IIDR_REV_MASK;
475 	val |= (PRODUCT_ID_KVM << GITS_IIDR_PRODUCTID_SHIFT) | IMPLEMENTER_ARM;
476 	return val;
477 }
478 
479 static int vgic_mmio_uaccess_write_its_iidr(struct kvm *kvm,
480 					    struct vgic_its *its,
481 					    gpa_t addr, unsigned int len,
482 					    unsigned long val)
483 {
484 	u32 rev = GITS_IIDR_REV(val);
485 
486 	if (rev >= NR_ITS_ABIS)
487 		return -EINVAL;
488 	vgic_its_set_abi(its, rev);
489 	return 0;
490 }
491 
492 static unsigned long vgic_mmio_read_its_idregs(struct kvm *kvm,
493 					       struct vgic_its *its,
494 					       gpa_t addr, unsigned int len)
495 {
496 	switch (addr & 0xffff) {
497 	case GITS_PIDR0:
498 		return 0x92;	/* part number, bits[7:0] */
499 	case GITS_PIDR1:
500 		return 0xb4;	/* part number, bits[11:8] */
501 	case GITS_PIDR2:
502 		return GIC_PIDR2_ARCH_GICv3 | 0x0b;
503 	case GITS_PIDR4:
504 		return 0x40;	/* This is a 64K software visible page */
505 	/* The following are the ID registers for (any) GIC. */
506 	case GITS_CIDR0:
507 		return 0x0d;
508 	case GITS_CIDR1:
509 		return 0xf0;
510 	case GITS_CIDR2:
511 		return 0x05;
512 	case GITS_CIDR3:
513 		return 0xb1;
514 	}
515 
516 	return 0;
517 }
518 
519 static struct vgic_its *__vgic_doorbell_to_its(struct kvm *kvm, gpa_t db)
520 {
521 	struct kvm_io_device *kvm_io_dev;
522 	struct vgic_io_device *iodev;
523 
524 	guard(srcu)(&kvm->srcu);
525 
526 	kvm_io_dev = kvm_io_bus_get_dev(kvm, KVM_MMIO_BUS, db);
527 	if (!kvm_io_dev)
528 		return ERR_PTR(-EINVAL);
529 
530 	if (kvm_io_dev->ops != &kvm_io_gic_ops)
531 		return ERR_PTR(-EINVAL);
532 
533 	iodev = container_of(kvm_io_dev, struct vgic_io_device, dev);
534 	if (iodev->iodev_type != IODEV_ITS)
535 		return ERR_PTR(-EINVAL);
536 
537 	return iodev->its;
538 }
539 
540 static unsigned long vgic_its_cache_key(u32 devid, u32 eventid)
541 {
542 	return (((unsigned long)devid) << VITS_TYPER_IDBITS) | eventid;
543 
544 }
545 
546 static struct vgic_irq *vgic_its_check_cache(struct kvm *kvm, phys_addr_t db,
547 					     u32 devid, u32 eventid)
548 {
549 	unsigned long cache_key = vgic_its_cache_key(devid, eventid);
550 	struct vgic_its *its;
551 	struct vgic_irq *irq;
552 
553 	if (devid > VITS_MAX_DEVID || eventid > VITS_MAX_EVENTID)
554 		return NULL;
555 
556 	its = __vgic_doorbell_to_its(kvm, db);
557 	if (IS_ERR(its))
558 		return NULL;
559 
560 	rcu_read_lock();
561 
562 	irq = xa_load(&its->translation_cache, cache_key);
563 	if (!vgic_try_get_irq_ref(irq))
564 		irq = NULL;
565 
566 	rcu_read_unlock();
567 
568 	return irq;
569 }
570 
571 static void vgic_its_cache_translation(struct kvm *kvm, struct vgic_its *its,
572 				       u32 devid, u32 eventid,
573 				       struct vgic_irq *irq)
574 {
575 	unsigned long cache_key = vgic_its_cache_key(devid, eventid);
576 	struct vgic_irq *old;
577 
578 	/* Do not cache a directly injected interrupt */
579 	if (irq->hw)
580 		return;
581 
582 	/*
583 	 * The irq refcount is guaranteed to be nonzero while holding the
584 	 * its_lock, as the ITE (and the reference it holds) cannot be freed.
585 	 */
586 	lockdep_assert_held(&its->its_lock);
587 	vgic_get_irq_ref(irq);
588 
589 	old = xa_store(&its->translation_cache, cache_key, irq, GFP_KERNEL_ACCOUNT);
590 
591 	/*
592 	 * Put the reference taken on @irq if the store fails. Intentionally do
593 	 * not return the error as the translation cache is best effort.
594 	 */
595 	if (xa_is_err(old)) {
596 		vgic_put_irq(kvm, irq);
597 		return;
598 	}
599 
600 	/*
601 	 * We could have raced with another CPU caching the same
602 	 * translation behind our back, ensure we don't leak a
603 	 * reference if that is the case.
604 	 */
605 	if (old)
606 		vgic_put_irq(kvm, old);
607 }
608 
609 static void vgic_its_invalidate_cache(struct vgic_its *its)
610 {
611 	struct kvm *kvm = its->dev->kvm;
612 	struct vgic_irq *irq;
613 	unsigned long idx;
614 
615 	xa_for_each(&its->translation_cache, idx, irq) {
616 		/* Only the context that erases the entry drops its cache ref. */
617 		irq = xa_erase(&its->translation_cache, idx);
618 		if (irq)
619 			vgic_put_irq(kvm, irq);
620 	}
621 }
622 
623 void vgic_its_invalidate_all_caches(struct kvm *kvm)
624 {
625 	struct kvm_device *dev;
626 	struct vgic_its *its;
627 
628 	rcu_read_lock();
629 
630 	list_for_each_entry_rcu(dev, &kvm->devices, vm_node) {
631 		if (dev->ops != &kvm_arm_vgic_its_ops)
632 			continue;
633 
634 		its = dev->private;
635 		vgic_its_invalidate_cache(its);
636 	}
637 
638 	rcu_read_unlock();
639 }
640 
641 int vgic_its_resolve_lpi(struct kvm *kvm, struct vgic_its *its,
642 			 u32 devid, u32 eventid, struct vgic_irq **irq)
643 {
644 	struct kvm_vcpu *vcpu;
645 	struct its_ite *ite;
646 
647 	if (!its->enabled)
648 		return -EBUSY;
649 
650 	ite = find_ite(its, devid, eventid);
651 	if (!ite || !its_is_collection_mapped(ite->collection))
652 		return E_ITS_INT_UNMAPPED_INTERRUPT;
653 
654 	vcpu = collection_to_vcpu(kvm, ite->collection);
655 	if (!vcpu)
656 		return E_ITS_INT_UNMAPPED_INTERRUPT;
657 
658 	if (!vgic_lpis_enabled(vcpu))
659 		return -EBUSY;
660 
661 	vgic_its_cache_translation(kvm, its, devid, eventid, ite->irq);
662 
663 	*irq = ite->irq;
664 	return 0;
665 }
666 
667 struct vgic_its *vgic_msi_to_its(struct kvm *kvm, struct kvm_msi *msi)
668 {
669 	u64 address;
670 
671 	if (!vgic_has_its(kvm))
672 		return ERR_PTR(-ENODEV);
673 
674 	if (!(msi->flags & KVM_MSI_VALID_DEVID))
675 		return ERR_PTR(-EINVAL);
676 
677 	address = (u64)msi->address_hi << 32 | msi->address_lo;
678 
679 	return __vgic_doorbell_to_its(kvm, address);
680 }
681 
682 /*
683  * Find the target VCPU and the LPI number for a given devid/eventid pair
684  * and make this IRQ pending, possibly injecting it.
685  * Must be called with the its_lock mutex held.
686  * Returns 0 on success, a positive error value for any ITS mapping
687  * related errors and negative error values for generic errors.
688  */
689 static int vgic_its_trigger_msi(struct kvm *kvm, struct vgic_its *its,
690 				u32 devid, u32 eventid)
691 {
692 	struct vgic_irq *irq = NULL;
693 	unsigned long flags;
694 	int err;
695 
696 	err = vgic_its_resolve_lpi(kvm, its, devid, eventid, &irq);
697 	if (err)
698 		return err;
699 
700 	if (irq->hw)
701 		return irq_set_irqchip_state(irq->host_irq,
702 					     IRQCHIP_STATE_PENDING, true);
703 
704 	raw_spin_lock_irqsave(&irq->irq_lock, flags);
705 	irq->pending_latch = true;
706 	vgic_queue_irq_unlock(kvm, irq, flags);
707 
708 	return 0;
709 }
710 
711 int vgic_its_inject_cached_translation(struct kvm *kvm, struct kvm_msi *msi)
712 {
713 	struct vgic_irq *irq;
714 	unsigned long flags;
715 	phys_addr_t db;
716 
717 	db = (u64)msi->address_hi << 32 | msi->address_lo;
718 	irq = vgic_its_check_cache(kvm, db, msi->devid, msi->data);
719 	if (!irq)
720 		return -EWOULDBLOCK;
721 
722 	raw_spin_lock_irqsave(&irq->irq_lock, flags);
723 	irq->pending_latch = true;
724 	vgic_queue_irq_unlock(kvm, irq, flags);
725 	vgic_put_irq(kvm, irq);
726 
727 	return 0;
728 }
729 
730 /*
731  * Queries the KVM IO bus framework to get the ITS pointer from the given
732  * doorbell address.
733  * We then call vgic_its_trigger_msi() with the decoded data.
734  * According to the KVM_SIGNAL_MSI API description returns 1 on success.
735  */
736 int vgic_its_inject_msi(struct kvm *kvm, struct kvm_msi *msi)
737 {
738 	struct vgic_its *its;
739 	int ret;
740 
741 	if (!vgic_its_inject_cached_translation(kvm, msi))
742 		return 1;
743 
744 	its = vgic_msi_to_its(kvm, msi);
745 	if (IS_ERR(its))
746 		return PTR_ERR(its);
747 
748 	mutex_lock(&its->its_lock);
749 	ret = vgic_its_trigger_msi(kvm, its, msi->devid, msi->data);
750 	mutex_unlock(&its->its_lock);
751 
752 	if (ret < 0)
753 		return ret;
754 
755 	/*
756 	 * KVM_SIGNAL_MSI demands a return value > 0 for success and 0
757 	 * if the guest has blocked the MSI. So we map any LPI mapping
758 	 * related error to that.
759 	 */
760 	if (ret)
761 		return 0;
762 	else
763 		return 1;
764 }
765 
766 /* Requires the its_lock to be held. */
767 static void its_free_ite(struct kvm *kvm, struct its_ite *ite)
768 {
769 	struct vgic_irq *irq = ite->irq;
770 	list_del(&ite->ite_list);
771 
772 	/* This put matches the get in vgic_add_lpi. */
773 	if (irq) {
774 		scoped_guard(raw_spinlock_irqsave, &irq->irq_lock) {
775 			if (irq->hw)
776 				its_unmap_vlpi(ite->irq->host_irq);
777 
778 			irq->hw = false;
779 			irq->mapped = false;
780 		}
781 
782 		vgic_put_irq(kvm, ite->irq);
783 	}
784 
785 	kfree(ite);
786 }
787 
788 /* Mapping one LPI from two events is UNPREDICTABLE: the first ITE keeps it. */
789 static bool vgic_its_map_lpi(struct kvm *kvm, struct its_ite *ite,
790 			     struct vgic_irq *irq, struct kvm_vcpu *vcpu)
791 {
792 	scoped_guard(raw_spinlock_irqsave, &irq->irq_lock) {
793 		if (!irq->mapped) {
794 			irq->mapped = true;
795 			irq->target_vcpu = vcpu;
796 			ite->irq = irq;
797 			return true;
798 		}
799 	}
800 
801 	vgic_put_irq(kvm, irq);
802 	return false;
803 }
804 
805 static u64 its_cmd_mask_field(u64 *its_cmd, int word, int shift, int size)
806 {
807 	return (le64_to_cpu(its_cmd[word]) >> shift) & (BIT_ULL(size) - 1);
808 }
809 
810 #define its_cmd_get_command(cmd)	its_cmd_mask_field(cmd, 0,  0,  8)
811 #define its_cmd_get_deviceid(cmd)	its_cmd_mask_field(cmd, 0, 32, 32)
812 #define its_cmd_get_size(cmd)		(its_cmd_mask_field(cmd, 1,  0,  5) + 1)
813 #define its_cmd_get_id(cmd)		its_cmd_mask_field(cmd, 1,  0, 32)
814 #define its_cmd_get_physical_id(cmd)	its_cmd_mask_field(cmd, 1, 32, 32)
815 #define its_cmd_get_collection(cmd)	its_cmd_mask_field(cmd, 2,  0, 16)
816 #define its_cmd_get_ittaddr(cmd)	(its_cmd_mask_field(cmd, 2,  8, 44) << 8)
817 #define its_cmd_get_target_addr(cmd)	its_cmd_mask_field(cmd, 2, 16, 32)
818 #define its_cmd_get_validbit(cmd)	its_cmd_mask_field(cmd, 2, 63,  1)
819 
820 /*
821  * The DISCARD command frees an Interrupt Translation Table Entry (ITTE).
822  * Must be called with the its_lock mutex held.
823  */
824 static int vgic_its_cmd_handle_discard(struct kvm *kvm, struct vgic_its *its,
825 				       u64 *its_cmd)
826 {
827 	u32 device_id = its_cmd_get_deviceid(its_cmd);
828 	u32 event_id = its_cmd_get_id(its_cmd);
829 	struct its_ite *ite;
830 
831 	ite = find_ite(its, device_id, event_id);
832 	if (ite && its_is_collection_mapped(ite->collection)) {
833 		struct its_device *device = find_its_device(its, device_id);
834 		int ite_esz = vgic_its_get_abi(its)->ite_esz;
835 		gpa_t gpa = device->itt_addr + ite->event_id * ite_esz;
836 		struct vgic_irq *irq = ite->irq;
837 		struct kvm_vcpu *vcpu, *target;
838 
839 		vgic_its_invalidate_cache(its);
840 
841 		/*
842 		 * Only an LPI on a vCPU's AP list can be in its list registers,
843 		 * which the exit path folds back, and that exit moves the LPI
844 		 * to its target vCPU if the target has changed: pause both.
845 		 */
846 		scoped_guard(raw_spinlock_irqsave, &irq->irq_lock) {
847 			vcpu = irq->vcpu;
848 			target = irq->target_vcpu;
849 		}
850 
851 		if (vcpu) {
852 			if (target != vcpu)
853 				kvm_pause_vcpu(target);
854 			kvm_pause_vcpu(vcpu);
855 		}
856 
857 		scoped_guard(raw_spinlock_irqsave, &irq->irq_lock)
858 			irq->pending_latch = false;
859 
860 		if (vcpu) {
861 			kvm_resume_vcpu(vcpu);
862 			if (target != vcpu)
863 				kvm_resume_vcpu(target);
864 		}
865 
866 		its_free_ite(kvm, ite);
867 
868 		return vgic_its_write_entry_lock(its, gpa, 0ULL, ite);
869 	}
870 
871 	return E_ITS_DISCARD_UNMAPPED_INTERRUPT;
872 }
873 
874 /*
875  * The MOVI command moves an ITTE to a different collection.
876  * Must be called with the its_lock mutex held.
877  */
878 static int vgic_its_cmd_handle_movi(struct kvm *kvm, struct vgic_its *its,
879 				    u64 *its_cmd)
880 {
881 	u32 device_id = its_cmd_get_deviceid(its_cmd);
882 	u32 event_id = its_cmd_get_id(its_cmd);
883 	u32 coll_id = its_cmd_get_collection(its_cmd);
884 	struct kvm_vcpu *vcpu;
885 	struct its_ite *ite;
886 	struct its_collection *collection;
887 
888 	ite = find_ite(its, device_id, event_id);
889 	if (!ite)
890 		return E_ITS_MOVI_UNMAPPED_INTERRUPT;
891 
892 	if (!its_is_collection_mapped(ite->collection))
893 		return E_ITS_MOVI_UNMAPPED_COLLECTION;
894 
895 	collection = find_collection(its, coll_id);
896 	if (!its_is_collection_mapped(collection))
897 		return E_ITS_MOVI_UNMAPPED_COLLECTION;
898 
899 	ite->collection = collection;
900 	vcpu = collection_to_vcpu(kvm, collection);
901 
902 	vgic_its_invalidate_cache(its);
903 
904 	return update_affinity(ite->irq, NULL, vcpu);
905 }
906 
907 static bool __is_visible_gfn_locked(struct vgic_its *its, gpa_t gpa)
908 {
909 	gfn_t gfn = gpa >> PAGE_SHIFT;
910 	int idx;
911 	bool ret;
912 
913 	idx = srcu_read_lock(&its->dev->kvm->srcu);
914 	ret = kvm_is_visible_gfn(its->dev->kvm, gfn);
915 	srcu_read_unlock(&its->dev->kvm->srcu, idx);
916 	return ret;
917 }
918 
919 /*
920  * Check whether an ID can be stored into the corresponding guest table.
921  * For a direct table this is pretty easy, but gets a bit nasty for
922  * indirect tables. We check whether the resulting guest physical address
923  * is actually valid (covered by a memslot and guest accessible).
924  * For this we have to read the respective first level entry.
925  */
926 static bool vgic_its_check_id(struct vgic_its *its, u64 baser, u32 id,
927 			      gpa_t *eaddr)
928 {
929 	int l1_tbl_size = GITS_BASER_NR_PAGES(baser) * SZ_64K;
930 	u64 indirect_ptr, type = GITS_BASER_TYPE(baser);
931 	phys_addr_t base = GITS_BASER_ADDR_48_to_52(baser);
932 	int esz = GITS_BASER_ENTRY_SIZE(baser);
933 	int index;
934 
935 	switch (type) {
936 	case GITS_BASER_TYPE_DEVICE:
937 		if (id > VITS_MAX_DEVID)
938 			return false;
939 		break;
940 	case GITS_BASER_TYPE_COLLECTION:
941 		/* as GITS_TYPER.CIL == 0, ITS supports 16-bit collection ID */
942 		if (id >= BIT_ULL(16))
943 			return false;
944 		break;
945 	default:
946 		return false;
947 	}
948 
949 	if (!(baser & GITS_BASER_INDIRECT)) {
950 		phys_addr_t addr;
951 
952 		if (id >= (l1_tbl_size / esz))
953 			return false;
954 
955 		addr = base + id * esz;
956 
957 		if (eaddr)
958 			*eaddr = addr;
959 
960 		return __is_visible_gfn_locked(its, addr);
961 	}
962 
963 	/* calculate and check the index into the 1st level */
964 	index = id / (SZ_64K / esz);
965 	if (index >= (l1_tbl_size / sizeof(u64)))
966 		return false;
967 
968 	/* Each 1st level entry is represented by a 64-bit value. */
969 	if (kvm_read_guest_lock(its->dev->kvm,
970 			   base + index * sizeof(indirect_ptr),
971 			   &indirect_ptr, sizeof(indirect_ptr)))
972 		return false;
973 
974 	indirect_ptr = le64_to_cpu(indirect_ptr);
975 
976 	/* check the valid bit of the first level entry */
977 	if (!(indirect_ptr & BIT_ULL(63)))
978 		return false;
979 
980 	/* Mask the guest physical address and calculate the frame number. */
981 	indirect_ptr &= GENMASK_ULL(51, 16);
982 
983 	/* Find the address of the actual entry */
984 	index = id % (SZ_64K / esz);
985 	indirect_ptr += index * esz;
986 
987 	if (eaddr)
988 		*eaddr = indirect_ptr;
989 
990 	return __is_visible_gfn_locked(its, indirect_ptr);
991 }
992 
993 /*
994  * Check whether an event ID can be stored in the corresponding Interrupt
995  * Translation Table, which starts at device->itt_addr.
996  */
997 static bool vgic_its_check_event_id(struct vgic_its *its, struct its_device *device,
998 		u32 event_id)
999 {
1000 	const struct vgic_its_abi *abi = vgic_its_get_abi(its);
1001 	int ite_esz = abi->ite_esz;
1002 	gpa_t gpa;
1003 
1004 	/* max table size is: BIT_ULL(device->num_eventid_bits) * ite_esz */
1005 	if (event_id >= BIT_ULL(device->num_eventid_bits))
1006 		return false;
1007 
1008 	gpa = device->itt_addr + event_id * ite_esz;
1009 	return __is_visible_gfn_locked(its, gpa);
1010 }
1011 
1012 /*
1013  * Add a new collection into the ITS collection table.
1014  * Returns 0 on success, and a negative error value for generic errors.
1015  */
1016 static int vgic_its_alloc_collection(struct vgic_its *its,
1017 				     struct its_collection **colp,
1018 				     u32 coll_id)
1019 {
1020 	struct its_collection *collection;
1021 
1022 	collection = kzalloc_obj(*collection, GFP_KERNEL_ACCOUNT);
1023 	if (!collection)
1024 		return -ENOMEM;
1025 
1026 	collection->collection_id = coll_id;
1027 	collection->target_addr = COLLECTION_NOT_MAPPED;
1028 
1029 	list_add_tail(&collection->coll_list, &its->collection_list);
1030 	*colp = collection;
1031 
1032 	return 0;
1033 }
1034 
1035 static void vgic_its_free_collection(struct vgic_its *its, u32 coll_id)
1036 {
1037 	struct its_collection *collection;
1038 	struct its_device *device;
1039 	struct its_ite *ite;
1040 
1041 	/*
1042 	 * Clearing the mapping for that collection ID removes the
1043 	 * entry from the list. If there wasn't any before, we can
1044 	 * go home early.
1045 	 */
1046 	collection = find_collection(its, coll_id);
1047 	if (!collection)
1048 		return;
1049 
1050 	for_each_lpi_its(device, ite, its)
1051 		if (ite->collection &&
1052 		    ite->collection->collection_id == coll_id)
1053 			ite->collection = NULL;
1054 
1055 	list_del(&collection->coll_list);
1056 	kfree(collection);
1057 }
1058 
1059 /* Must be called with its_lock mutex held */
1060 static struct its_ite *vgic_its_alloc_ite(struct its_device *device,
1061 					  struct its_collection *collection,
1062 					  u32 event_id)
1063 {
1064 	struct its_ite *ite;
1065 
1066 	ite = kzalloc_obj(*ite, GFP_KERNEL_ACCOUNT);
1067 	if (!ite)
1068 		return ERR_PTR(-ENOMEM);
1069 
1070 	ite->event_id	= event_id;
1071 	ite->collection = collection;
1072 
1073 	list_add_tail(&ite->ite_list, &device->itt_head);
1074 	return ite;
1075 }
1076 
1077 /*
1078  * The MAPTI and MAPI commands map LPIs to ITTEs.
1079  * Must be called with its_lock mutex held.
1080  */
1081 static int vgic_its_cmd_handle_mapi(struct kvm *kvm, struct vgic_its *its,
1082 				    u64 *its_cmd)
1083 {
1084 	u32 device_id = its_cmd_get_deviceid(its_cmd);
1085 	u32 event_id = its_cmd_get_id(its_cmd);
1086 	u32 coll_id = its_cmd_get_collection(its_cmd);
1087 	struct its_ite *ite;
1088 	struct kvm_vcpu *vcpu = NULL;
1089 	struct its_device *device;
1090 	struct its_collection *collection, *new_coll = NULL;
1091 	struct vgic_irq *irq;
1092 	int lpi_nr;
1093 
1094 	device = find_its_device(its, device_id);
1095 	if (!device)
1096 		return E_ITS_MAPTI_UNMAPPED_DEVICE;
1097 
1098 	if (!vgic_its_check_event_id(its, device, event_id))
1099 		return E_ITS_MAPTI_ID_OOR;
1100 
1101 	if (its_cmd_get_command(its_cmd) == GITS_CMD_MAPTI)
1102 		lpi_nr = its_cmd_get_physical_id(its_cmd);
1103 	else
1104 		lpi_nr = event_id;
1105 	if (lpi_nr < GIC_LPI_OFFSET ||
1106 	    lpi_nr >= max_lpis_propbaser(kvm->arch.vgic.propbaser))
1107 		return E_ITS_MAPTI_PHYSICALID_OOR;
1108 
1109 	/* If there is an existing mapping, behavior is UNPREDICTABLE. */
1110 	if (find_ite(its, device_id, event_id))
1111 		return 0;
1112 
1113 	collection = find_collection(its, coll_id);
1114 	if (!collection) {
1115 		int ret;
1116 
1117 		if (!vgic_its_check_id(its, its->baser_coll_table, coll_id, NULL))
1118 			return E_ITS_MAPC_COLLECTION_OOR;
1119 
1120 		ret = vgic_its_alloc_collection(its, &collection, coll_id);
1121 		if (ret)
1122 			return ret;
1123 		new_coll = collection;
1124 	}
1125 
1126 	ite = vgic_its_alloc_ite(device, collection, event_id);
1127 	if (IS_ERR(ite)) {
1128 		if (new_coll)
1129 			vgic_its_free_collection(its, coll_id);
1130 		return PTR_ERR(ite);
1131 	}
1132 
1133 	if (its_is_collection_mapped(collection))
1134 		vcpu = collection_to_vcpu(kvm, collection);
1135 
1136 	irq = vgic_add_lpi(kvm, lpi_nr, vcpu);
1137 	if (!IS_ERR(irq) && !vgic_its_map_lpi(kvm, ite, irq, vcpu))
1138 		irq = ERR_PTR(-EEXIST);
1139 	if (IS_ERR(irq)) {
1140 		if (new_coll)
1141 			vgic_its_free_collection(its, coll_id);
1142 		its_free_ite(kvm, ite);
1143 		return PTR_ERR(irq);
1144 	}
1145 
1146 	return 0;
1147 }
1148 
1149 /* Requires the its_lock to be held. */
1150 static void vgic_its_free_device(struct kvm *kvm, struct vgic_its *its,
1151 				 struct its_device *device)
1152 {
1153 	struct its_ite *ite, *temp;
1154 
1155 	/*
1156 	 * The spec says that unmapping a device with still valid
1157 	 * ITTEs associated is UNPREDICTABLE. We remove all ITTEs,
1158 	 * since we cannot leave the memory unreferenced.
1159 	 */
1160 	list_for_each_entry_safe(ite, temp, &device->itt_head, ite_list)
1161 		its_free_ite(kvm, ite);
1162 
1163 	vgic_its_invalidate_cache(its);
1164 
1165 	list_del(&device->dev_list);
1166 	kfree(device);
1167 }
1168 
1169 /* its lock must be held */
1170 static void vgic_its_free_device_list(struct kvm *kvm, struct vgic_its *its)
1171 {
1172 	struct its_device *cur, *temp;
1173 
1174 	list_for_each_entry_safe(cur, temp, &its->device_list, dev_list)
1175 		vgic_its_free_device(kvm, its, cur);
1176 }
1177 
1178 /* its lock must be held */
1179 static void vgic_its_free_collection_list(struct kvm *kvm, struct vgic_its *its)
1180 {
1181 	struct its_collection *cur, *temp;
1182 
1183 	list_for_each_entry_safe(cur, temp, &its->collection_list, coll_list)
1184 		vgic_its_free_collection(its, cur->collection_id);
1185 }
1186 
1187 /* Must be called with its_lock mutex held */
1188 static struct its_device *vgic_its_alloc_device(struct vgic_its *its,
1189 						u32 device_id, gpa_t itt_addr,
1190 						u8 num_eventid_bits)
1191 {
1192 	struct its_device *device;
1193 
1194 	device = kzalloc_obj(*device, GFP_KERNEL_ACCOUNT);
1195 	if (!device)
1196 		return ERR_PTR(-ENOMEM);
1197 
1198 	device->device_id = device_id;
1199 	device->itt_addr = itt_addr;
1200 	device->num_eventid_bits = num_eventid_bits;
1201 	INIT_LIST_HEAD(&device->itt_head);
1202 
1203 	list_add_tail(&device->dev_list, &its->device_list);
1204 	return device;
1205 }
1206 
1207 /*
1208  * MAPD maps or unmaps a device ID to Interrupt Translation Tables (ITTs).
1209  * Must be called with the its_lock mutex held.
1210  */
1211 static int vgic_its_cmd_handle_mapd(struct kvm *kvm, struct vgic_its *its,
1212 				    u64 *its_cmd)
1213 {
1214 	u32 device_id = its_cmd_get_deviceid(its_cmd);
1215 	bool valid = its_cmd_get_validbit(its_cmd);
1216 	u8 num_eventid_bits = its_cmd_get_size(its_cmd);
1217 	gpa_t itt_addr = its_cmd_get_ittaddr(its_cmd);
1218 	struct its_device *device;
1219 	gpa_t gpa;
1220 
1221 	if (!vgic_its_check_id(its, its->baser_device_table, device_id, &gpa))
1222 		return E_ITS_MAPD_DEVICE_OOR;
1223 
1224 	if (valid && num_eventid_bits > VITS_TYPER_IDBITS)
1225 		return E_ITS_MAPD_ITTSIZE_OOR;
1226 
1227 	device = find_its_device(its, device_id);
1228 
1229 	/*
1230 	 * The spec says that calling MAPD on an already mapped device
1231 	 * invalidates all cached data for this device. We implement this
1232 	 * by removing the mapping and re-establishing it.
1233 	 */
1234 	if (device)
1235 		vgic_its_free_device(kvm, its, device);
1236 
1237 	/*
1238 	 * The spec does not say whether unmapping a not-mapped device
1239 	 * is an error, so we are done in any case.
1240 	 */
1241 	if (!valid)
1242 		return vgic_its_write_entry_lock(its, gpa, 0ULL, dte);
1243 
1244 	device = vgic_its_alloc_device(its, device_id, itt_addr,
1245 				       num_eventid_bits);
1246 
1247 	return PTR_ERR_OR_ZERO(device);
1248 }
1249 
1250 /*
1251  * The MAPC command maps collection IDs to redistributors.
1252  * Must be called with the its_lock mutex held.
1253  */
1254 static int vgic_its_cmd_handle_mapc(struct kvm *kvm, struct vgic_its *its,
1255 				    u64 *its_cmd)
1256 {
1257 	u16 coll_id;
1258 	struct its_collection *collection;
1259 	bool valid;
1260 
1261 	valid = its_cmd_get_validbit(its_cmd);
1262 	coll_id = its_cmd_get_collection(its_cmd);
1263 
1264 	if (!valid) {
1265 		vgic_its_free_collection(its, coll_id);
1266 		vgic_its_invalidate_cache(its);
1267 	} else {
1268 		struct kvm_vcpu *vcpu;
1269 
1270 		vcpu = kvm_get_vcpu_by_id(kvm, its_cmd_get_target_addr(its_cmd));
1271 		if (!vcpu)
1272 			return E_ITS_MAPC_PROCNUM_OOR;
1273 
1274 		collection = find_collection(its, coll_id);
1275 
1276 		if (!collection) {
1277 			int ret;
1278 
1279 			if (!vgic_its_check_id(its, its->baser_coll_table,
1280 						coll_id, NULL))
1281 				return E_ITS_MAPC_COLLECTION_OOR;
1282 
1283 			ret = vgic_its_alloc_collection(its, &collection,
1284 							coll_id);
1285 			if (ret)
1286 				return ret;
1287 			collection->target_addr = vcpu->vcpu_id;
1288 		} else {
1289 			collection->target_addr = vcpu->vcpu_id;
1290 			update_affinity_collection(kvm, its, collection);
1291 		}
1292 	}
1293 
1294 	return 0;
1295 }
1296 
1297 /*
1298  * The CLEAR command removes the pending state for a particular LPI.
1299  * Must be called with the its_lock mutex held.
1300  */
1301 static int vgic_its_cmd_handle_clear(struct kvm *kvm, struct vgic_its *its,
1302 				     u64 *its_cmd)
1303 {
1304 	u32 device_id = its_cmd_get_deviceid(its_cmd);
1305 	u32 event_id = its_cmd_get_id(its_cmd);
1306 	struct its_ite *ite;
1307 
1308 
1309 	ite = find_ite(its, device_id, event_id);
1310 	if (!ite)
1311 		return E_ITS_CLEAR_UNMAPPED_INTERRUPT;
1312 
1313 	ite->irq->pending_latch = false;
1314 
1315 	if (ite->irq->hw)
1316 		return irq_set_irqchip_state(ite->irq->host_irq,
1317 					     IRQCHIP_STATE_PENDING, false);
1318 
1319 	return 0;
1320 }
1321 
1322 int vgic_its_inv_lpi(struct kvm *kvm, struct vgic_irq *irq)
1323 {
1324 	return update_lpi_config(kvm, irq, NULL, true);
1325 }
1326 
1327 /*
1328  * The INV command syncs the configuration bits from the memory table.
1329  * Must be called with the its_lock mutex held.
1330  */
1331 static int vgic_its_cmd_handle_inv(struct kvm *kvm, struct vgic_its *its,
1332 				   u64 *its_cmd)
1333 {
1334 	u32 device_id = its_cmd_get_deviceid(its_cmd);
1335 	u32 event_id = its_cmd_get_id(its_cmd);
1336 	struct its_ite *ite;
1337 
1338 
1339 	ite = find_ite(its, device_id, event_id);
1340 	if (!ite)
1341 		return E_ITS_INV_UNMAPPED_INTERRUPT;
1342 
1343 	return vgic_its_inv_lpi(kvm, ite->irq);
1344 }
1345 
1346 /**
1347  * vgic_its_invall - invalidate all LPIs targeting a given vcpu
1348  * @vcpu: the vcpu for which the RD is targeted by an invalidation
1349  *
1350  * Contrary to the INVALL command, this targets a RD instead of a
1351  * collection, and we don't need to hold the its_lock, since no ITS is
1352  * involved here.
1353  */
1354 int vgic_its_invall(struct kvm_vcpu *vcpu)
1355 {
1356 	struct kvm *kvm = vcpu->kvm;
1357 	struct vgic_dist *dist = &kvm->arch.vgic;
1358 	struct vgic_irq *irq;
1359 	unsigned long intid;
1360 
1361 	xa_for_each(&dist->lpi_xa, intid, irq) {
1362 		irq = vgic_get_irq(kvm, intid);
1363 		if (!irq)
1364 			continue;
1365 
1366 		update_lpi_config(kvm, irq, vcpu, false);
1367 		vgic_put_irq(kvm, irq);
1368 	}
1369 
1370 	if (vcpu->arch.vgic_cpu.vgic_v3.its_vpe.its_vm)
1371 		its_invall_vpe(&vcpu->arch.vgic_cpu.vgic_v3.its_vpe);
1372 
1373 	return 0;
1374 }
1375 
1376 /*
1377  * The INVALL command requests flushing of all IRQ data in this collection.
1378  * Find the VCPU mapped to that collection, then iterate over the VM's list
1379  * of mapped LPIs and update the configuration for each IRQ which targets
1380  * the specified vcpu. The configuration will be read from the in-memory
1381  * configuration table.
1382  * Must be called with the its_lock mutex held.
1383  */
1384 static int vgic_its_cmd_handle_invall(struct kvm *kvm, struct vgic_its *its,
1385 				      u64 *its_cmd)
1386 {
1387 	u32 coll_id = its_cmd_get_collection(its_cmd);
1388 	struct its_collection *collection;
1389 	struct kvm_vcpu *vcpu;
1390 
1391 	collection = find_collection(its, coll_id);
1392 	if (!its_is_collection_mapped(collection))
1393 		return E_ITS_INVALL_UNMAPPED_COLLECTION;
1394 
1395 	vcpu = collection_to_vcpu(kvm, collection);
1396 	vgic_its_invall(vcpu);
1397 
1398 	return 0;
1399 }
1400 
1401 /*
1402  * The MOVALL command moves the pending state of all IRQs targeting one
1403  * redistributor to another. We don't hold the pending state in the VCPUs,
1404  * but in the IRQs instead, so there is really not much to do for us here.
1405  * However the spec says that no IRQ must target the old redistributor
1406  * afterwards, so we make sure that no LPI is using the associated target_vcpu.
1407  * This command affects all LPIs in the system that target that redistributor.
1408  */
1409 static int vgic_its_cmd_handle_movall(struct kvm *kvm, struct vgic_its *its,
1410 				      u64 *its_cmd)
1411 {
1412 	struct vgic_dist *dist = &kvm->arch.vgic;
1413 	struct kvm_vcpu *vcpu1, *vcpu2;
1414 	struct vgic_irq *irq;
1415 	unsigned long intid;
1416 
1417 	/* We advertise GITS_TYPER.PTA==0, making the address the vcpu ID */
1418 	vcpu1 = kvm_get_vcpu_by_id(kvm, its_cmd_get_target_addr(its_cmd));
1419 	vcpu2 = kvm_get_vcpu_by_id(kvm, its_cmd_mask_field(its_cmd, 3, 16, 32));
1420 
1421 	if (!vcpu1 || !vcpu2)
1422 		return E_ITS_MOVALL_PROCNUM_OOR;
1423 
1424 	if (vcpu1 == vcpu2)
1425 		return 0;
1426 
1427 	/*
1428 	 * Bulk operations such as MOVALL are a pain, as they can clash
1429 	 * badly locking-wise with other vcpus entering and exiting the
1430 	 * guest, should they be affected by it. Stopping the guest is a
1431 	 * safer bet to ensure uncontended access and ultimately forward
1432 	 * progress. Yeah...
1433 	 */
1434 	kvm_arm_halt_guest(kvm);
1435 
1436 	xa_for_each(&dist->lpi_xa, intid, irq) {
1437 		irq = vgic_get_irq(kvm, intid);
1438 		if (!irq)
1439 			continue;
1440 
1441 		update_affinity(irq, vcpu1, vcpu2);
1442 
1443 		vgic_put_irq(kvm, irq);
1444 	}
1445 
1446 	vgic_its_invalidate_cache(its);
1447 
1448 	kvm_arm_resume_guest(kvm);
1449 
1450 	return 0;
1451 }
1452 
1453 /*
1454  * The INT command injects the LPI associated with that DevID/EvID pair.
1455  * Must be called with the its_lock mutex held.
1456  */
1457 static int vgic_its_cmd_handle_int(struct kvm *kvm, struct vgic_its *its,
1458 				   u64 *its_cmd)
1459 {
1460 	u32 msi_data = its_cmd_get_id(its_cmd);
1461 	u64 msi_devid = its_cmd_get_deviceid(its_cmd);
1462 
1463 	return vgic_its_trigger_msi(kvm, its, msi_devid, msi_data);
1464 }
1465 
1466 /*
1467  * This function is called with the its_cmd lock held, but the ITS data
1468  * structure lock dropped.
1469  */
1470 static int vgic_its_handle_command(struct kvm *kvm, struct vgic_its *its,
1471 				   u64 *its_cmd)
1472 {
1473 	int ret = -ENODEV;
1474 
1475 	mutex_lock(&its->its_lock);
1476 	switch (its_cmd_get_command(its_cmd)) {
1477 	case GITS_CMD_MAPD:
1478 		ret = vgic_its_cmd_handle_mapd(kvm, its, its_cmd);
1479 		break;
1480 	case GITS_CMD_MAPC:
1481 		ret = vgic_its_cmd_handle_mapc(kvm, its, its_cmd);
1482 		break;
1483 	case GITS_CMD_MAPI:
1484 		ret = vgic_its_cmd_handle_mapi(kvm, its, its_cmd);
1485 		break;
1486 	case GITS_CMD_MAPTI:
1487 		ret = vgic_its_cmd_handle_mapi(kvm, its, its_cmd);
1488 		break;
1489 	case GITS_CMD_MOVI:
1490 		ret = vgic_its_cmd_handle_movi(kvm, its, its_cmd);
1491 		break;
1492 	case GITS_CMD_DISCARD:
1493 		ret = vgic_its_cmd_handle_discard(kvm, its, its_cmd);
1494 		break;
1495 	case GITS_CMD_CLEAR:
1496 		ret = vgic_its_cmd_handle_clear(kvm, its, its_cmd);
1497 		break;
1498 	case GITS_CMD_MOVALL:
1499 		ret = vgic_its_cmd_handle_movall(kvm, its, its_cmd);
1500 		break;
1501 	case GITS_CMD_INT:
1502 		ret = vgic_its_cmd_handle_int(kvm, its, its_cmd);
1503 		break;
1504 	case GITS_CMD_INV:
1505 		ret = vgic_its_cmd_handle_inv(kvm, its, its_cmd);
1506 		break;
1507 	case GITS_CMD_INVALL:
1508 		ret = vgic_its_cmd_handle_invall(kvm, its, its_cmd);
1509 		break;
1510 	case GITS_CMD_SYNC:
1511 		/* we ignore this command: we are in sync all of the time */
1512 		ret = 0;
1513 		break;
1514 	}
1515 	mutex_unlock(&its->its_lock);
1516 
1517 	return ret;
1518 }
1519 
1520 static u64 vgic_sanitise_its_baser(u64 reg)
1521 {
1522 	reg = vgic_sanitise_field(reg, GITS_BASER_SHAREABILITY_MASK,
1523 				  GITS_BASER_SHAREABILITY_SHIFT,
1524 				  vgic_sanitise_shareability);
1525 	reg = vgic_sanitise_field(reg, GITS_BASER_INNER_CACHEABILITY_MASK,
1526 				  GITS_BASER_INNER_CACHEABILITY_SHIFT,
1527 				  vgic_sanitise_inner_cacheability);
1528 	reg = vgic_sanitise_field(reg, GITS_BASER_OUTER_CACHEABILITY_MASK,
1529 				  GITS_BASER_OUTER_CACHEABILITY_SHIFT,
1530 				  vgic_sanitise_outer_cacheability);
1531 
1532 	/* We support only one (ITS) page size: 64K */
1533 	reg = (reg & ~GITS_BASER_PAGE_SIZE_MASK) | GITS_BASER_PAGE_SIZE_64K;
1534 
1535 	return reg;
1536 }
1537 
1538 static u64 vgic_sanitise_its_cbaser(u64 reg)
1539 {
1540 	reg = vgic_sanitise_field(reg, GITS_CBASER_SHAREABILITY_MASK,
1541 				  GITS_CBASER_SHAREABILITY_SHIFT,
1542 				  vgic_sanitise_shareability);
1543 	reg = vgic_sanitise_field(reg, GITS_CBASER_INNER_CACHEABILITY_MASK,
1544 				  GITS_CBASER_INNER_CACHEABILITY_SHIFT,
1545 				  vgic_sanitise_inner_cacheability);
1546 	reg = vgic_sanitise_field(reg, GITS_CBASER_OUTER_CACHEABILITY_MASK,
1547 				  GITS_CBASER_OUTER_CACHEABILITY_SHIFT,
1548 				  vgic_sanitise_outer_cacheability);
1549 
1550 	/* Sanitise the physical address to be 64k aligned. */
1551 	reg &= ~GENMASK_ULL(15, 12);
1552 
1553 	return reg;
1554 }
1555 
1556 static unsigned long vgic_mmio_read_its_cbaser(struct kvm *kvm,
1557 					       struct vgic_its *its,
1558 					       gpa_t addr, unsigned int len)
1559 {
1560 	return extract_bytes(its->cbaser, addr & 7, len);
1561 }
1562 
1563 static void vgic_mmio_write_its_cbaser(struct kvm *kvm, struct vgic_its *its,
1564 				       gpa_t addr, unsigned int len,
1565 				       unsigned long val)
1566 {
1567 	/* When GITS_CTLR.Enable is 1, this register is RO. */
1568 	if (its->enabled)
1569 		return;
1570 
1571 	mutex_lock(&its->cmd_lock);
1572 	its->cbaser = update_64bit_reg(its->cbaser, addr & 7, len, val);
1573 	its->cbaser = vgic_sanitise_its_cbaser(its->cbaser);
1574 	its->creadr = 0;
1575 	/*
1576 	 * CWRITER is architecturally UNKNOWN on reset, but we need to reset
1577 	 * it to CREADR to make sure we start with an empty command buffer.
1578 	 */
1579 	its->cwriter = its->creadr;
1580 	mutex_unlock(&its->cmd_lock);
1581 }
1582 
1583 #define ITS_CMD_BUFFER_SIZE(baser)	((((baser) & 0xff) + 1) << 12)
1584 #define ITS_CMD_SIZE			32
1585 #define ITS_CMD_OFFSET(reg)		((reg) & GENMASK(19, 5))
1586 
1587 /* Must be called with the cmd_lock held. */
1588 static void vgic_its_process_commands(struct kvm *kvm, struct vgic_its *its)
1589 {
1590 	gpa_t cbaser;
1591 	u64 cmd_buf[4];
1592 
1593 	/* Commands are only processed when the ITS is enabled. */
1594 	if (!its->enabled)
1595 		return;
1596 
1597 	cbaser = GITS_CBASER_ADDRESS(its->cbaser);
1598 
1599 	while (its->cwriter != its->creadr) {
1600 		int ret = kvm_read_guest_lock(kvm, cbaser + its->creadr,
1601 					      cmd_buf, ITS_CMD_SIZE);
1602 		/*
1603 		 * If kvm_read_guest() fails, this could be due to the guest
1604 		 * programming a bogus value in CBASER or something else going
1605 		 * wrong from which we cannot easily recover.
1606 		 * According to section 6.3.2 in the GICv3 spec we can just
1607 		 * ignore that command then.
1608 		 */
1609 		if (!ret)
1610 			vgic_its_handle_command(kvm, its, cmd_buf);
1611 
1612 		its->creadr += ITS_CMD_SIZE;
1613 		if (its->creadr == ITS_CMD_BUFFER_SIZE(its->cbaser))
1614 			its->creadr = 0;
1615 	}
1616 }
1617 
1618 /*
1619  * By writing to CWRITER the guest announces new commands to be processed.
1620  * To avoid any races in the first place, we take the its_cmd lock, which
1621  * protects our ring buffer variables, so that there is only one user
1622  * per ITS handling commands at a given time.
1623  */
1624 static void vgic_mmio_write_its_cwriter(struct kvm *kvm, struct vgic_its *its,
1625 					gpa_t addr, unsigned int len,
1626 					unsigned long val)
1627 {
1628 	u64 reg;
1629 
1630 	if (!its)
1631 		return;
1632 
1633 	mutex_lock(&its->cmd_lock);
1634 
1635 	reg = update_64bit_reg(its->cwriter, addr & 7, len, val);
1636 	reg = ITS_CMD_OFFSET(reg);
1637 	if (reg >= ITS_CMD_BUFFER_SIZE(its->cbaser)) {
1638 		mutex_unlock(&its->cmd_lock);
1639 		return;
1640 	}
1641 	its->cwriter = reg;
1642 
1643 	vgic_its_process_commands(kvm, its);
1644 
1645 	mutex_unlock(&its->cmd_lock);
1646 }
1647 
1648 static unsigned long vgic_mmio_read_its_cwriter(struct kvm *kvm,
1649 						struct vgic_its *its,
1650 						gpa_t addr, unsigned int len)
1651 {
1652 	return extract_bytes(its->cwriter, addr & 0x7, len);
1653 }
1654 
1655 static unsigned long vgic_mmio_read_its_creadr(struct kvm *kvm,
1656 					       struct vgic_its *its,
1657 					       gpa_t addr, unsigned int len)
1658 {
1659 	return extract_bytes(its->creadr, addr & 0x7, len);
1660 }
1661 
1662 static int vgic_mmio_uaccess_write_its_creadr(struct kvm *kvm,
1663 					      struct vgic_its *its,
1664 					      gpa_t addr, unsigned int len,
1665 					      unsigned long val)
1666 {
1667 	u32 cmd_offset;
1668 	int ret = 0;
1669 
1670 	mutex_lock(&its->cmd_lock);
1671 
1672 	if (its->enabled) {
1673 		ret = -EBUSY;
1674 		goto out;
1675 	}
1676 
1677 	cmd_offset = ITS_CMD_OFFSET(val);
1678 	if (cmd_offset >= ITS_CMD_BUFFER_SIZE(its->cbaser)) {
1679 		ret = -EINVAL;
1680 		goto out;
1681 	}
1682 
1683 	its->creadr = cmd_offset;
1684 out:
1685 	mutex_unlock(&its->cmd_lock);
1686 	return ret;
1687 }
1688 
1689 #define BASER_INDEX(addr) (((addr) / sizeof(u64)) & 0x7)
1690 static unsigned long vgic_mmio_read_its_baser(struct kvm *kvm,
1691 					      struct vgic_its *its,
1692 					      gpa_t addr, unsigned int len)
1693 {
1694 	u64 reg;
1695 
1696 	switch (BASER_INDEX(addr)) {
1697 	case 0:
1698 		reg = its->baser_device_table;
1699 		break;
1700 	case 1:
1701 		reg = its->baser_coll_table;
1702 		break;
1703 	default:
1704 		reg = 0;
1705 		break;
1706 	}
1707 
1708 	return extract_bytes(reg, addr & 7, len);
1709 }
1710 
1711 #define GITS_BASER_RO_MASK	(GENMASK_ULL(52, 48) | GENMASK_ULL(58, 56))
1712 static void vgic_mmio_write_its_baser(struct kvm *kvm,
1713 				      struct vgic_its *its,
1714 				      gpa_t addr, unsigned int len,
1715 				      unsigned long val)
1716 {
1717 	const struct vgic_its_abi *abi = vgic_its_get_abi(its);
1718 	u64 old, entry_size, table_type;
1719 	u64 reg, *regptr, clearbits = 0;
1720 
1721 	/* When GITS_CTLR.Enable is 1, we ignore write accesses. */
1722 	if (its->enabled)
1723 		return;
1724 
1725 	switch (BASER_INDEX(addr)) {
1726 	case 0:
1727 		regptr = &its->baser_device_table;
1728 		entry_size = abi->dte_esz;
1729 		table_type = GITS_BASER_TYPE_DEVICE;
1730 		break;
1731 	case 1:
1732 		regptr = &its->baser_coll_table;
1733 		entry_size = abi->cte_esz;
1734 		table_type = GITS_BASER_TYPE_COLLECTION;
1735 		clearbits = GITS_BASER_INDIRECT;
1736 		break;
1737 	default:
1738 		return;
1739 	}
1740 
1741 	old = *regptr;
1742 
1743 	reg = update_64bit_reg(old, addr & 7, len, val);
1744 	reg &= ~GITS_BASER_RO_MASK;
1745 	reg &= ~clearbits;
1746 
1747 	reg |= (entry_size - 1) << GITS_BASER_ENTRY_SIZE_SHIFT;
1748 	reg |= table_type << GITS_BASER_TYPE_SHIFT;
1749 	reg = vgic_sanitise_its_baser(reg);
1750 
1751 	*regptr = reg;
1752 
1753 	/* The ITS driver rewrites an unchanged GITS_BASER<n> on resume. */
1754 	if (reg != old) {
1755 		/* Take the its_lock to prevent a race with a save/restore */
1756 		mutex_lock(&its->its_lock);
1757 		switch (table_type) {
1758 		case GITS_BASER_TYPE_DEVICE:
1759 			vgic_its_free_device_list(kvm, its);
1760 			break;
1761 		case GITS_BASER_TYPE_COLLECTION:
1762 			vgic_its_free_collection_list(kvm, its);
1763 			break;
1764 		}
1765 		/* A concurrent injection may have cached a translation. */
1766 		vgic_its_invalidate_cache(its);
1767 		mutex_unlock(&its->its_lock);
1768 	}
1769 }
1770 
1771 static unsigned long vgic_mmio_read_its_ctlr(struct kvm *vcpu,
1772 					     struct vgic_its *its,
1773 					     gpa_t addr, unsigned int len)
1774 {
1775 	u32 reg = 0;
1776 
1777 	mutex_lock(&its->cmd_lock);
1778 	if (its->creadr == its->cwriter)
1779 		reg |= GITS_CTLR_QUIESCENT;
1780 	if (its->enabled)
1781 		reg |= GITS_CTLR_ENABLE;
1782 	mutex_unlock(&its->cmd_lock);
1783 
1784 	return reg;
1785 }
1786 
1787 static void vgic_mmio_write_its_ctlr(struct kvm *kvm, struct vgic_its *its,
1788 				     gpa_t addr, unsigned int len,
1789 				     unsigned long val)
1790 {
1791 	mutex_lock(&its->cmd_lock);
1792 
1793 	/*
1794 	 * It is UNPREDICTABLE to enable the ITS if any of the CBASER or
1795 	 * device/collection BASER are invalid
1796 	 */
1797 	if (!its->enabled && (val & GITS_CTLR_ENABLE) &&
1798 		(!(its->baser_device_table & GITS_BASER_VALID) ||
1799 		 !(its->baser_coll_table & GITS_BASER_VALID) ||
1800 		 !(its->cbaser & GITS_CBASER_VALID)))
1801 		goto out;
1802 
1803 	its->enabled = !!(val & GITS_CTLR_ENABLE);
1804 	if (!its->enabled)
1805 		vgic_its_invalidate_cache(its);
1806 
1807 	/*
1808 	 * Try to process any pending commands. This function bails out early
1809 	 * if the ITS is disabled or no commands have been queued.
1810 	 */
1811 	vgic_its_process_commands(kvm, its);
1812 
1813 out:
1814 	mutex_unlock(&its->cmd_lock);
1815 }
1816 
1817 #define REGISTER_ITS_DESC(off, rd, wr, length, acc)		\
1818 {								\
1819 	.reg_offset = off,					\
1820 	.len = length,						\
1821 	.access_flags = acc,					\
1822 	.its_read = rd,						\
1823 	.its_write = wr,					\
1824 }
1825 
1826 #define REGISTER_ITS_DESC_UACCESS(off, rd, wr, uwr, length, acc)\
1827 {								\
1828 	.reg_offset = off,					\
1829 	.len = length,						\
1830 	.access_flags = acc,					\
1831 	.its_read = rd,						\
1832 	.its_write = wr,					\
1833 	.uaccess_its_write = uwr,				\
1834 }
1835 
1836 static void its_mmio_write_wi(struct kvm *kvm, struct vgic_its *its,
1837 			      gpa_t addr, unsigned int len, unsigned long val)
1838 {
1839 	/* Ignore */
1840 }
1841 
1842 static struct vgic_register_region its_registers[] = {
1843 	REGISTER_ITS_DESC(GITS_CTLR,
1844 		vgic_mmio_read_its_ctlr, vgic_mmio_write_its_ctlr, 4,
1845 		VGIC_ACCESS_32bit),
1846 	REGISTER_ITS_DESC_UACCESS(GITS_IIDR,
1847 		vgic_mmio_read_its_iidr, its_mmio_write_wi,
1848 		vgic_mmio_uaccess_write_its_iidr, 4,
1849 		VGIC_ACCESS_32bit),
1850 	REGISTER_ITS_DESC(GITS_TYPER,
1851 		vgic_mmio_read_its_typer, its_mmio_write_wi, 8,
1852 		VGIC_ACCESS_64bit | VGIC_ACCESS_32bit),
1853 	REGISTER_ITS_DESC(GITS_CBASER,
1854 		vgic_mmio_read_its_cbaser, vgic_mmio_write_its_cbaser, 8,
1855 		VGIC_ACCESS_64bit | VGIC_ACCESS_32bit),
1856 	REGISTER_ITS_DESC(GITS_CWRITER,
1857 		vgic_mmio_read_its_cwriter, vgic_mmio_write_its_cwriter, 8,
1858 		VGIC_ACCESS_64bit | VGIC_ACCESS_32bit),
1859 	REGISTER_ITS_DESC_UACCESS(GITS_CREADR,
1860 		vgic_mmio_read_its_creadr, its_mmio_write_wi,
1861 		vgic_mmio_uaccess_write_its_creadr, 8,
1862 		VGIC_ACCESS_64bit | VGIC_ACCESS_32bit),
1863 	REGISTER_ITS_DESC(GITS_BASER,
1864 		vgic_mmio_read_its_baser, vgic_mmio_write_its_baser, 0x40,
1865 		VGIC_ACCESS_64bit | VGIC_ACCESS_32bit),
1866 	REGISTER_ITS_DESC(GITS_IDREGS_BASE,
1867 		vgic_mmio_read_its_idregs, its_mmio_write_wi, 0x30,
1868 		VGIC_ACCESS_32bit),
1869 };
1870 
1871 /* This is called on setting the LPI enable bit in the redistributor. */
1872 void vgic_enable_lpis(struct kvm_vcpu *vcpu)
1873 {
1874 	if (!(vcpu->arch.vgic_cpu.pendbaser & GICR_PENDBASER_PTZ))
1875 		its_sync_lpi_pending_table(vcpu);
1876 }
1877 
1878 static int vgic_register_its_iodev(struct kvm *kvm, struct vgic_its *its,
1879 				   u64 addr)
1880 {
1881 	struct vgic_io_device *iodev = &its->iodev;
1882 	int ret;
1883 
1884 	mutex_lock(&kvm->slots_lock);
1885 	if (!IS_VGIC_ADDR_UNDEF(its->vgic_its_base)) {
1886 		ret = -EBUSY;
1887 		goto out;
1888 	}
1889 
1890 	its->vgic_its_base = addr;
1891 	iodev->regions = its_registers;
1892 	iodev->nr_regions = ARRAY_SIZE(its_registers);
1893 	kvm_iodevice_init(&iodev->dev, &kvm_io_gic_ops);
1894 
1895 	iodev->base_addr = its->vgic_its_base;
1896 	iodev->iodev_type = IODEV_ITS;
1897 	iodev->its = its;
1898 	ret = kvm_io_bus_register_dev(kvm, KVM_MMIO_BUS, iodev->base_addr,
1899 				      KVM_VGIC_V3_ITS_SIZE, &iodev->dev);
1900 out:
1901 	mutex_unlock(&kvm->slots_lock);
1902 
1903 	return ret;
1904 }
1905 
1906 #define INITIAL_BASER_VALUE						  \
1907 	(GIC_BASER_CACHEABILITY(GITS_BASER, INNER, RaWb)		| \
1908 	 GIC_BASER_CACHEABILITY(GITS_BASER, OUTER, SameAsInner)		| \
1909 	 GIC_BASER_SHAREABILITY(GITS_BASER, InnerShareable)		| \
1910 	 GITS_BASER_PAGE_SIZE_64K)
1911 
1912 #define INITIAL_PROPBASER_VALUE						  \
1913 	(GIC_BASER_CACHEABILITY(GICR_PROPBASER, INNER, RaWb)		| \
1914 	 GIC_BASER_CACHEABILITY(GICR_PROPBASER, OUTER, SameAsInner)	| \
1915 	 GIC_BASER_SHAREABILITY(GICR_PROPBASER, InnerShareable))
1916 
1917 static int vgic_its_create(struct kvm_device *dev, u32 type)
1918 {
1919 	int ret;
1920 	struct vgic_its *its;
1921 
1922 	if (type != KVM_DEV_TYPE_ARM_VGIC_ITS)
1923 		return -ENODEV;
1924 
1925 	its = kzalloc_obj(struct vgic_its, GFP_KERNEL_ACCOUNT);
1926 	if (!its)
1927 		return -ENOMEM;
1928 
1929 	mutex_lock(&dev->kvm->arch.config_lock);
1930 
1931 	/*
1932 	 * Reject creation of a GICv3 ITS if:
1933 	 * - The VM already has a VGIC other than GICv3.
1934 	 * - An existing ITS requires a VGIC model other than GICv3.
1935 	 */
1936 	if ((irqchip_in_kernel(dev->kvm) && !vgic_is_v3(dev->kvm)) ||
1937 	    (dev->kvm->arch.vgic.its_model &&
1938 	     dev->kvm->arch.vgic.its_model != KVM_DEV_TYPE_ARM_VGIC_V3)) {
1939 		mutex_unlock(&dev->kvm->arch.config_lock);
1940 		kfree(its);
1941 		return -ENODEV;
1942 	}
1943 
1944 	if (vgic_initialized(dev->kvm)) {
1945 		ret = vgic_v4_init(dev->kvm);
1946 		if (ret < 0) {
1947 			mutex_unlock(&dev->kvm->arch.config_lock);
1948 			kfree(its);
1949 			return ret;
1950 		}
1951 	}
1952 
1953 	mutex_init(&its->its_lock);
1954 	mutex_init(&its->cmd_lock);
1955 
1956 	/* Yep, even more trickery for lock ordering... */
1957 #ifdef CONFIG_LOCKDEP
1958 	mutex_lock(&its->cmd_lock);
1959 	mutex_lock(&its->its_lock);
1960 	mutex_unlock(&its->its_lock);
1961 	mutex_unlock(&its->cmd_lock);
1962 #endif
1963 
1964 	its->vgic_its_base = VGIC_ADDR_UNDEF;
1965 
1966 	INIT_LIST_HEAD(&its->device_list);
1967 	INIT_LIST_HEAD(&its->collection_list);
1968 	xa_init(&its->translation_cache);
1969 
1970 	dev->kvm->arch.vgic.msis_require_devid = true;
1971 	dev->kvm->arch.vgic.its_model = KVM_DEV_TYPE_ARM_VGIC_V3;
1972 	its->enabled = false;
1973 	its->dev = dev;
1974 
1975 	its->baser_device_table = INITIAL_BASER_VALUE			|
1976 		((u64)GITS_BASER_TYPE_DEVICE << GITS_BASER_TYPE_SHIFT);
1977 	its->baser_coll_table = INITIAL_BASER_VALUE |
1978 		((u64)GITS_BASER_TYPE_COLLECTION << GITS_BASER_TYPE_SHIFT);
1979 	dev->kvm->arch.vgic.propbaser = INITIAL_PROPBASER_VALUE;
1980 	dev->private = its;
1981 
1982 	vgic_its_set_abi(its, NR_ITS_ABIS - 1);
1983 	mutex_unlock(&dev->kvm->arch.config_lock);
1984 	return 0;
1985 }
1986 
1987 static void vgic_its_destroy(struct kvm_device *kvm_dev)
1988 {
1989 	struct kvm *kvm = kvm_dev->kvm;
1990 	struct vgic_its *its = kvm_dev->private;
1991 
1992 	mutex_lock(&its->its_lock);
1993 
1994 	vgic_its_debug_destroy(kvm_dev);
1995 
1996 	vgic_its_free_device_list(kvm, its);
1997 	vgic_its_free_collection_list(kvm, its);
1998 	vgic_its_invalidate_cache(its);
1999 	xa_destroy(&its->translation_cache);
2000 
2001 	mutex_unlock(&its->its_lock);
2002 	kfree(its);
2003 	kfree(kvm_dev);/* alloc by kvm_ioctl_create_device, free by .destroy */
2004 }
2005 
2006 static int vgic_its_has_attr_regs(struct kvm_device *dev,
2007 				  struct kvm_device_attr *attr)
2008 {
2009 	const struct vgic_register_region *region;
2010 	gpa_t offset = attr->attr;
2011 	int align;
2012 
2013 	align = (offset < GITS_TYPER) || (offset >= GITS_PIDR4) ? 0x3 : 0x7;
2014 
2015 	if (offset & align)
2016 		return -EINVAL;
2017 
2018 	region = vgic_find_mmio_region(its_registers,
2019 				       ARRAY_SIZE(its_registers),
2020 				       offset);
2021 	if (!region)
2022 		return -ENXIO;
2023 
2024 	return 0;
2025 }
2026 
2027 static int vgic_its_attr_regs_access(struct kvm_device *dev,
2028 				     struct kvm_device_attr *attr,
2029 				     u64 *reg, bool is_write)
2030 {
2031 	const struct vgic_register_region *region;
2032 	struct vgic_its *its;
2033 	gpa_t addr, offset;
2034 	unsigned int len;
2035 	int align, ret = 0;
2036 
2037 	its = dev->private;
2038 	offset = attr->attr;
2039 
2040 	/*
2041 	 * Although the spec supports upper/lower 32-bit accesses to
2042 	 * 64-bit ITS registers, the userspace ABI requires 64-bit
2043 	 * accesses to all 64-bit wide registers. We therefore only
2044 	 * support 32-bit accesses to GITS_CTLR, GITS_IIDR and GITS ID
2045 	 * registers
2046 	 */
2047 	if ((offset < GITS_TYPER) || (offset >= GITS_PIDR4))
2048 		align = 0x3;
2049 	else
2050 		align = 0x7;
2051 
2052 	if (offset & align)
2053 		return -EINVAL;
2054 
2055 	mutex_lock(&dev->kvm->lock);
2056 
2057 	if (kvm_trylock_all_vcpus(dev->kvm)) {
2058 		mutex_unlock(&dev->kvm->lock);
2059 		return -EBUSY;
2060 	}
2061 
2062 	mutex_lock(&dev->kvm->arch.config_lock);
2063 
2064 	if (IS_VGIC_ADDR_UNDEF(its->vgic_its_base)) {
2065 		ret = -ENXIO;
2066 		goto out;
2067 	}
2068 
2069 	region = vgic_find_mmio_region(its_registers,
2070 				       ARRAY_SIZE(its_registers),
2071 				       offset);
2072 	if (!region) {
2073 		ret = -ENXIO;
2074 		goto out;
2075 	}
2076 
2077 	addr = its->vgic_its_base + offset;
2078 
2079 	len = region->access_flags & VGIC_ACCESS_64bit ? 8 : 4;
2080 
2081 	if (is_write) {
2082 		if (region->uaccess_its_write)
2083 			ret = region->uaccess_its_write(dev->kvm, its, addr,
2084 							len, *reg);
2085 		else
2086 			region->its_write(dev->kvm, its, addr, len, *reg);
2087 	} else {
2088 		*reg = region->its_read(dev->kvm, its, addr, len);
2089 	}
2090 out:
2091 	mutex_unlock(&dev->kvm->arch.config_lock);
2092 	kvm_unlock_all_vcpus(dev->kvm);
2093 	mutex_unlock(&dev->kvm->lock);
2094 	return ret;
2095 }
2096 
2097 static u32 compute_next_devid_offset(struct vgic_its *its, u64 baser,
2098 				     struct its_device *dev)
2099 {
2100 	struct its_device *next = dev;
2101 
2102 	/*
2103 	 * Point at the next device vgic_its_save_device_tables() saves. It
2104 	 * sorts device_list first, so the subtraction cannot underflow.
2105 	 */
2106 	list_for_each_entry_continue(next, &its->device_list, dev_list) {
2107 		if (vgic_its_check_id(its, baser, next->device_id, NULL))
2108 			return min_t(u32, next->device_id - dev->device_id,
2109 				     VITS_DTE_MAX_DEVID_OFFSET);
2110 	}
2111 
2112 	return 0;
2113 }
2114 
2115 static u32 compute_next_eventid_offset(struct list_head *h, struct its_ite *ite)
2116 {
2117 	struct its_ite *next = ite;
2118 
2119 	/* Point at the next ITE that vgic_its_save_ite() stores as valid. */
2120 	list_for_each_entry_continue(next, h, ite_list) {
2121 		if (next->collection)
2122 			return min_t(u32, next->event_id - ite->event_id,
2123 				     VITS_ITE_MAX_EVENTID_OFFSET);
2124 	}
2125 
2126 	return 0;
2127 }
2128 
2129 /**
2130  * typedef entry_fn_t - Callback called on a table entry restore path
2131  * @its: its handle
2132  * @id: id of the entry
2133  * @entry: pointer to the entry
2134  * @opaque: pointer to an opaque data
2135  *
2136  * Return: < 0 on error, 0 if last element was identified, id offset to next
2137  * element otherwise
2138  */
2139 typedef int (*entry_fn_t)(struct vgic_its *its, u32 id, void *entry,
2140 			  void *opaque);
2141 
2142 /**
2143  * scan_its_table - Scan a contiguous table in guest RAM and applies a function
2144  * to each entry
2145  *
2146  * @its: its handle
2147  * @base: base gpa of the table
2148  * @size: size of the table in bytes
2149  * @esz: entry size in bytes
2150  * @start_id: the ID of the first entry in the table
2151  * (non zero for 2d level tables)
2152  * @fn: function to apply on each entry
2153  * @opaque: pointer to opaque data
2154  *
2155  * Return: < 0 on error, 0 if last element was identified, 1 otherwise
2156  * (the last element may not be found on second level tables)
2157  */
2158 static int scan_its_table(struct vgic_its *its, gpa_t base, int size, u32 esz,
2159 			  int start_id, entry_fn_t fn, void *opaque)
2160 {
2161 	struct kvm *kvm = its->dev->kvm;
2162 	unsigned long len = size;
2163 	int id = start_id;
2164 	gpa_t gpa = base;
2165 	char entry[ESZ_MAX];
2166 	int ret;
2167 
2168 	memset(entry, 0, esz);
2169 
2170 	while (true) {
2171 		int next_offset;
2172 		size_t byte_offset;
2173 
2174 		ret = kvm_read_guest_lock(kvm, gpa, entry, esz);
2175 		if (ret)
2176 			return ret;
2177 
2178 		next_offset = fn(its, id, entry, opaque);
2179 		if (next_offset <= 0)
2180 			return next_offset;
2181 
2182 		byte_offset = next_offset * esz;
2183 		if (byte_offset >= len)
2184 			break;
2185 
2186 		id += next_offset;
2187 		gpa += byte_offset;
2188 		len -= byte_offset;
2189 	}
2190 	return 1;
2191 }
2192 
2193 /*
2194  * vgic_its_save_ite - Save an interrupt translation entry at @gpa
2195  */
2196 static int vgic_its_save_ite(struct vgic_its *its, struct its_device *dev,
2197 			      struct its_ite *ite, gpa_t gpa)
2198 {
2199 	u32 next_offset;
2200 	u64 val;
2201 
2202 	/*
2203 	 * MAPC with V=0 and clearing GITS_BASER<coll>.Valid both keep the
2204 	 * ITEs mapped while dropping their collection, and with it the ICID.
2205 	 * Save a zeroed entry, which the restore path reads back as invalid.
2206 	 */
2207 	if (!ite->collection)
2208 		return vgic_its_write_entry_lock(its, gpa, 0ULL, ite);
2209 
2210 	next_offset = compute_next_eventid_offset(&dev->itt_head, ite);
2211 	val = ((u64)next_offset << KVM_ITS_ITE_NEXT_SHIFT) |
2212 	       ((u64)ite->irq->intid << KVM_ITS_ITE_PINTID_SHIFT) |
2213 		ite->collection->collection_id;
2214 	val = cpu_to_le64(val);
2215 
2216 	return vgic_its_write_entry_lock(its, gpa, val, ite);
2217 }
2218 
2219 /**
2220  * vgic_its_restore_ite - restore an interrupt translation entry
2221  *
2222  * @its: its handle
2223  * @event_id: id used for indexing
2224  * @ptr: pointer to the ITE entry
2225  * @opaque: pointer to the its_device
2226  */
2227 static int vgic_its_restore_ite(struct vgic_its *its, u32 event_id,
2228 				void *ptr, void *opaque)
2229 {
2230 	struct its_device *dev = opaque;
2231 	struct its_collection *collection;
2232 	struct kvm *kvm = its->dev->kvm;
2233 	struct kvm_vcpu *vcpu = NULL;
2234 	u64 val;
2235 	u64 *p = (u64 *)ptr;
2236 	struct vgic_irq *irq;
2237 	u32 coll_id, lpi_id;
2238 	struct its_ite *ite;
2239 	u32 offset;
2240 
2241 	val = *p;
2242 
2243 	val = le64_to_cpu(val);
2244 
2245 	coll_id = val & KVM_ITS_ITE_ICID_MASK;
2246 	lpi_id = (val & KVM_ITS_ITE_PINTID_MASK) >> KVM_ITS_ITE_PINTID_SHIFT;
2247 
2248 	if (!lpi_id)
2249 		return 1; /* invalid entry, no choice but to scan next entry */
2250 
2251 	if (lpi_id < VGIC_MIN_LPI)
2252 		return -EINVAL;
2253 
2254 	offset = val >> KVM_ITS_ITE_NEXT_SHIFT;
2255 	if (event_id + offset >= BIT_ULL(dev->num_eventid_bits))
2256 		return -EINVAL;
2257 
2258 	collection = find_collection(its, coll_id);
2259 	if (!collection)
2260 		return -EINVAL;
2261 
2262 	if (!vgic_its_check_event_id(its, dev, event_id))
2263 		return -EINVAL;
2264 
2265 	ite = vgic_its_alloc_ite(dev, collection, event_id);
2266 	if (IS_ERR(ite))
2267 		return PTR_ERR(ite);
2268 
2269 	if (its_is_collection_mapped(collection))
2270 		vcpu = kvm_get_vcpu_by_id(kvm, collection->target_addr);
2271 
2272 	irq = vgic_add_lpi(kvm, lpi_id, vcpu);
2273 	if (IS_ERR(irq)) {
2274 		its_free_ite(kvm, ite);
2275 		return PTR_ERR(irq);
2276 	}
2277 
2278 	/* Drop an ITE whose LPI another ITE maps, as MAPTI does. */
2279 	if (!vgic_its_map_lpi(kvm, ite, irq, vcpu))
2280 		its_free_ite(kvm, ite);
2281 
2282 	return offset;
2283 }
2284 
2285 static int vgic_its_ite_cmp(void *priv, const struct list_head *a,
2286 			    const struct list_head *b)
2287 {
2288 	struct its_ite *itea = container_of(a, struct its_ite, ite_list);
2289 	struct its_ite *iteb = container_of(b, struct its_ite, ite_list);
2290 
2291 	if (itea->event_id < iteb->event_id)
2292 		return -1;
2293 	else
2294 		return 1;
2295 }
2296 
2297 static int vgic_its_save_itt(struct vgic_its *its, struct its_device *device)
2298 {
2299 	const struct vgic_its_abi *abi = vgic_its_get_abi(its);
2300 	gpa_t base = device->itt_addr;
2301 	struct its_ite *ite;
2302 	int ret;
2303 	int ite_esz = abi->ite_esz;
2304 
2305 	list_sort(NULL, &device->itt_head, vgic_its_ite_cmp);
2306 
2307 	list_for_each_entry(ite, &device->itt_head, ite_list) {
2308 		gpa_t gpa = base + ite->event_id * ite_esz;
2309 
2310 		/*
2311 		 * If an LPI carries the HW bit, this means that this
2312 		 * interrupt is controlled by GICv4, and we do not
2313 		 * have direct access to that state without GICv4.1.
2314 		 * Let's simply fail the save operation...
2315 		 */
2316 		if (ite->irq->hw && !kvm_vgic_global_state.has_gicv4_1)
2317 			return -EACCES;
2318 
2319 		ret = vgic_its_save_ite(its, device, ite, gpa);
2320 		if (ret)
2321 			return ret;
2322 	}
2323 	return 0;
2324 }
2325 
2326 /**
2327  * vgic_its_restore_itt - restore the ITT of a device
2328  *
2329  * @its: its handle
2330  * @dev: device handle
2331  *
2332  * Return 0 on success, < 0 on error
2333  */
2334 static int vgic_its_restore_itt(struct vgic_its *its, struct its_device *dev)
2335 {
2336 	const struct vgic_its_abi *abi = vgic_its_get_abi(its);
2337 	gpa_t base = dev->itt_addr;
2338 	int ret;
2339 	int ite_esz = abi->ite_esz;
2340 	size_t max_size = BIT_ULL(dev->num_eventid_bits) * ite_esz;
2341 
2342 	ret = scan_its_table(its, base, max_size, ite_esz, 0,
2343 			     vgic_its_restore_ite, dev);
2344 
2345 	/* scan_its_table returns +1 if all ITEs are invalid */
2346 	if (ret > 0)
2347 		ret = 0;
2348 
2349 	return ret;
2350 }
2351 
2352 /**
2353  * vgic_its_save_dte - Save a device table entry at a given GPA
2354  *
2355  * @its: ITS handle
2356  * @baser: GITS_BASER<dev> the caller is saving against
2357  * @dev: ITS device
2358  * @ptr: GPA
2359  */
2360 static int vgic_its_save_dte(struct vgic_its *its, u64 baser,
2361 			     struct its_device *dev, gpa_t ptr)
2362 {
2363 	u64 val, itt_addr_field;
2364 	u32 next_offset;
2365 
2366 	itt_addr_field = dev->itt_addr >> 8;
2367 	next_offset = compute_next_devid_offset(its, baser, dev);
2368 	val = (1ULL << KVM_ITS_DTE_VALID_SHIFT |
2369 	       ((u64)next_offset << KVM_ITS_DTE_NEXT_SHIFT) |
2370 	       (itt_addr_field << KVM_ITS_DTE_ITTADDR_SHIFT) |
2371 		(dev->num_eventid_bits - 1));
2372 	val = cpu_to_le64(val);
2373 
2374 	return vgic_its_write_entry_lock(its, ptr, val, dte);
2375 }
2376 
2377 /**
2378  * vgic_its_restore_dte - restore a device table entry
2379  *
2380  * @its: its handle
2381  * @id: device id the DTE corresponds to
2382  * @ptr: kernel VA where the 8 byte DTE is located
2383  * @opaque: unused
2384  *
2385  * Return: < 0 on error, 0 if the dte is the last one, id offset to the
2386  * next dte otherwise
2387  */
2388 static int vgic_its_restore_dte(struct vgic_its *its, u32 id,
2389 				void *ptr, void *opaque)
2390 {
2391 	struct its_device *dev;
2392 	u64 baser = its->baser_device_table;
2393 	gpa_t itt_addr;
2394 	u8 num_eventid_bits;
2395 	u64 entry = *(u64 *)ptr;
2396 	bool valid;
2397 	u32 offset;
2398 	int ret;
2399 
2400 	entry = le64_to_cpu(entry);
2401 
2402 	valid = entry >> KVM_ITS_DTE_VALID_SHIFT;
2403 	num_eventid_bits = (entry & KVM_ITS_DTE_SIZE_MASK) + 1;
2404 	itt_addr = ((entry & KVM_ITS_DTE_ITTADDR_MASK)
2405 			>> KVM_ITS_DTE_ITTADDR_SHIFT) << 8;
2406 
2407 	if (!valid)
2408 		return 1;
2409 
2410 	/* dte entry is valid */
2411 	offset = (entry & KVM_ITS_DTE_NEXT_MASK) >> KVM_ITS_DTE_NEXT_SHIFT;
2412 
2413 	/* Mimic the MAPD behaviour and reject invalid EID bits. */
2414 	if (num_eventid_bits > VITS_TYPER_IDBITS)
2415 		return -EINVAL;
2416 
2417 	if (!vgic_its_check_id(its, baser, id, NULL))
2418 		return -EINVAL;
2419 
2420 	dev = vgic_its_alloc_device(its, id, itt_addr, num_eventid_bits);
2421 	if (IS_ERR(dev))
2422 		return PTR_ERR(dev);
2423 
2424 	ret = vgic_its_restore_itt(its, dev);
2425 	if (ret) {
2426 		vgic_its_free_device(its->dev->kvm, its, dev);
2427 		return ret;
2428 	}
2429 
2430 	return offset;
2431 }
2432 
2433 static int vgic_its_device_cmp(void *priv, const struct list_head *a,
2434 			       const struct list_head *b)
2435 {
2436 	struct its_device *deva = container_of(a, struct its_device, dev_list);
2437 	struct its_device *devb = container_of(b, struct its_device, dev_list);
2438 
2439 	if (deva->device_id < devb->device_id)
2440 		return -1;
2441 	else
2442 		return 1;
2443 }
2444 
2445 /*
2446  * vgic_its_save_device_tables - Save the device table and all ITT
2447  * into guest RAM
2448  *
2449  * L1/L2 handling is hidden by vgic_its_check_id() helper which directly
2450  * returns the GPA of the device entry
2451  */
2452 static int vgic_its_save_device_tables(struct vgic_its *its)
2453 {
2454 	u64 baser = its->baser_device_table;
2455 	struct its_device *dev;
2456 
2457 	if (!(baser & GITS_BASER_VALID))
2458 		return 0;
2459 
2460 	list_sort(NULL, &its->device_list, vgic_its_device_cmp);
2461 
2462 	list_for_each_entry(dev, &its->device_list, dev_list) {
2463 		int ret;
2464 		gpa_t eaddr;
2465 
2466 		/* Don't fail a save that userspace must be able to issue. */
2467 		if (!vgic_its_check_id(its, baser,
2468 				       dev->device_id, &eaddr))
2469 			continue;
2470 
2471 		ret = vgic_its_save_itt(its, dev);
2472 		if (ret)
2473 			return ret;
2474 
2475 		ret = vgic_its_save_dte(its, baser, dev, eaddr);
2476 		if (ret)
2477 			return ret;
2478 	}
2479 	return 0;
2480 }
2481 
2482 /**
2483  * handle_l1_dte - callback used for L1 device table entries (2 stage case)
2484  *
2485  * @its: its handle
2486  * @id: index of the entry in the L1 table
2487  * @addr: kernel VA
2488  * @opaque: unused
2489  *
2490  * L1 table entries are scanned by steps of 1 entry
2491  * Return < 0 if error, 0 if last dte was found when scanning the L2
2492  * table, +1 otherwise (meaning next L1 entry must be scanned)
2493  */
2494 static int handle_l1_dte(struct vgic_its *its, u32 id, void *addr,
2495 			 void *opaque)
2496 {
2497 	const struct vgic_its_abi *abi = vgic_its_get_abi(its);
2498 	int l2_start_id = id * (SZ_64K / abi->dte_esz);
2499 	u64 entry = *(u64 *)addr;
2500 	int dte_esz = abi->dte_esz;
2501 	gpa_t gpa;
2502 	int ret;
2503 
2504 	entry = le64_to_cpu(entry);
2505 
2506 	if (!(entry & KVM_ITS_L1E_VALID_MASK))
2507 		return 1;
2508 
2509 	gpa = entry & KVM_ITS_L1E_ADDR_MASK;
2510 
2511 	ret = scan_its_table(its, gpa, SZ_64K, dte_esz,
2512 			     l2_start_id, vgic_its_restore_dte, NULL);
2513 
2514 	return ret;
2515 }
2516 
2517 /*
2518  * vgic_its_restore_device_tables - Restore the device table and all ITT
2519  * from guest RAM to internal data structs
2520  */
2521 static int vgic_its_restore_device_tables(struct vgic_its *its)
2522 {
2523 	const struct vgic_its_abi *abi = vgic_its_get_abi(its);
2524 	u64 baser = its->baser_device_table;
2525 	int l1_esz, ret;
2526 	int l1_tbl_size = GITS_BASER_NR_PAGES(baser) * SZ_64K;
2527 	gpa_t l1_gpa;
2528 
2529 	if (!(baser & GITS_BASER_VALID))
2530 		return 0;
2531 
2532 	l1_gpa = GITS_BASER_ADDR_48_to_52(baser);
2533 
2534 	if (baser & GITS_BASER_INDIRECT) {
2535 		l1_esz = GITS_LVL1_ENTRY_SIZE;
2536 		ret = scan_its_table(its, l1_gpa, l1_tbl_size, l1_esz, 0,
2537 				     handle_l1_dte, NULL);
2538 	} else {
2539 		l1_esz = abi->dte_esz;
2540 		ret = scan_its_table(its, l1_gpa, l1_tbl_size, l1_esz, 0,
2541 				     vgic_its_restore_dte, NULL);
2542 	}
2543 
2544 	/* scan_its_table returns +1 if all entries are invalid */
2545 	if (ret > 0)
2546 		ret = 0;
2547 
2548 	if (ret < 0)
2549 		vgic_its_free_device_list(its->dev->kvm, its);
2550 
2551 	return ret;
2552 }
2553 
2554 static int vgic_its_save_cte(struct vgic_its *its,
2555 			     struct its_collection *collection,
2556 			     gpa_t gpa)
2557 {
2558 	u64 val;
2559 
2560 	val = (1ULL << KVM_ITS_CTE_VALID_SHIFT |
2561 	       ((u64)collection->target_addr << KVM_ITS_CTE_RDBASE_SHIFT) |
2562 	       collection->collection_id);
2563 	val = cpu_to_le64(val);
2564 
2565 	return vgic_its_write_entry_lock(its, gpa, val, cte);
2566 }
2567 
2568 /*
2569  * Restore a collection entry into the ITS collection table.
2570  * Return +1 on success, 0 if the entry was invalid (which should be
2571  * interpreted as end-of-table), and a negative error value for generic errors.
2572  */
2573 static int vgic_its_restore_cte(struct vgic_its *its, gpa_t gpa)
2574 {
2575 	struct its_collection *collection;
2576 	struct kvm *kvm = its->dev->kvm;
2577 	u32 target_addr, coll_id;
2578 	u64 val;
2579 	int ret;
2580 
2581 	ret = vgic_its_read_entry_lock(its, gpa, &val, cte);
2582 	if (ret)
2583 		return ret;
2584 	val = le64_to_cpu(val);
2585 	if (!(val & KVM_ITS_CTE_VALID_MASK))
2586 		return 0;
2587 
2588 	target_addr = (u32)(val >> KVM_ITS_CTE_RDBASE_SHIFT);
2589 	coll_id = val & KVM_ITS_CTE_ICID_MASK;
2590 
2591 	if (target_addr != COLLECTION_NOT_MAPPED &&
2592 	    !kvm_get_vcpu_by_id(kvm, target_addr))
2593 		return -EINVAL;
2594 
2595 	collection = find_collection(its, coll_id);
2596 	if (collection)
2597 		return -EEXIST;
2598 
2599 	if (!vgic_its_check_id(its, its->baser_coll_table, coll_id, NULL))
2600 		return -EINVAL;
2601 
2602 	ret = vgic_its_alloc_collection(its, &collection, coll_id);
2603 	if (ret)
2604 		return ret;
2605 	collection->target_addr = target_addr;
2606 	return 1;
2607 }
2608 
2609 /*
2610  * vgic_its_save_collection_table - Save the collection table into
2611  * guest RAM
2612  */
2613 static int vgic_its_save_collection_table(struct vgic_its *its)
2614 {
2615 	const struct vgic_its_abi *abi = vgic_its_get_abi(its);
2616 	u64 baser = its->baser_coll_table;
2617 	gpa_t gpa = GITS_BASER_ADDR_48_to_52(baser);
2618 	struct its_collection *collection;
2619 	size_t max_size, filled = 0;
2620 	int ret, cte_esz = abi->cte_esz;
2621 
2622 	if (!(baser & GITS_BASER_VALID))
2623 		return 0;
2624 
2625 	max_size = GITS_BASER_NR_PAGES(baser) * SZ_64K;
2626 
2627 	list_for_each_entry(collection, &its->collection_list, coll_list) {
2628 		ret = vgic_its_save_cte(its, collection, gpa);
2629 		if (ret)
2630 			return ret;
2631 		gpa += cte_esz;
2632 		filled += cte_esz;
2633 	}
2634 
2635 	if (filled == max_size)
2636 		return 0;
2637 
2638 	/*
2639 	 * table is not fully filled, add a last dummy element
2640 	 * with valid bit unset
2641 	 */
2642 	return vgic_its_write_entry_lock(its, gpa, 0ULL, cte);
2643 }
2644 
2645 /*
2646  * vgic_its_restore_collection_table - reads the collection table
2647  * in guest memory and restores the ITS internal state. Requires the
2648  * BASER registers to be restored before.
2649  */
2650 static int vgic_its_restore_collection_table(struct vgic_its *its)
2651 {
2652 	const struct vgic_its_abi *abi = vgic_its_get_abi(its);
2653 	u64 baser = its->baser_coll_table;
2654 	int cte_esz = abi->cte_esz;
2655 	size_t max_size, read = 0;
2656 	gpa_t gpa;
2657 	int ret;
2658 
2659 	if (!(baser & GITS_BASER_VALID))
2660 		return 0;
2661 
2662 	gpa = GITS_BASER_ADDR_48_to_52(baser);
2663 
2664 	max_size = GITS_BASER_NR_PAGES(baser) * SZ_64K;
2665 
2666 	while (read < max_size) {
2667 		ret = vgic_its_restore_cte(its, gpa);
2668 		if (ret <= 0)
2669 			break;
2670 		gpa += cte_esz;
2671 		read += cte_esz;
2672 	}
2673 
2674 	if (ret > 0)
2675 		return 0;
2676 
2677 	if (ret < 0)
2678 		vgic_its_free_collection_list(its->dev->kvm, its);
2679 
2680 	return ret;
2681 }
2682 
2683 /*
2684  * vgic_its_save_tables_v0 - Save the ITS tables into guest ARM
2685  * according to v0 ABI
2686  */
2687 static int vgic_its_save_tables_v0(struct vgic_its *its)
2688 {
2689 	int ret;
2690 
2691 	ret = vgic_its_save_device_tables(its);
2692 	if (ret)
2693 		return ret;
2694 
2695 	return vgic_its_save_collection_table(its);
2696 }
2697 
2698 /*
2699  * vgic_its_restore_tables_v0 - Restore the ITS tables from guest RAM
2700  * to internal data structs according to V0 ABI
2701  *
2702  */
2703 static int vgic_its_restore_tables_v0(struct vgic_its *its)
2704 {
2705 	int ret;
2706 
2707 	ret = vgic_its_restore_collection_table(its);
2708 	if (ret)
2709 		return ret;
2710 
2711 	ret = vgic_its_restore_device_tables(its);
2712 	if (ret)
2713 		vgic_its_free_collection_list(its->dev->kvm, its);
2714 	return ret;
2715 }
2716 
2717 static void vgic_its_commit_v0(struct vgic_its *its)
2718 {
2719 	const struct vgic_its_abi *abi;
2720 
2721 	abi = vgic_its_get_abi(its);
2722 	its->baser_coll_table &= ~GITS_BASER_ENTRY_SIZE_MASK;
2723 	its->baser_device_table &= ~GITS_BASER_ENTRY_SIZE_MASK;
2724 
2725 	its->baser_coll_table |= (GIC_ENCODE_SZ(abi->cte_esz, 5)
2726 					<< GITS_BASER_ENTRY_SIZE_SHIFT);
2727 
2728 	its->baser_device_table |= (GIC_ENCODE_SZ(abi->dte_esz, 5)
2729 					<< GITS_BASER_ENTRY_SIZE_SHIFT);
2730 }
2731 
2732 static void vgic_its_reset(struct kvm *kvm, struct vgic_its *its)
2733 {
2734 	/* We need to keep the ABI specific field values */
2735 	its->baser_coll_table &= ~GITS_BASER_VALID;
2736 	its->baser_device_table &= ~GITS_BASER_VALID;
2737 	its->cbaser = 0;
2738 	its->creadr = 0;
2739 	its->cwriter = 0;
2740 	its->enabled = 0;
2741 	vgic_its_free_device_list(kvm, its);
2742 	vgic_its_free_collection_list(kvm, its);
2743 }
2744 
2745 static int vgic_its_has_attr(struct kvm_device *dev,
2746 			     struct kvm_device_attr *attr)
2747 {
2748 	switch (attr->group) {
2749 	case KVM_DEV_ARM_VGIC_GRP_ADDR:
2750 		switch (attr->attr) {
2751 		case KVM_VGIC_ITS_ADDR_TYPE:
2752 			return 0;
2753 		}
2754 		break;
2755 	case KVM_DEV_ARM_VGIC_GRP_CTRL:
2756 		switch (attr->attr) {
2757 		case KVM_DEV_ARM_VGIC_CTRL_INIT:
2758 			return 0;
2759 		case KVM_DEV_ARM_ITS_CTRL_RESET:
2760 			return 0;
2761 		case KVM_DEV_ARM_ITS_SAVE_TABLES:
2762 			return 0;
2763 		case KVM_DEV_ARM_ITS_RESTORE_TABLES:
2764 			return 0;
2765 		}
2766 		break;
2767 	case KVM_DEV_ARM_VGIC_GRP_ITS_REGS:
2768 		return vgic_its_has_attr_regs(dev, attr);
2769 	}
2770 	return -ENXIO;
2771 }
2772 
2773 static int vgic_its_ctrl(struct kvm *kvm, struct vgic_its *its, u64 attr)
2774 {
2775 	const struct vgic_its_abi *abi = vgic_its_get_abi(its);
2776 	int ret = 0;
2777 
2778 	if (attr == KVM_DEV_ARM_VGIC_CTRL_INIT) /* Nothing to do */
2779 		return 0;
2780 
2781 	mutex_lock(&kvm->lock);
2782 
2783 	if (kvm_trylock_all_vcpus(kvm)) {
2784 		mutex_unlock(&kvm->lock);
2785 		return -EBUSY;
2786 	}
2787 
2788 	mutex_lock(&kvm->arch.config_lock);
2789 	mutex_lock(&its->its_lock);
2790 
2791 	switch (attr) {
2792 	case KVM_DEV_ARM_ITS_CTRL_RESET:
2793 		vgic_its_reset(kvm, its);
2794 		break;
2795 	case KVM_DEV_ARM_ITS_SAVE_TABLES:
2796 		ret = abi->save_tables(its);
2797 		break;
2798 	case KVM_DEV_ARM_ITS_RESTORE_TABLES:
2799 		ret = abi->restore_tables(its);
2800 		break;
2801 	default:
2802 		ret = -ENXIO;
2803 		break;
2804 	}
2805 
2806 	mutex_unlock(&its->its_lock);
2807 	mutex_unlock(&kvm->arch.config_lock);
2808 	kvm_unlock_all_vcpus(kvm);
2809 	mutex_unlock(&kvm->lock);
2810 	return ret;
2811 }
2812 
2813 /*
2814  * kvm_arch_allow_write_without_running_vcpu - allow writing guest memory
2815  * without the running VCPU when dirty ring is enabled.
2816  *
2817  * The running VCPU is required to track dirty guest pages when dirty ring
2818  * is enabled. Otherwise, the backup bitmap should be used to track the
2819  * dirty guest pages. When vgic/its tables are being saved, the backup
2820  * bitmap is used to track the dirty guest pages due to the missed running
2821  * VCPU in the period.
2822  */
2823 bool kvm_arch_allow_write_without_running_vcpu(struct kvm *kvm)
2824 {
2825 	struct vgic_dist *dist = &kvm->arch.vgic;
2826 
2827 	return dist->table_write_in_progress;
2828 }
2829 
2830 static int vgic_its_set_attr(struct kvm_device *dev,
2831 			     struct kvm_device_attr *attr)
2832 {
2833 	struct vgic_its *its = dev->private;
2834 	int ret;
2835 
2836 	switch (attr->group) {
2837 	case KVM_DEV_ARM_VGIC_GRP_ADDR: {
2838 		u64 __user *uaddr = (u64 __user *)(long)attr->addr;
2839 		unsigned long type = (unsigned long)attr->attr;
2840 		u64 addr;
2841 
2842 		if (type != KVM_VGIC_ITS_ADDR_TYPE)
2843 			return -ENODEV;
2844 
2845 		if (copy_from_user(&addr, uaddr, sizeof(addr)))
2846 			return -EFAULT;
2847 
2848 		ret = vgic_check_iorange(dev->kvm, its->vgic_its_base,
2849 					 addr, SZ_64K, KVM_VGIC_V3_ITS_SIZE);
2850 		if (ret)
2851 			return ret;
2852 
2853 		ret = vgic_register_its_iodev(dev->kvm, its, addr);
2854 		if (ret)
2855 			return ret;
2856 
2857 		return vgic_its_debug_init(dev);
2858 
2859 	}
2860 	case KVM_DEV_ARM_VGIC_GRP_CTRL:
2861 		return vgic_its_ctrl(dev->kvm, its, attr->attr);
2862 	case KVM_DEV_ARM_VGIC_GRP_ITS_REGS: {
2863 		u64 __user *uaddr = (u64 __user *)(long)attr->addr;
2864 		u64 reg;
2865 
2866 		if (get_user(reg, uaddr))
2867 			return -EFAULT;
2868 
2869 		return vgic_its_attr_regs_access(dev, attr, &reg, true);
2870 	}
2871 	}
2872 	return -ENXIO;
2873 }
2874 
2875 static int vgic_its_get_attr(struct kvm_device *dev,
2876 			     struct kvm_device_attr *attr)
2877 {
2878 	switch (attr->group) {
2879 	case KVM_DEV_ARM_VGIC_GRP_ADDR: {
2880 		struct vgic_its *its = dev->private;
2881 		u64 addr = its->vgic_its_base;
2882 		u64 __user *uaddr = (u64 __user *)(long)attr->addr;
2883 		unsigned long type = (unsigned long)attr->attr;
2884 
2885 		if (type != KVM_VGIC_ITS_ADDR_TYPE)
2886 			return -ENODEV;
2887 
2888 		if (copy_to_user(uaddr, &addr, sizeof(addr)))
2889 			return -EFAULT;
2890 		break;
2891 	}
2892 	case KVM_DEV_ARM_VGIC_GRP_ITS_REGS: {
2893 		u64 __user *uaddr = (u64 __user *)(long)attr->addr;
2894 		u64 reg;
2895 		int ret;
2896 
2897 		ret = vgic_its_attr_regs_access(dev, attr, &reg, false);
2898 		if (ret)
2899 			return ret;
2900 		return put_user(reg, uaddr);
2901 	}
2902 	default:
2903 		return -ENXIO;
2904 	}
2905 
2906 	return 0;
2907 }
2908 
2909 static struct kvm_device_ops kvm_arm_vgic_its_ops = {
2910 	.name = "kvm-arm-vgic-its",
2911 	.create = vgic_its_create,
2912 	.destroy = vgic_its_destroy,
2913 	.set_attr = vgic_its_set_attr,
2914 	.get_attr = vgic_its_get_attr,
2915 	.has_attr = vgic_its_has_attr,
2916 };
2917 
2918 int kvm_vgic_register_its_device(void)
2919 {
2920 	return kvm_register_device_ops(&kvm_arm_vgic_its_ops,
2921 				       KVM_DEV_TYPE_ARM_VGIC_ITS);
2922 }
2923