xref: /linux/arch/arm64/kvm/vgic/vgic-its.c (revision d5a821f66047c2effd06147b84775f9b2ce0f4aa)
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  */
vgic_add_lpi(struct kvm * kvm,u32 intid,struct kvm_vcpu * vcpu)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 
vgic_its_get_abi(struct vgic_its * its)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 
vgic_its_set_abi(struct vgic_its * its,u32 rev)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  */
find_its_device(struct vgic_its * its,u32 device_id)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  */
find_ite(struct vgic_its * its,u32 device_id,u32 event_id)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  */
find_collection(struct vgic_its * its,int coll_id)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  */
update_lpi_config(struct kvm * kvm,struct vgic_irq * irq,struct kvm_vcpu * filter_vcpu,bool needs_inv)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 
update_affinity(struct vgic_irq * irq,struct kvm_vcpu * from_vcpu,struct kvm_vcpu * vcpu)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 
collection_to_vcpu(struct kvm * kvm,struct its_collection * col)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  */
update_affinity_ite(struct kvm * kvm,struct its_ite * ite)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  */
update_affinity_collection(struct kvm * kvm,struct vgic_its * its,struct its_collection * coll)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 
max_lpis_propbaser(u64 propbaser)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  */
its_sync_lpi_pending_table(struct kvm_vcpu * vcpu)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 
vgic_mmio_read_its_typer(struct kvm * kvm,struct vgic_its * its,gpa_t addr,unsigned int len)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 
vgic_mmio_read_its_iidr(struct kvm * kvm,struct vgic_its * its,gpa_t addr,unsigned int len)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 
vgic_mmio_uaccess_write_its_iidr(struct kvm * kvm,struct vgic_its * its,gpa_t addr,unsigned int len,unsigned long val)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 
vgic_mmio_read_its_idregs(struct kvm * kvm,struct vgic_its * its,gpa_t addr,unsigned int len)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 
__vgic_doorbell_to_its(struct kvm * kvm,gpa_t db)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 
vgic_its_cache_key(u32 devid,u32 eventid)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 
vgic_its_check_cache(struct kvm * kvm,phys_addr_t db,u32 devid,u32 eventid)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 
vgic_its_cache_translation(struct kvm * kvm,struct vgic_its * its,u32 devid,u32 eventid,struct vgic_irq * irq)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 
vgic_its_invalidate_cache(struct vgic_its * its)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 
vgic_its_invalidate_all_caches(struct kvm * kvm)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 
vgic_its_resolve_lpi(struct kvm * kvm,struct vgic_its * its,u32 devid,u32 eventid,struct vgic_irq ** irq)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 
vgic_msi_to_its(struct kvm * kvm,struct kvm_msi * msi)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  */
vgic_its_trigger_msi(struct kvm * kvm,struct vgic_its * its,u32 devid,u32 eventid)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 
vgic_its_inject_cached_translation(struct kvm * kvm,struct kvm_msi * msi)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  */
vgic_its_inject_msi(struct kvm * kvm,struct kvm_msi * msi)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. */
its_free_ite(struct kvm * kvm,struct its_ite * ite)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 		}
780 
781 		vgic_put_irq(kvm, ite->irq);
782 	}
783 
784 	kfree(ite);
785 }
786 
its_cmd_mask_field(u64 * its_cmd,int word,int shift,int size)787 static u64 its_cmd_mask_field(u64 *its_cmd, int word, int shift, int size)
788 {
789 	return (le64_to_cpu(its_cmd[word]) >> shift) & (BIT_ULL(size) - 1);
790 }
791 
792 #define its_cmd_get_command(cmd)	its_cmd_mask_field(cmd, 0,  0,  8)
793 #define its_cmd_get_deviceid(cmd)	its_cmd_mask_field(cmd, 0, 32, 32)
794 #define its_cmd_get_size(cmd)		(its_cmd_mask_field(cmd, 1,  0,  5) + 1)
795 #define its_cmd_get_id(cmd)		its_cmd_mask_field(cmd, 1,  0, 32)
796 #define its_cmd_get_physical_id(cmd)	its_cmd_mask_field(cmd, 1, 32, 32)
797 #define its_cmd_get_collection(cmd)	its_cmd_mask_field(cmd, 2,  0, 16)
798 #define its_cmd_get_ittaddr(cmd)	(its_cmd_mask_field(cmd, 2,  8, 44) << 8)
799 #define its_cmd_get_target_addr(cmd)	its_cmd_mask_field(cmd, 2, 16, 32)
800 #define its_cmd_get_validbit(cmd)	its_cmd_mask_field(cmd, 2, 63,  1)
801 
802 /*
803  * The DISCARD command frees an Interrupt Translation Table Entry (ITTE).
804  * Must be called with the its_lock mutex held.
805  */
vgic_its_cmd_handle_discard(struct kvm * kvm,struct vgic_its * its,u64 * its_cmd)806 static int vgic_its_cmd_handle_discard(struct kvm *kvm, struct vgic_its *its,
807 				       u64 *its_cmd)
808 {
809 	u32 device_id = its_cmd_get_deviceid(its_cmd);
810 	u32 event_id = its_cmd_get_id(its_cmd);
811 	struct its_ite *ite;
812 
813 	ite = find_ite(its, device_id, event_id);
814 	if (ite && its_is_collection_mapped(ite->collection)) {
815 		struct its_device *device = find_its_device(its, device_id);
816 		int ite_esz = vgic_its_get_abi(its)->ite_esz;
817 		gpa_t gpa = device->itt_addr + ite->event_id * ite_esz;
818 		/*
819 		 * Though the spec talks about removing the pending state, we
820 		 * don't bother here since we clear the ITTE anyway and the
821 		 * pending state is a property of the ITTE struct.
822 		 */
823 		vgic_its_invalidate_cache(its);
824 
825 		its_free_ite(kvm, ite);
826 
827 		return vgic_its_write_entry_lock(its, gpa, 0ULL, ite);
828 	}
829 
830 	return E_ITS_DISCARD_UNMAPPED_INTERRUPT;
831 }
832 
833 /*
834  * The MOVI command moves an ITTE to a different collection.
835  * Must be called with the its_lock mutex held.
836  */
vgic_its_cmd_handle_movi(struct kvm * kvm,struct vgic_its * its,u64 * its_cmd)837 static int vgic_its_cmd_handle_movi(struct kvm *kvm, struct vgic_its *its,
838 				    u64 *its_cmd)
839 {
840 	u32 device_id = its_cmd_get_deviceid(its_cmd);
841 	u32 event_id = its_cmd_get_id(its_cmd);
842 	u32 coll_id = its_cmd_get_collection(its_cmd);
843 	struct kvm_vcpu *vcpu;
844 	struct its_ite *ite;
845 	struct its_collection *collection;
846 
847 	ite = find_ite(its, device_id, event_id);
848 	if (!ite)
849 		return E_ITS_MOVI_UNMAPPED_INTERRUPT;
850 
851 	if (!its_is_collection_mapped(ite->collection))
852 		return E_ITS_MOVI_UNMAPPED_COLLECTION;
853 
854 	collection = find_collection(its, coll_id);
855 	if (!its_is_collection_mapped(collection))
856 		return E_ITS_MOVI_UNMAPPED_COLLECTION;
857 
858 	ite->collection = collection;
859 	vcpu = collection_to_vcpu(kvm, collection);
860 
861 	vgic_its_invalidate_cache(its);
862 
863 	return update_affinity(ite->irq, NULL, vcpu);
864 }
865 
__is_visible_gfn_locked(struct vgic_its * its,gpa_t gpa)866 static bool __is_visible_gfn_locked(struct vgic_its *its, gpa_t gpa)
867 {
868 	gfn_t gfn = gpa >> PAGE_SHIFT;
869 	int idx;
870 	bool ret;
871 
872 	idx = srcu_read_lock(&its->dev->kvm->srcu);
873 	ret = kvm_is_visible_gfn(its->dev->kvm, gfn);
874 	srcu_read_unlock(&its->dev->kvm->srcu, idx);
875 	return ret;
876 }
877 
878 /*
879  * Check whether an ID can be stored into the corresponding guest table.
880  * For a direct table this is pretty easy, but gets a bit nasty for
881  * indirect tables. We check whether the resulting guest physical address
882  * is actually valid (covered by a memslot and guest accessible).
883  * For this we have to read the respective first level entry.
884  */
vgic_its_check_id(struct vgic_its * its,u64 baser,u32 id,gpa_t * eaddr)885 static bool vgic_its_check_id(struct vgic_its *its, u64 baser, u32 id,
886 			      gpa_t *eaddr)
887 {
888 	int l1_tbl_size = GITS_BASER_NR_PAGES(baser) * SZ_64K;
889 	u64 indirect_ptr, type = GITS_BASER_TYPE(baser);
890 	phys_addr_t base = GITS_BASER_ADDR_48_to_52(baser);
891 	int esz = GITS_BASER_ENTRY_SIZE(baser);
892 	int index;
893 
894 	switch (type) {
895 	case GITS_BASER_TYPE_DEVICE:
896 		if (id > VITS_MAX_DEVID)
897 			return false;
898 		break;
899 	case GITS_BASER_TYPE_COLLECTION:
900 		/* as GITS_TYPER.CIL == 0, ITS supports 16-bit collection ID */
901 		if (id >= BIT_ULL(16))
902 			return false;
903 		break;
904 	default:
905 		return false;
906 	}
907 
908 	if (!(baser & GITS_BASER_INDIRECT)) {
909 		phys_addr_t addr;
910 
911 		if (id >= (l1_tbl_size / esz))
912 			return false;
913 
914 		addr = base + id * esz;
915 
916 		if (eaddr)
917 			*eaddr = addr;
918 
919 		return __is_visible_gfn_locked(its, addr);
920 	}
921 
922 	/* calculate and check the index into the 1st level */
923 	index = id / (SZ_64K / esz);
924 	if (index >= (l1_tbl_size / sizeof(u64)))
925 		return false;
926 
927 	/* Each 1st level entry is represented by a 64-bit value. */
928 	if (kvm_read_guest_lock(its->dev->kvm,
929 			   base + index * sizeof(indirect_ptr),
930 			   &indirect_ptr, sizeof(indirect_ptr)))
931 		return false;
932 
933 	indirect_ptr = le64_to_cpu(indirect_ptr);
934 
935 	/* check the valid bit of the first level entry */
936 	if (!(indirect_ptr & BIT_ULL(63)))
937 		return false;
938 
939 	/* Mask the guest physical address and calculate the frame number. */
940 	indirect_ptr &= GENMASK_ULL(51, 16);
941 
942 	/* Find the address of the actual entry */
943 	index = id % (SZ_64K / esz);
944 	indirect_ptr += index * esz;
945 
946 	if (eaddr)
947 		*eaddr = indirect_ptr;
948 
949 	return __is_visible_gfn_locked(its, indirect_ptr);
950 }
951 
952 /*
953  * Check whether an event ID can be stored in the corresponding Interrupt
954  * Translation Table, which starts at device->itt_addr.
955  */
vgic_its_check_event_id(struct vgic_its * its,struct its_device * device,u32 event_id)956 static bool vgic_its_check_event_id(struct vgic_its *its, struct its_device *device,
957 		u32 event_id)
958 {
959 	const struct vgic_its_abi *abi = vgic_its_get_abi(its);
960 	int ite_esz = abi->ite_esz;
961 	gpa_t gpa;
962 
963 	/* max table size is: BIT_ULL(device->num_eventid_bits) * ite_esz */
964 	if (event_id >= BIT_ULL(device->num_eventid_bits))
965 		return false;
966 
967 	gpa = device->itt_addr + event_id * ite_esz;
968 	return __is_visible_gfn_locked(its, gpa);
969 }
970 
971 /*
972  * Add a new collection into the ITS collection table.
973  * Returns 0 on success, and a negative error value for generic errors.
974  */
vgic_its_alloc_collection(struct vgic_its * its,struct its_collection ** colp,u32 coll_id)975 static int vgic_its_alloc_collection(struct vgic_its *its,
976 				     struct its_collection **colp,
977 				     u32 coll_id)
978 {
979 	struct its_collection *collection;
980 
981 	collection = kzalloc_obj(*collection, GFP_KERNEL_ACCOUNT);
982 	if (!collection)
983 		return -ENOMEM;
984 
985 	collection->collection_id = coll_id;
986 	collection->target_addr = COLLECTION_NOT_MAPPED;
987 
988 	list_add_tail(&collection->coll_list, &its->collection_list);
989 	*colp = collection;
990 
991 	return 0;
992 }
993 
vgic_its_free_collection(struct vgic_its * its,u32 coll_id)994 static void vgic_its_free_collection(struct vgic_its *its, u32 coll_id)
995 {
996 	struct its_collection *collection;
997 	struct its_device *device;
998 	struct its_ite *ite;
999 
1000 	/*
1001 	 * Clearing the mapping for that collection ID removes the
1002 	 * entry from the list. If there wasn't any before, we can
1003 	 * go home early.
1004 	 */
1005 	collection = find_collection(its, coll_id);
1006 	if (!collection)
1007 		return;
1008 
1009 	for_each_lpi_its(device, ite, its)
1010 		if (ite->collection &&
1011 		    ite->collection->collection_id == coll_id)
1012 			ite->collection = NULL;
1013 
1014 	list_del(&collection->coll_list);
1015 	kfree(collection);
1016 }
1017 
1018 /* Must be called with its_lock mutex held */
vgic_its_alloc_ite(struct its_device * device,struct its_collection * collection,u32 event_id)1019 static struct its_ite *vgic_its_alloc_ite(struct its_device *device,
1020 					  struct its_collection *collection,
1021 					  u32 event_id)
1022 {
1023 	struct its_ite *ite;
1024 
1025 	ite = kzalloc_obj(*ite, GFP_KERNEL_ACCOUNT);
1026 	if (!ite)
1027 		return ERR_PTR(-ENOMEM);
1028 
1029 	ite->event_id	= event_id;
1030 	ite->collection = collection;
1031 
1032 	list_add_tail(&ite->ite_list, &device->itt_head);
1033 	return ite;
1034 }
1035 
1036 /*
1037  * The MAPTI and MAPI commands map LPIs to ITTEs.
1038  * Must be called with its_lock mutex held.
1039  */
vgic_its_cmd_handle_mapi(struct kvm * kvm,struct vgic_its * its,u64 * its_cmd)1040 static int vgic_its_cmd_handle_mapi(struct kvm *kvm, struct vgic_its *its,
1041 				    u64 *its_cmd)
1042 {
1043 	u32 device_id = its_cmd_get_deviceid(its_cmd);
1044 	u32 event_id = its_cmd_get_id(its_cmd);
1045 	u32 coll_id = its_cmd_get_collection(its_cmd);
1046 	struct its_ite *ite;
1047 	struct kvm_vcpu *vcpu = NULL;
1048 	struct its_device *device;
1049 	struct its_collection *collection, *new_coll = NULL;
1050 	struct vgic_irq *irq;
1051 	int lpi_nr;
1052 
1053 	device = find_its_device(its, device_id);
1054 	if (!device)
1055 		return E_ITS_MAPTI_UNMAPPED_DEVICE;
1056 
1057 	if (!vgic_its_check_event_id(its, device, event_id))
1058 		return E_ITS_MAPTI_ID_OOR;
1059 
1060 	if (its_cmd_get_command(its_cmd) == GITS_CMD_MAPTI)
1061 		lpi_nr = its_cmd_get_physical_id(its_cmd);
1062 	else
1063 		lpi_nr = event_id;
1064 	if (lpi_nr < GIC_LPI_OFFSET ||
1065 	    lpi_nr >= max_lpis_propbaser(kvm->arch.vgic.propbaser))
1066 		return E_ITS_MAPTI_PHYSICALID_OOR;
1067 
1068 	/* If there is an existing mapping, behavior is UNPREDICTABLE. */
1069 	if (find_ite(its, device_id, event_id))
1070 		return 0;
1071 
1072 	collection = find_collection(its, coll_id);
1073 	if (!collection) {
1074 		int ret;
1075 
1076 		if (!vgic_its_check_id(its, its->baser_coll_table, coll_id, NULL))
1077 			return E_ITS_MAPC_COLLECTION_OOR;
1078 
1079 		ret = vgic_its_alloc_collection(its, &collection, coll_id);
1080 		if (ret)
1081 			return ret;
1082 		new_coll = collection;
1083 	}
1084 
1085 	ite = vgic_its_alloc_ite(device, collection, event_id);
1086 	if (IS_ERR(ite)) {
1087 		if (new_coll)
1088 			vgic_its_free_collection(its, coll_id);
1089 		return PTR_ERR(ite);
1090 	}
1091 
1092 	if (its_is_collection_mapped(collection))
1093 		vcpu = collection_to_vcpu(kvm, collection);
1094 
1095 	irq = vgic_add_lpi(kvm, lpi_nr, vcpu);
1096 	if (IS_ERR(irq)) {
1097 		if (new_coll)
1098 			vgic_its_free_collection(its, coll_id);
1099 		its_free_ite(kvm, ite);
1100 		return PTR_ERR(irq);
1101 	}
1102 	ite->irq = irq;
1103 
1104 	return 0;
1105 }
1106 
1107 /* Requires the its_lock to be held. */
vgic_its_free_device(struct kvm * kvm,struct vgic_its * its,struct its_device * device)1108 static void vgic_its_free_device(struct kvm *kvm, struct vgic_its *its,
1109 				 struct its_device *device)
1110 {
1111 	struct its_ite *ite, *temp;
1112 
1113 	/*
1114 	 * The spec says that unmapping a device with still valid
1115 	 * ITTEs associated is UNPREDICTABLE. We remove all ITTEs,
1116 	 * since we cannot leave the memory unreferenced.
1117 	 */
1118 	list_for_each_entry_safe(ite, temp, &device->itt_head, ite_list)
1119 		its_free_ite(kvm, ite);
1120 
1121 	vgic_its_invalidate_cache(its);
1122 
1123 	list_del(&device->dev_list);
1124 	kfree(device);
1125 }
1126 
1127 /* its lock must be held */
vgic_its_free_device_list(struct kvm * kvm,struct vgic_its * its)1128 static void vgic_its_free_device_list(struct kvm *kvm, struct vgic_its *its)
1129 {
1130 	struct its_device *cur, *temp;
1131 
1132 	list_for_each_entry_safe(cur, temp, &its->device_list, dev_list)
1133 		vgic_its_free_device(kvm, its, cur);
1134 }
1135 
1136 /* its lock must be held */
vgic_its_free_collection_list(struct kvm * kvm,struct vgic_its * its)1137 static void vgic_its_free_collection_list(struct kvm *kvm, struct vgic_its *its)
1138 {
1139 	struct its_collection *cur, *temp;
1140 
1141 	list_for_each_entry_safe(cur, temp, &its->collection_list, coll_list)
1142 		vgic_its_free_collection(its, cur->collection_id);
1143 }
1144 
1145 /* Must be called with its_lock mutex held */
vgic_its_alloc_device(struct vgic_its * its,u32 device_id,gpa_t itt_addr,u8 num_eventid_bits)1146 static struct its_device *vgic_its_alloc_device(struct vgic_its *its,
1147 						u32 device_id, gpa_t itt_addr,
1148 						u8 num_eventid_bits)
1149 {
1150 	struct its_device *device;
1151 
1152 	device = kzalloc_obj(*device, GFP_KERNEL_ACCOUNT);
1153 	if (!device)
1154 		return ERR_PTR(-ENOMEM);
1155 
1156 	device->device_id = device_id;
1157 	device->itt_addr = itt_addr;
1158 	device->num_eventid_bits = num_eventid_bits;
1159 	INIT_LIST_HEAD(&device->itt_head);
1160 
1161 	list_add_tail(&device->dev_list, &its->device_list);
1162 	return device;
1163 }
1164 
1165 /*
1166  * MAPD maps or unmaps a device ID to Interrupt Translation Tables (ITTs).
1167  * Must be called with the its_lock mutex held.
1168  */
vgic_its_cmd_handle_mapd(struct kvm * kvm,struct vgic_its * its,u64 * its_cmd)1169 static int vgic_its_cmd_handle_mapd(struct kvm *kvm, struct vgic_its *its,
1170 				    u64 *its_cmd)
1171 {
1172 	u32 device_id = its_cmd_get_deviceid(its_cmd);
1173 	bool valid = its_cmd_get_validbit(its_cmd);
1174 	u8 num_eventid_bits = its_cmd_get_size(its_cmd);
1175 	gpa_t itt_addr = its_cmd_get_ittaddr(its_cmd);
1176 	struct its_device *device;
1177 	gpa_t gpa;
1178 
1179 	if (!vgic_its_check_id(its, its->baser_device_table, device_id, &gpa))
1180 		return E_ITS_MAPD_DEVICE_OOR;
1181 
1182 	if (valid && num_eventid_bits > VITS_TYPER_IDBITS)
1183 		return E_ITS_MAPD_ITTSIZE_OOR;
1184 
1185 	device = find_its_device(its, device_id);
1186 
1187 	/*
1188 	 * The spec says that calling MAPD on an already mapped device
1189 	 * invalidates all cached data for this device. We implement this
1190 	 * by removing the mapping and re-establishing it.
1191 	 */
1192 	if (device)
1193 		vgic_its_free_device(kvm, its, device);
1194 
1195 	/*
1196 	 * The spec does not say whether unmapping a not-mapped device
1197 	 * is an error, so we are done in any case.
1198 	 */
1199 	if (!valid)
1200 		return vgic_its_write_entry_lock(its, gpa, 0ULL, dte);
1201 
1202 	device = vgic_its_alloc_device(its, device_id, itt_addr,
1203 				       num_eventid_bits);
1204 
1205 	return PTR_ERR_OR_ZERO(device);
1206 }
1207 
1208 /*
1209  * The MAPC command maps collection IDs to redistributors.
1210  * Must be called with the its_lock mutex held.
1211  */
vgic_its_cmd_handle_mapc(struct kvm * kvm,struct vgic_its * its,u64 * its_cmd)1212 static int vgic_its_cmd_handle_mapc(struct kvm *kvm, struct vgic_its *its,
1213 				    u64 *its_cmd)
1214 {
1215 	u16 coll_id;
1216 	struct its_collection *collection;
1217 	bool valid;
1218 
1219 	valid = its_cmd_get_validbit(its_cmd);
1220 	coll_id = its_cmd_get_collection(its_cmd);
1221 
1222 	if (!valid) {
1223 		vgic_its_free_collection(its, coll_id);
1224 		vgic_its_invalidate_cache(its);
1225 	} else {
1226 		struct kvm_vcpu *vcpu;
1227 
1228 		vcpu = kvm_get_vcpu_by_id(kvm, its_cmd_get_target_addr(its_cmd));
1229 		if (!vcpu)
1230 			return E_ITS_MAPC_PROCNUM_OOR;
1231 
1232 		collection = find_collection(its, coll_id);
1233 
1234 		if (!collection) {
1235 			int ret;
1236 
1237 			if (!vgic_its_check_id(its, its->baser_coll_table,
1238 						coll_id, NULL))
1239 				return E_ITS_MAPC_COLLECTION_OOR;
1240 
1241 			ret = vgic_its_alloc_collection(its, &collection,
1242 							coll_id);
1243 			if (ret)
1244 				return ret;
1245 			collection->target_addr = vcpu->vcpu_id;
1246 		} else {
1247 			collection->target_addr = vcpu->vcpu_id;
1248 			update_affinity_collection(kvm, its, collection);
1249 		}
1250 	}
1251 
1252 	return 0;
1253 }
1254 
1255 /*
1256  * The CLEAR command removes the pending state for a particular LPI.
1257  * Must be called with the its_lock mutex held.
1258  */
vgic_its_cmd_handle_clear(struct kvm * kvm,struct vgic_its * its,u64 * its_cmd)1259 static int vgic_its_cmd_handle_clear(struct kvm *kvm, struct vgic_its *its,
1260 				     u64 *its_cmd)
1261 {
1262 	u32 device_id = its_cmd_get_deviceid(its_cmd);
1263 	u32 event_id = its_cmd_get_id(its_cmd);
1264 	struct its_ite *ite;
1265 
1266 
1267 	ite = find_ite(its, device_id, event_id);
1268 	if (!ite)
1269 		return E_ITS_CLEAR_UNMAPPED_INTERRUPT;
1270 
1271 	ite->irq->pending_latch = false;
1272 
1273 	if (ite->irq->hw)
1274 		return irq_set_irqchip_state(ite->irq->host_irq,
1275 					     IRQCHIP_STATE_PENDING, false);
1276 
1277 	return 0;
1278 }
1279 
vgic_its_inv_lpi(struct kvm * kvm,struct vgic_irq * irq)1280 int vgic_its_inv_lpi(struct kvm *kvm, struct vgic_irq *irq)
1281 {
1282 	return update_lpi_config(kvm, irq, NULL, true);
1283 }
1284 
1285 /*
1286  * The INV command syncs the configuration bits from the memory table.
1287  * Must be called with the its_lock mutex held.
1288  */
vgic_its_cmd_handle_inv(struct kvm * kvm,struct vgic_its * its,u64 * its_cmd)1289 static int vgic_its_cmd_handle_inv(struct kvm *kvm, struct vgic_its *its,
1290 				   u64 *its_cmd)
1291 {
1292 	u32 device_id = its_cmd_get_deviceid(its_cmd);
1293 	u32 event_id = its_cmd_get_id(its_cmd);
1294 	struct its_ite *ite;
1295 
1296 
1297 	ite = find_ite(its, device_id, event_id);
1298 	if (!ite)
1299 		return E_ITS_INV_UNMAPPED_INTERRUPT;
1300 
1301 	return vgic_its_inv_lpi(kvm, ite->irq);
1302 }
1303 
1304 /**
1305  * vgic_its_invall - invalidate all LPIs targeting a given vcpu
1306  * @vcpu: the vcpu for which the RD is targeted by an invalidation
1307  *
1308  * Contrary to the INVALL command, this targets a RD instead of a
1309  * collection, and we don't need to hold the its_lock, since no ITS is
1310  * involved here.
1311  */
vgic_its_invall(struct kvm_vcpu * vcpu)1312 int vgic_its_invall(struct kvm_vcpu *vcpu)
1313 {
1314 	struct kvm *kvm = vcpu->kvm;
1315 	struct vgic_dist *dist = &kvm->arch.vgic;
1316 	struct vgic_irq *irq;
1317 	unsigned long intid;
1318 
1319 	xa_for_each(&dist->lpi_xa, intid, irq) {
1320 		irq = vgic_get_irq(kvm, intid);
1321 		if (!irq)
1322 			continue;
1323 
1324 		update_lpi_config(kvm, irq, vcpu, false);
1325 		vgic_put_irq(kvm, irq);
1326 	}
1327 
1328 	if (vcpu->arch.vgic_cpu.vgic_v3.its_vpe.its_vm)
1329 		its_invall_vpe(&vcpu->arch.vgic_cpu.vgic_v3.its_vpe);
1330 
1331 	return 0;
1332 }
1333 
1334 /*
1335  * The INVALL command requests flushing of all IRQ data in this collection.
1336  * Find the VCPU mapped to that collection, then iterate over the VM's list
1337  * of mapped LPIs and update the configuration for each IRQ which targets
1338  * the specified vcpu. The configuration will be read from the in-memory
1339  * configuration table.
1340  * Must be called with the its_lock mutex held.
1341  */
vgic_its_cmd_handle_invall(struct kvm * kvm,struct vgic_its * its,u64 * its_cmd)1342 static int vgic_its_cmd_handle_invall(struct kvm *kvm, struct vgic_its *its,
1343 				      u64 *its_cmd)
1344 {
1345 	u32 coll_id = its_cmd_get_collection(its_cmd);
1346 	struct its_collection *collection;
1347 	struct kvm_vcpu *vcpu;
1348 
1349 	collection = find_collection(its, coll_id);
1350 	if (!its_is_collection_mapped(collection))
1351 		return E_ITS_INVALL_UNMAPPED_COLLECTION;
1352 
1353 	vcpu = collection_to_vcpu(kvm, collection);
1354 	vgic_its_invall(vcpu);
1355 
1356 	return 0;
1357 }
1358 
1359 /*
1360  * The MOVALL command moves the pending state of all IRQs targeting one
1361  * redistributor to another. We don't hold the pending state in the VCPUs,
1362  * but in the IRQs instead, so there is really not much to do for us here.
1363  * However the spec says that no IRQ must target the old redistributor
1364  * afterwards, so we make sure that no LPI is using the associated target_vcpu.
1365  * This command affects all LPIs in the system that target that redistributor.
1366  */
vgic_its_cmd_handle_movall(struct kvm * kvm,struct vgic_its * its,u64 * its_cmd)1367 static int vgic_its_cmd_handle_movall(struct kvm *kvm, struct vgic_its *its,
1368 				      u64 *its_cmd)
1369 {
1370 	struct vgic_dist *dist = &kvm->arch.vgic;
1371 	struct kvm_vcpu *vcpu1, *vcpu2;
1372 	struct vgic_irq *irq;
1373 	unsigned long intid;
1374 
1375 	/* We advertise GITS_TYPER.PTA==0, making the address the vcpu ID */
1376 	vcpu1 = kvm_get_vcpu_by_id(kvm, its_cmd_get_target_addr(its_cmd));
1377 	vcpu2 = kvm_get_vcpu_by_id(kvm, its_cmd_mask_field(its_cmd, 3, 16, 32));
1378 
1379 	if (!vcpu1 || !vcpu2)
1380 		return E_ITS_MOVALL_PROCNUM_OOR;
1381 
1382 	if (vcpu1 == vcpu2)
1383 		return 0;
1384 
1385 	xa_for_each(&dist->lpi_xa, intid, irq) {
1386 		irq = vgic_get_irq(kvm, intid);
1387 		if (!irq)
1388 			continue;
1389 
1390 		update_affinity(irq, vcpu1, vcpu2);
1391 
1392 		vgic_put_irq(kvm, irq);
1393 	}
1394 
1395 	vgic_its_invalidate_cache(its);
1396 
1397 	return 0;
1398 }
1399 
1400 /*
1401  * The INT command injects the LPI associated with that DevID/EvID pair.
1402  * Must be called with the its_lock mutex held.
1403  */
vgic_its_cmd_handle_int(struct kvm * kvm,struct vgic_its * its,u64 * its_cmd)1404 static int vgic_its_cmd_handle_int(struct kvm *kvm, struct vgic_its *its,
1405 				   u64 *its_cmd)
1406 {
1407 	u32 msi_data = its_cmd_get_id(its_cmd);
1408 	u64 msi_devid = its_cmd_get_deviceid(its_cmd);
1409 
1410 	return vgic_its_trigger_msi(kvm, its, msi_devid, msi_data);
1411 }
1412 
1413 /*
1414  * This function is called with the its_cmd lock held, but the ITS data
1415  * structure lock dropped.
1416  */
vgic_its_handle_command(struct kvm * kvm,struct vgic_its * its,u64 * its_cmd)1417 static int vgic_its_handle_command(struct kvm *kvm, struct vgic_its *its,
1418 				   u64 *its_cmd)
1419 {
1420 	int ret = -ENODEV;
1421 
1422 	mutex_lock(&its->its_lock);
1423 	switch (its_cmd_get_command(its_cmd)) {
1424 	case GITS_CMD_MAPD:
1425 		ret = vgic_its_cmd_handle_mapd(kvm, its, its_cmd);
1426 		break;
1427 	case GITS_CMD_MAPC:
1428 		ret = vgic_its_cmd_handle_mapc(kvm, its, its_cmd);
1429 		break;
1430 	case GITS_CMD_MAPI:
1431 		ret = vgic_its_cmd_handle_mapi(kvm, its, its_cmd);
1432 		break;
1433 	case GITS_CMD_MAPTI:
1434 		ret = vgic_its_cmd_handle_mapi(kvm, its, its_cmd);
1435 		break;
1436 	case GITS_CMD_MOVI:
1437 		ret = vgic_its_cmd_handle_movi(kvm, its, its_cmd);
1438 		break;
1439 	case GITS_CMD_DISCARD:
1440 		ret = vgic_its_cmd_handle_discard(kvm, its, its_cmd);
1441 		break;
1442 	case GITS_CMD_CLEAR:
1443 		ret = vgic_its_cmd_handle_clear(kvm, its, its_cmd);
1444 		break;
1445 	case GITS_CMD_MOVALL:
1446 		ret = vgic_its_cmd_handle_movall(kvm, its, its_cmd);
1447 		break;
1448 	case GITS_CMD_INT:
1449 		ret = vgic_its_cmd_handle_int(kvm, its, its_cmd);
1450 		break;
1451 	case GITS_CMD_INV:
1452 		ret = vgic_its_cmd_handle_inv(kvm, its, its_cmd);
1453 		break;
1454 	case GITS_CMD_INVALL:
1455 		ret = vgic_its_cmd_handle_invall(kvm, its, its_cmd);
1456 		break;
1457 	case GITS_CMD_SYNC:
1458 		/* we ignore this command: we are in sync all of the time */
1459 		ret = 0;
1460 		break;
1461 	}
1462 	mutex_unlock(&its->its_lock);
1463 
1464 	return ret;
1465 }
1466 
vgic_sanitise_its_baser(u64 reg)1467 static u64 vgic_sanitise_its_baser(u64 reg)
1468 {
1469 	reg = vgic_sanitise_field(reg, GITS_BASER_SHAREABILITY_MASK,
1470 				  GITS_BASER_SHAREABILITY_SHIFT,
1471 				  vgic_sanitise_shareability);
1472 	reg = vgic_sanitise_field(reg, GITS_BASER_INNER_CACHEABILITY_MASK,
1473 				  GITS_BASER_INNER_CACHEABILITY_SHIFT,
1474 				  vgic_sanitise_inner_cacheability);
1475 	reg = vgic_sanitise_field(reg, GITS_BASER_OUTER_CACHEABILITY_MASK,
1476 				  GITS_BASER_OUTER_CACHEABILITY_SHIFT,
1477 				  vgic_sanitise_outer_cacheability);
1478 
1479 	/* We support only one (ITS) page size: 64K */
1480 	reg = (reg & ~GITS_BASER_PAGE_SIZE_MASK) | GITS_BASER_PAGE_SIZE_64K;
1481 
1482 	return reg;
1483 }
1484 
vgic_sanitise_its_cbaser(u64 reg)1485 static u64 vgic_sanitise_its_cbaser(u64 reg)
1486 {
1487 	reg = vgic_sanitise_field(reg, GITS_CBASER_SHAREABILITY_MASK,
1488 				  GITS_CBASER_SHAREABILITY_SHIFT,
1489 				  vgic_sanitise_shareability);
1490 	reg = vgic_sanitise_field(reg, GITS_CBASER_INNER_CACHEABILITY_MASK,
1491 				  GITS_CBASER_INNER_CACHEABILITY_SHIFT,
1492 				  vgic_sanitise_inner_cacheability);
1493 	reg = vgic_sanitise_field(reg, GITS_CBASER_OUTER_CACHEABILITY_MASK,
1494 				  GITS_CBASER_OUTER_CACHEABILITY_SHIFT,
1495 				  vgic_sanitise_outer_cacheability);
1496 
1497 	/* Sanitise the physical address to be 64k aligned. */
1498 	reg &= ~GENMASK_ULL(15, 12);
1499 
1500 	return reg;
1501 }
1502 
vgic_mmio_read_its_cbaser(struct kvm * kvm,struct vgic_its * its,gpa_t addr,unsigned int len)1503 static unsigned long vgic_mmio_read_its_cbaser(struct kvm *kvm,
1504 					       struct vgic_its *its,
1505 					       gpa_t addr, unsigned int len)
1506 {
1507 	return extract_bytes(its->cbaser, addr & 7, len);
1508 }
1509 
vgic_mmio_write_its_cbaser(struct kvm * kvm,struct vgic_its * its,gpa_t addr,unsigned int len,unsigned long val)1510 static void vgic_mmio_write_its_cbaser(struct kvm *kvm, struct vgic_its *its,
1511 				       gpa_t addr, unsigned int len,
1512 				       unsigned long val)
1513 {
1514 	/* When GITS_CTLR.Enable is 1, this register is RO. */
1515 	if (its->enabled)
1516 		return;
1517 
1518 	mutex_lock(&its->cmd_lock);
1519 	its->cbaser = update_64bit_reg(its->cbaser, addr & 7, len, val);
1520 	its->cbaser = vgic_sanitise_its_cbaser(its->cbaser);
1521 	its->creadr = 0;
1522 	/*
1523 	 * CWRITER is architecturally UNKNOWN on reset, but we need to reset
1524 	 * it to CREADR to make sure we start with an empty command buffer.
1525 	 */
1526 	its->cwriter = its->creadr;
1527 	mutex_unlock(&its->cmd_lock);
1528 }
1529 
1530 #define ITS_CMD_BUFFER_SIZE(baser)	((((baser) & 0xff) + 1) << 12)
1531 #define ITS_CMD_SIZE			32
1532 #define ITS_CMD_OFFSET(reg)		((reg) & GENMASK(19, 5))
1533 
1534 /* Must be called with the cmd_lock held. */
vgic_its_process_commands(struct kvm * kvm,struct vgic_its * its)1535 static void vgic_its_process_commands(struct kvm *kvm, struct vgic_its *its)
1536 {
1537 	gpa_t cbaser;
1538 	u64 cmd_buf[4];
1539 
1540 	/* Commands are only processed when the ITS is enabled. */
1541 	if (!its->enabled)
1542 		return;
1543 
1544 	cbaser = GITS_CBASER_ADDRESS(its->cbaser);
1545 
1546 	while (its->cwriter != its->creadr) {
1547 		int ret = kvm_read_guest_lock(kvm, cbaser + its->creadr,
1548 					      cmd_buf, ITS_CMD_SIZE);
1549 		/*
1550 		 * If kvm_read_guest() fails, this could be due to the guest
1551 		 * programming a bogus value in CBASER or something else going
1552 		 * wrong from which we cannot easily recover.
1553 		 * According to section 6.3.2 in the GICv3 spec we can just
1554 		 * ignore that command then.
1555 		 */
1556 		if (!ret)
1557 			vgic_its_handle_command(kvm, its, cmd_buf);
1558 
1559 		its->creadr += ITS_CMD_SIZE;
1560 		if (its->creadr == ITS_CMD_BUFFER_SIZE(its->cbaser))
1561 			its->creadr = 0;
1562 	}
1563 }
1564 
1565 /*
1566  * By writing to CWRITER the guest announces new commands to be processed.
1567  * To avoid any races in the first place, we take the its_cmd lock, which
1568  * protects our ring buffer variables, so that there is only one user
1569  * per ITS handling commands at a given time.
1570  */
vgic_mmio_write_its_cwriter(struct kvm * kvm,struct vgic_its * its,gpa_t addr,unsigned int len,unsigned long val)1571 static void vgic_mmio_write_its_cwriter(struct kvm *kvm, struct vgic_its *its,
1572 					gpa_t addr, unsigned int len,
1573 					unsigned long val)
1574 {
1575 	u64 reg;
1576 
1577 	if (!its)
1578 		return;
1579 
1580 	mutex_lock(&its->cmd_lock);
1581 
1582 	reg = update_64bit_reg(its->cwriter, addr & 7, len, val);
1583 	reg = ITS_CMD_OFFSET(reg);
1584 	if (reg >= ITS_CMD_BUFFER_SIZE(its->cbaser)) {
1585 		mutex_unlock(&its->cmd_lock);
1586 		return;
1587 	}
1588 	its->cwriter = reg;
1589 
1590 	vgic_its_process_commands(kvm, its);
1591 
1592 	mutex_unlock(&its->cmd_lock);
1593 }
1594 
vgic_mmio_read_its_cwriter(struct kvm * kvm,struct vgic_its * its,gpa_t addr,unsigned int len)1595 static unsigned long vgic_mmio_read_its_cwriter(struct kvm *kvm,
1596 						struct vgic_its *its,
1597 						gpa_t addr, unsigned int len)
1598 {
1599 	return extract_bytes(its->cwriter, addr & 0x7, len);
1600 }
1601 
vgic_mmio_read_its_creadr(struct kvm * kvm,struct vgic_its * its,gpa_t addr,unsigned int len)1602 static unsigned long vgic_mmio_read_its_creadr(struct kvm *kvm,
1603 					       struct vgic_its *its,
1604 					       gpa_t addr, unsigned int len)
1605 {
1606 	return extract_bytes(its->creadr, addr & 0x7, len);
1607 }
1608 
vgic_mmio_uaccess_write_its_creadr(struct kvm * kvm,struct vgic_its * its,gpa_t addr,unsigned int len,unsigned long val)1609 static int vgic_mmio_uaccess_write_its_creadr(struct kvm *kvm,
1610 					      struct vgic_its *its,
1611 					      gpa_t addr, unsigned int len,
1612 					      unsigned long val)
1613 {
1614 	u32 cmd_offset;
1615 	int ret = 0;
1616 
1617 	mutex_lock(&its->cmd_lock);
1618 
1619 	if (its->enabled) {
1620 		ret = -EBUSY;
1621 		goto out;
1622 	}
1623 
1624 	cmd_offset = ITS_CMD_OFFSET(val);
1625 	if (cmd_offset >= ITS_CMD_BUFFER_SIZE(its->cbaser)) {
1626 		ret = -EINVAL;
1627 		goto out;
1628 	}
1629 
1630 	its->creadr = cmd_offset;
1631 out:
1632 	mutex_unlock(&its->cmd_lock);
1633 	return ret;
1634 }
1635 
1636 #define BASER_INDEX(addr) (((addr) / sizeof(u64)) & 0x7)
vgic_mmio_read_its_baser(struct kvm * kvm,struct vgic_its * its,gpa_t addr,unsigned int len)1637 static unsigned long vgic_mmio_read_its_baser(struct kvm *kvm,
1638 					      struct vgic_its *its,
1639 					      gpa_t addr, unsigned int len)
1640 {
1641 	u64 reg;
1642 
1643 	switch (BASER_INDEX(addr)) {
1644 	case 0:
1645 		reg = its->baser_device_table;
1646 		break;
1647 	case 1:
1648 		reg = its->baser_coll_table;
1649 		break;
1650 	default:
1651 		reg = 0;
1652 		break;
1653 	}
1654 
1655 	return extract_bytes(reg, addr & 7, len);
1656 }
1657 
1658 #define GITS_BASER_RO_MASK	(GENMASK_ULL(52, 48) | GENMASK_ULL(58, 56))
vgic_mmio_write_its_baser(struct kvm * kvm,struct vgic_its * its,gpa_t addr,unsigned int len,unsigned long val)1659 static void vgic_mmio_write_its_baser(struct kvm *kvm,
1660 				      struct vgic_its *its,
1661 				      gpa_t addr, unsigned int len,
1662 				      unsigned long val)
1663 {
1664 	const struct vgic_its_abi *abi = vgic_its_get_abi(its);
1665 	u64 old, entry_size, table_type;
1666 	u64 reg, *regptr, clearbits = 0;
1667 
1668 	/* When GITS_CTLR.Enable is 1, we ignore write accesses. */
1669 	if (its->enabled)
1670 		return;
1671 
1672 	switch (BASER_INDEX(addr)) {
1673 	case 0:
1674 		regptr = &its->baser_device_table;
1675 		entry_size = abi->dte_esz;
1676 		table_type = GITS_BASER_TYPE_DEVICE;
1677 		break;
1678 	case 1:
1679 		regptr = &its->baser_coll_table;
1680 		entry_size = abi->cte_esz;
1681 		table_type = GITS_BASER_TYPE_COLLECTION;
1682 		clearbits = GITS_BASER_INDIRECT;
1683 		break;
1684 	default:
1685 		return;
1686 	}
1687 
1688 	old = *regptr;
1689 
1690 	reg = update_64bit_reg(old, addr & 7, len, val);
1691 	reg &= ~GITS_BASER_RO_MASK;
1692 	reg &= ~clearbits;
1693 
1694 	reg |= (entry_size - 1) << GITS_BASER_ENTRY_SIZE_SHIFT;
1695 	reg |= table_type << GITS_BASER_TYPE_SHIFT;
1696 	reg = vgic_sanitise_its_baser(reg);
1697 
1698 	*regptr = reg;
1699 
1700 	/* The ITS driver rewrites an unchanged GITS_BASER<n> on resume. */
1701 	if (reg != old) {
1702 		/* Take the its_lock to prevent a race with a save/restore */
1703 		mutex_lock(&its->its_lock);
1704 		switch (table_type) {
1705 		case GITS_BASER_TYPE_DEVICE:
1706 			vgic_its_free_device_list(kvm, its);
1707 			break;
1708 		case GITS_BASER_TYPE_COLLECTION:
1709 			vgic_its_free_collection_list(kvm, its);
1710 			break;
1711 		}
1712 		/* A concurrent injection may have cached a translation. */
1713 		vgic_its_invalidate_cache(its);
1714 		mutex_unlock(&its->its_lock);
1715 	}
1716 }
1717 
vgic_mmio_read_its_ctlr(struct kvm * vcpu,struct vgic_its * its,gpa_t addr,unsigned int len)1718 static unsigned long vgic_mmio_read_its_ctlr(struct kvm *vcpu,
1719 					     struct vgic_its *its,
1720 					     gpa_t addr, unsigned int len)
1721 {
1722 	u32 reg = 0;
1723 
1724 	mutex_lock(&its->cmd_lock);
1725 	if (its->creadr == its->cwriter)
1726 		reg |= GITS_CTLR_QUIESCENT;
1727 	if (its->enabled)
1728 		reg |= GITS_CTLR_ENABLE;
1729 	mutex_unlock(&its->cmd_lock);
1730 
1731 	return reg;
1732 }
1733 
vgic_mmio_write_its_ctlr(struct kvm * kvm,struct vgic_its * its,gpa_t addr,unsigned int len,unsigned long val)1734 static void vgic_mmio_write_its_ctlr(struct kvm *kvm, struct vgic_its *its,
1735 				     gpa_t addr, unsigned int len,
1736 				     unsigned long val)
1737 {
1738 	mutex_lock(&its->cmd_lock);
1739 
1740 	/*
1741 	 * It is UNPREDICTABLE to enable the ITS if any of the CBASER or
1742 	 * device/collection BASER are invalid
1743 	 */
1744 	if (!its->enabled && (val & GITS_CTLR_ENABLE) &&
1745 		(!(its->baser_device_table & GITS_BASER_VALID) ||
1746 		 !(its->baser_coll_table & GITS_BASER_VALID) ||
1747 		 !(its->cbaser & GITS_CBASER_VALID)))
1748 		goto out;
1749 
1750 	its->enabled = !!(val & GITS_CTLR_ENABLE);
1751 	if (!its->enabled)
1752 		vgic_its_invalidate_cache(its);
1753 
1754 	/*
1755 	 * Try to process any pending commands. This function bails out early
1756 	 * if the ITS is disabled or no commands have been queued.
1757 	 */
1758 	vgic_its_process_commands(kvm, its);
1759 
1760 out:
1761 	mutex_unlock(&its->cmd_lock);
1762 }
1763 
1764 #define REGISTER_ITS_DESC(off, rd, wr, length, acc)		\
1765 {								\
1766 	.reg_offset = off,					\
1767 	.len = length,						\
1768 	.access_flags = acc,					\
1769 	.its_read = rd,						\
1770 	.its_write = wr,					\
1771 }
1772 
1773 #define REGISTER_ITS_DESC_UACCESS(off, rd, wr, uwr, length, acc)\
1774 {								\
1775 	.reg_offset = off,					\
1776 	.len = length,						\
1777 	.access_flags = acc,					\
1778 	.its_read = rd,						\
1779 	.its_write = wr,					\
1780 	.uaccess_its_write = uwr,				\
1781 }
1782 
its_mmio_write_wi(struct kvm * kvm,struct vgic_its * its,gpa_t addr,unsigned int len,unsigned long val)1783 static void its_mmio_write_wi(struct kvm *kvm, struct vgic_its *its,
1784 			      gpa_t addr, unsigned int len, unsigned long val)
1785 {
1786 	/* Ignore */
1787 }
1788 
1789 static struct vgic_register_region its_registers[] = {
1790 	REGISTER_ITS_DESC(GITS_CTLR,
1791 		vgic_mmio_read_its_ctlr, vgic_mmio_write_its_ctlr, 4,
1792 		VGIC_ACCESS_32bit),
1793 	REGISTER_ITS_DESC_UACCESS(GITS_IIDR,
1794 		vgic_mmio_read_its_iidr, its_mmio_write_wi,
1795 		vgic_mmio_uaccess_write_its_iidr, 4,
1796 		VGIC_ACCESS_32bit),
1797 	REGISTER_ITS_DESC(GITS_TYPER,
1798 		vgic_mmio_read_its_typer, its_mmio_write_wi, 8,
1799 		VGIC_ACCESS_64bit | VGIC_ACCESS_32bit),
1800 	REGISTER_ITS_DESC(GITS_CBASER,
1801 		vgic_mmio_read_its_cbaser, vgic_mmio_write_its_cbaser, 8,
1802 		VGIC_ACCESS_64bit | VGIC_ACCESS_32bit),
1803 	REGISTER_ITS_DESC(GITS_CWRITER,
1804 		vgic_mmio_read_its_cwriter, vgic_mmio_write_its_cwriter, 8,
1805 		VGIC_ACCESS_64bit | VGIC_ACCESS_32bit),
1806 	REGISTER_ITS_DESC_UACCESS(GITS_CREADR,
1807 		vgic_mmio_read_its_creadr, its_mmio_write_wi,
1808 		vgic_mmio_uaccess_write_its_creadr, 8,
1809 		VGIC_ACCESS_64bit | VGIC_ACCESS_32bit),
1810 	REGISTER_ITS_DESC(GITS_BASER,
1811 		vgic_mmio_read_its_baser, vgic_mmio_write_its_baser, 0x40,
1812 		VGIC_ACCESS_64bit | VGIC_ACCESS_32bit),
1813 	REGISTER_ITS_DESC(GITS_IDREGS_BASE,
1814 		vgic_mmio_read_its_idregs, its_mmio_write_wi, 0x30,
1815 		VGIC_ACCESS_32bit),
1816 };
1817 
1818 /* This is called on setting the LPI enable bit in the redistributor. */
vgic_enable_lpis(struct kvm_vcpu * vcpu)1819 void vgic_enable_lpis(struct kvm_vcpu *vcpu)
1820 {
1821 	if (!(vcpu->arch.vgic_cpu.pendbaser & GICR_PENDBASER_PTZ))
1822 		its_sync_lpi_pending_table(vcpu);
1823 }
1824 
vgic_register_its_iodev(struct kvm * kvm,struct vgic_its * its,u64 addr)1825 static int vgic_register_its_iodev(struct kvm *kvm, struct vgic_its *its,
1826 				   u64 addr)
1827 {
1828 	struct vgic_io_device *iodev = &its->iodev;
1829 	int ret;
1830 
1831 	mutex_lock(&kvm->slots_lock);
1832 	if (!IS_VGIC_ADDR_UNDEF(its->vgic_its_base)) {
1833 		ret = -EBUSY;
1834 		goto out;
1835 	}
1836 
1837 	its->vgic_its_base = addr;
1838 	iodev->regions = its_registers;
1839 	iodev->nr_regions = ARRAY_SIZE(its_registers);
1840 	kvm_iodevice_init(&iodev->dev, &kvm_io_gic_ops);
1841 
1842 	iodev->base_addr = its->vgic_its_base;
1843 	iodev->iodev_type = IODEV_ITS;
1844 	iodev->its = its;
1845 	ret = kvm_io_bus_register_dev(kvm, KVM_MMIO_BUS, iodev->base_addr,
1846 				      KVM_VGIC_V3_ITS_SIZE, &iodev->dev);
1847 out:
1848 	mutex_unlock(&kvm->slots_lock);
1849 
1850 	return ret;
1851 }
1852 
1853 #define INITIAL_BASER_VALUE						  \
1854 	(GIC_BASER_CACHEABILITY(GITS_BASER, INNER, RaWb)		| \
1855 	 GIC_BASER_CACHEABILITY(GITS_BASER, OUTER, SameAsInner)		| \
1856 	 GIC_BASER_SHAREABILITY(GITS_BASER, InnerShareable)		| \
1857 	 GITS_BASER_PAGE_SIZE_64K)
1858 
1859 #define INITIAL_PROPBASER_VALUE						  \
1860 	(GIC_BASER_CACHEABILITY(GICR_PROPBASER, INNER, RaWb)		| \
1861 	 GIC_BASER_CACHEABILITY(GICR_PROPBASER, OUTER, SameAsInner)	| \
1862 	 GIC_BASER_SHAREABILITY(GICR_PROPBASER, InnerShareable))
1863 
vgic_its_create(struct kvm_device * dev,u32 type)1864 static int vgic_its_create(struct kvm_device *dev, u32 type)
1865 {
1866 	int ret;
1867 	struct vgic_its *its;
1868 
1869 	if (type != KVM_DEV_TYPE_ARM_VGIC_ITS)
1870 		return -ENODEV;
1871 
1872 	its = kzalloc_obj(struct vgic_its, GFP_KERNEL_ACCOUNT);
1873 	if (!its)
1874 		return -ENOMEM;
1875 
1876 	mutex_lock(&dev->kvm->arch.config_lock);
1877 
1878 	if (vgic_initialized(dev->kvm)) {
1879 		ret = vgic_v4_init(dev->kvm);
1880 		if (ret < 0) {
1881 			mutex_unlock(&dev->kvm->arch.config_lock);
1882 			kfree(its);
1883 			return ret;
1884 		}
1885 	}
1886 
1887 	mutex_init(&its->its_lock);
1888 	mutex_init(&its->cmd_lock);
1889 
1890 	/* Yep, even more trickery for lock ordering... */
1891 #ifdef CONFIG_LOCKDEP
1892 	mutex_lock(&its->cmd_lock);
1893 	mutex_lock(&its->its_lock);
1894 	mutex_unlock(&its->its_lock);
1895 	mutex_unlock(&its->cmd_lock);
1896 #endif
1897 
1898 	its->vgic_its_base = VGIC_ADDR_UNDEF;
1899 
1900 	INIT_LIST_HEAD(&its->device_list);
1901 	INIT_LIST_HEAD(&its->collection_list);
1902 	xa_init(&its->translation_cache);
1903 
1904 	dev->kvm->arch.vgic.msis_require_devid = true;
1905 	dev->kvm->arch.vgic.has_its = true;
1906 	its->enabled = false;
1907 	its->dev = dev;
1908 
1909 	its->baser_device_table = INITIAL_BASER_VALUE			|
1910 		((u64)GITS_BASER_TYPE_DEVICE << GITS_BASER_TYPE_SHIFT);
1911 	its->baser_coll_table = INITIAL_BASER_VALUE |
1912 		((u64)GITS_BASER_TYPE_COLLECTION << GITS_BASER_TYPE_SHIFT);
1913 	dev->kvm->arch.vgic.propbaser = INITIAL_PROPBASER_VALUE;
1914 	dev->private = its;
1915 
1916 	vgic_its_set_abi(its, NR_ITS_ABIS - 1);
1917 	mutex_unlock(&dev->kvm->arch.config_lock);
1918 	return 0;
1919 }
1920 
vgic_its_destroy(struct kvm_device * kvm_dev)1921 static void vgic_its_destroy(struct kvm_device *kvm_dev)
1922 {
1923 	struct kvm *kvm = kvm_dev->kvm;
1924 	struct vgic_its *its = kvm_dev->private;
1925 
1926 	mutex_lock(&its->its_lock);
1927 
1928 	vgic_its_debug_destroy(kvm_dev);
1929 
1930 	vgic_its_free_device_list(kvm, its);
1931 	vgic_its_free_collection_list(kvm, its);
1932 	vgic_its_invalidate_cache(its);
1933 	xa_destroy(&its->translation_cache);
1934 
1935 	mutex_unlock(&its->its_lock);
1936 	kfree(its);
1937 	kfree(kvm_dev);/* alloc by kvm_ioctl_create_device, free by .destroy */
1938 }
1939 
vgic_its_has_attr_regs(struct kvm_device * dev,struct kvm_device_attr * attr)1940 static int vgic_its_has_attr_regs(struct kvm_device *dev,
1941 				  struct kvm_device_attr *attr)
1942 {
1943 	const struct vgic_register_region *region;
1944 	gpa_t offset = attr->attr;
1945 	int align;
1946 
1947 	align = (offset < GITS_TYPER) || (offset >= GITS_PIDR4) ? 0x3 : 0x7;
1948 
1949 	if (offset & align)
1950 		return -EINVAL;
1951 
1952 	region = vgic_find_mmio_region(its_registers,
1953 				       ARRAY_SIZE(its_registers),
1954 				       offset);
1955 	if (!region)
1956 		return -ENXIO;
1957 
1958 	return 0;
1959 }
1960 
vgic_its_attr_regs_access(struct kvm_device * dev,struct kvm_device_attr * attr,u64 * reg,bool is_write)1961 static int vgic_its_attr_regs_access(struct kvm_device *dev,
1962 				     struct kvm_device_attr *attr,
1963 				     u64 *reg, bool is_write)
1964 {
1965 	const struct vgic_register_region *region;
1966 	struct vgic_its *its;
1967 	gpa_t addr, offset;
1968 	unsigned int len;
1969 	int align, ret = 0;
1970 
1971 	its = dev->private;
1972 	offset = attr->attr;
1973 
1974 	/*
1975 	 * Although the spec supports upper/lower 32-bit accesses to
1976 	 * 64-bit ITS registers, the userspace ABI requires 64-bit
1977 	 * accesses to all 64-bit wide registers. We therefore only
1978 	 * support 32-bit accesses to GITS_CTLR, GITS_IIDR and GITS ID
1979 	 * registers
1980 	 */
1981 	if ((offset < GITS_TYPER) || (offset >= GITS_PIDR4))
1982 		align = 0x3;
1983 	else
1984 		align = 0x7;
1985 
1986 	if (offset & align)
1987 		return -EINVAL;
1988 
1989 	mutex_lock(&dev->kvm->lock);
1990 
1991 	if (kvm_trylock_all_vcpus(dev->kvm)) {
1992 		mutex_unlock(&dev->kvm->lock);
1993 		return -EBUSY;
1994 	}
1995 
1996 	mutex_lock(&dev->kvm->arch.config_lock);
1997 
1998 	if (IS_VGIC_ADDR_UNDEF(its->vgic_its_base)) {
1999 		ret = -ENXIO;
2000 		goto out;
2001 	}
2002 
2003 	region = vgic_find_mmio_region(its_registers,
2004 				       ARRAY_SIZE(its_registers),
2005 				       offset);
2006 	if (!region) {
2007 		ret = -ENXIO;
2008 		goto out;
2009 	}
2010 
2011 	addr = its->vgic_its_base + offset;
2012 
2013 	len = region->access_flags & VGIC_ACCESS_64bit ? 8 : 4;
2014 
2015 	if (is_write) {
2016 		if (region->uaccess_its_write)
2017 			ret = region->uaccess_its_write(dev->kvm, its, addr,
2018 							len, *reg);
2019 		else
2020 			region->its_write(dev->kvm, its, addr, len, *reg);
2021 	} else {
2022 		*reg = region->its_read(dev->kvm, its, addr, len);
2023 	}
2024 out:
2025 	mutex_unlock(&dev->kvm->arch.config_lock);
2026 	kvm_unlock_all_vcpus(dev->kvm);
2027 	mutex_unlock(&dev->kvm->lock);
2028 	return ret;
2029 }
2030 
compute_next_devid_offset(struct vgic_its * its,u64 baser,struct its_device * dev)2031 static u32 compute_next_devid_offset(struct vgic_its *its, u64 baser,
2032 				     struct its_device *dev)
2033 {
2034 	struct its_device *next = dev;
2035 
2036 	/*
2037 	 * Point at the next device vgic_its_save_device_tables() saves. It
2038 	 * sorts device_list first, so the subtraction cannot underflow.
2039 	 */
2040 	list_for_each_entry_continue(next, &its->device_list, dev_list) {
2041 		if (vgic_its_check_id(its, baser, next->device_id, NULL))
2042 			return min_t(u32, next->device_id - dev->device_id,
2043 				     VITS_DTE_MAX_DEVID_OFFSET);
2044 	}
2045 
2046 	return 0;
2047 }
2048 
compute_next_eventid_offset(struct list_head * h,struct its_ite * ite)2049 static u32 compute_next_eventid_offset(struct list_head *h, struct its_ite *ite)
2050 {
2051 	struct its_ite *next = ite;
2052 
2053 	/* Point at the next ITE that vgic_its_save_ite() stores as valid. */
2054 	list_for_each_entry_continue(next, h, ite_list) {
2055 		if (next->collection)
2056 			return min_t(u32, next->event_id - ite->event_id,
2057 				     VITS_ITE_MAX_EVENTID_OFFSET);
2058 	}
2059 
2060 	return 0;
2061 }
2062 
2063 /**
2064  * typedef entry_fn_t - Callback called on a table entry restore path
2065  * @its: its handle
2066  * @id: id of the entry
2067  * @entry: pointer to the entry
2068  * @opaque: pointer to an opaque data
2069  *
2070  * Return: < 0 on error, 0 if last element was identified, id offset to next
2071  * element otherwise
2072  */
2073 typedef int (*entry_fn_t)(struct vgic_its *its, u32 id, void *entry,
2074 			  void *opaque);
2075 
2076 /**
2077  * scan_its_table - Scan a contiguous table in guest RAM and applies a function
2078  * to each entry
2079  *
2080  * @its: its handle
2081  * @base: base gpa of the table
2082  * @size: size of the table in bytes
2083  * @esz: entry size in bytes
2084  * @start_id: the ID of the first entry in the table
2085  * (non zero for 2d level tables)
2086  * @fn: function to apply on each entry
2087  * @opaque: pointer to opaque data
2088  *
2089  * Return: < 0 on error, 0 if last element was identified, 1 otherwise
2090  * (the last element may not be found on second level tables)
2091  */
scan_its_table(struct vgic_its * its,gpa_t base,int size,u32 esz,int start_id,entry_fn_t fn,void * opaque)2092 static int scan_its_table(struct vgic_its *its, gpa_t base, int size, u32 esz,
2093 			  int start_id, entry_fn_t fn, void *opaque)
2094 {
2095 	struct kvm *kvm = its->dev->kvm;
2096 	unsigned long len = size;
2097 	int id = start_id;
2098 	gpa_t gpa = base;
2099 	char entry[ESZ_MAX];
2100 	int ret;
2101 
2102 	memset(entry, 0, esz);
2103 
2104 	while (true) {
2105 		int next_offset;
2106 		size_t byte_offset;
2107 
2108 		ret = kvm_read_guest_lock(kvm, gpa, entry, esz);
2109 		if (ret)
2110 			return ret;
2111 
2112 		next_offset = fn(its, id, entry, opaque);
2113 		if (next_offset <= 0)
2114 			return next_offset;
2115 
2116 		byte_offset = next_offset * esz;
2117 		if (byte_offset >= len)
2118 			break;
2119 
2120 		id += next_offset;
2121 		gpa += byte_offset;
2122 		len -= byte_offset;
2123 	}
2124 	return 1;
2125 }
2126 
2127 /*
2128  * vgic_its_save_ite - Save an interrupt translation entry at @gpa
2129  */
vgic_its_save_ite(struct vgic_its * its,struct its_device * dev,struct its_ite * ite,gpa_t gpa)2130 static int vgic_its_save_ite(struct vgic_its *its, struct its_device *dev,
2131 			      struct its_ite *ite, gpa_t gpa)
2132 {
2133 	u32 next_offset;
2134 	u64 val;
2135 
2136 	/*
2137 	 * MAPC with V=0 keeps the ITEs mapped but drops their collection,
2138 	 * and with it the ICID. Save a zeroed entry, which the restore path
2139 	 * reads back as invalid.
2140 	 */
2141 	if (!ite->collection)
2142 		return vgic_its_write_entry_lock(its, gpa, 0ULL, ite);
2143 
2144 	next_offset = compute_next_eventid_offset(&dev->itt_head, ite);
2145 	val = ((u64)next_offset << KVM_ITS_ITE_NEXT_SHIFT) |
2146 	       ((u64)ite->irq->intid << KVM_ITS_ITE_PINTID_SHIFT) |
2147 		ite->collection->collection_id;
2148 	val = cpu_to_le64(val);
2149 
2150 	return vgic_its_write_entry_lock(its, gpa, val, ite);
2151 }
2152 
2153 /**
2154  * vgic_its_restore_ite - restore an interrupt translation entry
2155  *
2156  * @its: its handle
2157  * @event_id: id used for indexing
2158  * @ptr: pointer to the ITE entry
2159  * @opaque: pointer to the its_device
2160  */
vgic_its_restore_ite(struct vgic_its * its,u32 event_id,void * ptr,void * opaque)2161 static int vgic_its_restore_ite(struct vgic_its *its, u32 event_id,
2162 				void *ptr, void *opaque)
2163 {
2164 	struct its_device *dev = opaque;
2165 	struct its_collection *collection;
2166 	struct kvm *kvm = its->dev->kvm;
2167 	struct kvm_vcpu *vcpu = NULL;
2168 	u64 val;
2169 	u64 *p = (u64 *)ptr;
2170 	struct vgic_irq *irq;
2171 	u32 coll_id, lpi_id;
2172 	struct its_ite *ite;
2173 	u32 offset;
2174 
2175 	val = *p;
2176 
2177 	val = le64_to_cpu(val);
2178 
2179 	coll_id = val & KVM_ITS_ITE_ICID_MASK;
2180 	lpi_id = (val & KVM_ITS_ITE_PINTID_MASK) >> KVM_ITS_ITE_PINTID_SHIFT;
2181 
2182 	if (!lpi_id)
2183 		return 1; /* invalid entry, no choice but to scan next entry */
2184 
2185 	if (lpi_id < VGIC_MIN_LPI)
2186 		return -EINVAL;
2187 
2188 	offset = val >> KVM_ITS_ITE_NEXT_SHIFT;
2189 	if (event_id + offset >= BIT_ULL(dev->num_eventid_bits))
2190 		return -EINVAL;
2191 
2192 	collection = find_collection(its, coll_id);
2193 	if (!collection)
2194 		return -EINVAL;
2195 
2196 	if (!vgic_its_check_event_id(its, dev, event_id))
2197 		return -EINVAL;
2198 
2199 	ite = vgic_its_alloc_ite(dev, collection, event_id);
2200 	if (IS_ERR(ite))
2201 		return PTR_ERR(ite);
2202 
2203 	if (its_is_collection_mapped(collection))
2204 		vcpu = kvm_get_vcpu_by_id(kvm, collection->target_addr);
2205 
2206 	irq = vgic_add_lpi(kvm, lpi_id, vcpu);
2207 	if (IS_ERR(irq)) {
2208 		its_free_ite(kvm, ite);
2209 		return PTR_ERR(irq);
2210 	}
2211 	ite->irq = irq;
2212 
2213 	return offset;
2214 }
2215 
vgic_its_ite_cmp(void * priv,const struct list_head * a,const struct list_head * b)2216 static int vgic_its_ite_cmp(void *priv, const struct list_head *a,
2217 			    const struct list_head *b)
2218 {
2219 	struct its_ite *itea = container_of(a, struct its_ite, ite_list);
2220 	struct its_ite *iteb = container_of(b, struct its_ite, ite_list);
2221 
2222 	if (itea->event_id < iteb->event_id)
2223 		return -1;
2224 	else
2225 		return 1;
2226 }
2227 
vgic_its_save_itt(struct vgic_its * its,struct its_device * device)2228 static int vgic_its_save_itt(struct vgic_its *its, struct its_device *device)
2229 {
2230 	const struct vgic_its_abi *abi = vgic_its_get_abi(its);
2231 	gpa_t base = device->itt_addr;
2232 	struct its_ite *ite;
2233 	int ret;
2234 	int ite_esz = abi->ite_esz;
2235 
2236 	list_sort(NULL, &device->itt_head, vgic_its_ite_cmp);
2237 
2238 	list_for_each_entry(ite, &device->itt_head, ite_list) {
2239 		gpa_t gpa = base + ite->event_id * ite_esz;
2240 
2241 		/*
2242 		 * If an LPI carries the HW bit, this means that this
2243 		 * interrupt is controlled by GICv4, and we do not
2244 		 * have direct access to that state without GICv4.1.
2245 		 * Let's simply fail the save operation...
2246 		 */
2247 		if (ite->irq->hw && !kvm_vgic_global_state.has_gicv4_1)
2248 			return -EACCES;
2249 
2250 		ret = vgic_its_save_ite(its, device, ite, gpa);
2251 		if (ret)
2252 			return ret;
2253 	}
2254 	return 0;
2255 }
2256 
2257 /**
2258  * vgic_its_restore_itt - restore the ITT of a device
2259  *
2260  * @its: its handle
2261  * @dev: device handle
2262  *
2263  * Return 0 on success, < 0 on error
2264  */
vgic_its_restore_itt(struct vgic_its * its,struct its_device * dev)2265 static int vgic_its_restore_itt(struct vgic_its *its, struct its_device *dev)
2266 {
2267 	const struct vgic_its_abi *abi = vgic_its_get_abi(its);
2268 	gpa_t base = dev->itt_addr;
2269 	int ret;
2270 	int ite_esz = abi->ite_esz;
2271 	size_t max_size = BIT_ULL(dev->num_eventid_bits) * ite_esz;
2272 
2273 	ret = scan_its_table(its, base, max_size, ite_esz, 0,
2274 			     vgic_its_restore_ite, dev);
2275 
2276 	/* scan_its_table returns +1 if all ITEs are invalid */
2277 	if (ret > 0)
2278 		ret = 0;
2279 
2280 	return ret;
2281 }
2282 
2283 /**
2284  * vgic_its_save_dte - Save a device table entry at a given GPA
2285  *
2286  * @its: ITS handle
2287  * @baser: GITS_BASER<dev> the caller is saving against
2288  * @dev: ITS device
2289  * @ptr: GPA
2290  */
vgic_its_save_dte(struct vgic_its * its,u64 baser,struct its_device * dev,gpa_t ptr)2291 static int vgic_its_save_dte(struct vgic_its *its, u64 baser,
2292 			     struct its_device *dev, gpa_t ptr)
2293 {
2294 	u64 val, itt_addr_field;
2295 	u32 next_offset;
2296 
2297 	itt_addr_field = dev->itt_addr >> 8;
2298 	next_offset = compute_next_devid_offset(its, baser, dev);
2299 	val = (1ULL << KVM_ITS_DTE_VALID_SHIFT |
2300 	       ((u64)next_offset << KVM_ITS_DTE_NEXT_SHIFT) |
2301 	       (itt_addr_field << KVM_ITS_DTE_ITTADDR_SHIFT) |
2302 		(dev->num_eventid_bits - 1));
2303 	val = cpu_to_le64(val);
2304 
2305 	return vgic_its_write_entry_lock(its, ptr, val, dte);
2306 }
2307 
2308 /**
2309  * vgic_its_restore_dte - restore a device table entry
2310  *
2311  * @its: its handle
2312  * @id: device id the DTE corresponds to
2313  * @ptr: kernel VA where the 8 byte DTE is located
2314  * @opaque: unused
2315  *
2316  * Return: < 0 on error, 0 if the dte is the last one, id offset to the
2317  * next dte otherwise
2318  */
vgic_its_restore_dte(struct vgic_its * its,u32 id,void * ptr,void * opaque)2319 static int vgic_its_restore_dte(struct vgic_its *its, u32 id,
2320 				void *ptr, void *opaque)
2321 {
2322 	struct its_device *dev;
2323 	u64 baser = its->baser_device_table;
2324 	gpa_t itt_addr;
2325 	u8 num_eventid_bits;
2326 	u64 entry = *(u64 *)ptr;
2327 	bool valid;
2328 	u32 offset;
2329 	int ret;
2330 
2331 	entry = le64_to_cpu(entry);
2332 
2333 	valid = entry >> KVM_ITS_DTE_VALID_SHIFT;
2334 	num_eventid_bits = (entry & KVM_ITS_DTE_SIZE_MASK) + 1;
2335 	itt_addr = ((entry & KVM_ITS_DTE_ITTADDR_MASK)
2336 			>> KVM_ITS_DTE_ITTADDR_SHIFT) << 8;
2337 
2338 	if (!valid)
2339 		return 1;
2340 
2341 	/* dte entry is valid */
2342 	offset = (entry & KVM_ITS_DTE_NEXT_MASK) >> KVM_ITS_DTE_NEXT_SHIFT;
2343 
2344 	/* Mimic the MAPD behaviour and reject invalid EID bits. */
2345 	if (num_eventid_bits > VITS_TYPER_IDBITS)
2346 		return -EINVAL;
2347 
2348 	if (!vgic_its_check_id(its, baser, id, NULL))
2349 		return -EINVAL;
2350 
2351 	dev = vgic_its_alloc_device(its, id, itt_addr, num_eventid_bits);
2352 	if (IS_ERR(dev))
2353 		return PTR_ERR(dev);
2354 
2355 	ret = vgic_its_restore_itt(its, dev);
2356 	if (ret) {
2357 		vgic_its_free_device(its->dev->kvm, its, dev);
2358 		return ret;
2359 	}
2360 
2361 	return offset;
2362 }
2363 
vgic_its_device_cmp(void * priv,const struct list_head * a,const struct list_head * b)2364 static int vgic_its_device_cmp(void *priv, const struct list_head *a,
2365 			       const struct list_head *b)
2366 {
2367 	struct its_device *deva = container_of(a, struct its_device, dev_list);
2368 	struct its_device *devb = container_of(b, struct its_device, dev_list);
2369 
2370 	if (deva->device_id < devb->device_id)
2371 		return -1;
2372 	else
2373 		return 1;
2374 }
2375 
2376 /*
2377  * vgic_its_save_device_tables - Save the device table and all ITT
2378  * into guest RAM
2379  *
2380  * L1/L2 handling is hidden by vgic_its_check_id() helper which directly
2381  * returns the GPA of the device entry
2382  */
vgic_its_save_device_tables(struct vgic_its * its)2383 static int vgic_its_save_device_tables(struct vgic_its *its)
2384 {
2385 	u64 baser = its->baser_device_table;
2386 	struct its_device *dev;
2387 
2388 	if (!(baser & GITS_BASER_VALID))
2389 		return 0;
2390 
2391 	list_sort(NULL, &its->device_list, vgic_its_device_cmp);
2392 
2393 	list_for_each_entry(dev, &its->device_list, dev_list) {
2394 		int ret;
2395 		gpa_t eaddr;
2396 
2397 		/* Don't fail a save that userspace must be able to issue. */
2398 		if (!vgic_its_check_id(its, baser,
2399 				       dev->device_id, &eaddr))
2400 			continue;
2401 
2402 		ret = vgic_its_save_itt(its, dev);
2403 		if (ret)
2404 			return ret;
2405 
2406 		ret = vgic_its_save_dte(its, baser, dev, eaddr);
2407 		if (ret)
2408 			return ret;
2409 	}
2410 	return 0;
2411 }
2412 
2413 /**
2414  * handle_l1_dte - callback used for L1 device table entries (2 stage case)
2415  *
2416  * @its: its handle
2417  * @id: index of the entry in the L1 table
2418  * @addr: kernel VA
2419  * @opaque: unused
2420  *
2421  * L1 table entries are scanned by steps of 1 entry
2422  * Return < 0 if error, 0 if last dte was found when scanning the L2
2423  * table, +1 otherwise (meaning next L1 entry must be scanned)
2424  */
handle_l1_dte(struct vgic_its * its,u32 id,void * addr,void * opaque)2425 static int handle_l1_dte(struct vgic_its *its, u32 id, void *addr,
2426 			 void *opaque)
2427 {
2428 	const struct vgic_its_abi *abi = vgic_its_get_abi(its);
2429 	int l2_start_id = id * (SZ_64K / abi->dte_esz);
2430 	u64 entry = *(u64 *)addr;
2431 	int dte_esz = abi->dte_esz;
2432 	gpa_t gpa;
2433 	int ret;
2434 
2435 	entry = le64_to_cpu(entry);
2436 
2437 	if (!(entry & KVM_ITS_L1E_VALID_MASK))
2438 		return 1;
2439 
2440 	gpa = entry & KVM_ITS_L1E_ADDR_MASK;
2441 
2442 	ret = scan_its_table(its, gpa, SZ_64K, dte_esz,
2443 			     l2_start_id, vgic_its_restore_dte, NULL);
2444 
2445 	return ret;
2446 }
2447 
2448 /*
2449  * vgic_its_restore_device_tables - Restore the device table and all ITT
2450  * from guest RAM to internal data structs
2451  */
vgic_its_restore_device_tables(struct vgic_its * its)2452 static int vgic_its_restore_device_tables(struct vgic_its *its)
2453 {
2454 	const struct vgic_its_abi *abi = vgic_its_get_abi(its);
2455 	u64 baser = its->baser_device_table;
2456 	int l1_esz, ret;
2457 	int l1_tbl_size = GITS_BASER_NR_PAGES(baser) * SZ_64K;
2458 	gpa_t l1_gpa;
2459 
2460 	if (!(baser & GITS_BASER_VALID))
2461 		return 0;
2462 
2463 	l1_gpa = GITS_BASER_ADDR_48_to_52(baser);
2464 
2465 	if (baser & GITS_BASER_INDIRECT) {
2466 		l1_esz = GITS_LVL1_ENTRY_SIZE;
2467 		ret = scan_its_table(its, l1_gpa, l1_tbl_size, l1_esz, 0,
2468 				     handle_l1_dte, NULL);
2469 	} else {
2470 		l1_esz = abi->dte_esz;
2471 		ret = scan_its_table(its, l1_gpa, l1_tbl_size, l1_esz, 0,
2472 				     vgic_its_restore_dte, NULL);
2473 	}
2474 
2475 	/* scan_its_table returns +1 if all entries are invalid */
2476 	if (ret > 0)
2477 		ret = 0;
2478 
2479 	if (ret < 0)
2480 		vgic_its_free_device_list(its->dev->kvm, its);
2481 
2482 	return ret;
2483 }
2484 
vgic_its_save_cte(struct vgic_its * its,struct its_collection * collection,gpa_t gpa)2485 static int vgic_its_save_cte(struct vgic_its *its,
2486 			     struct its_collection *collection,
2487 			     gpa_t gpa)
2488 {
2489 	u64 val;
2490 
2491 	val = (1ULL << KVM_ITS_CTE_VALID_SHIFT |
2492 	       ((u64)collection->target_addr << KVM_ITS_CTE_RDBASE_SHIFT) |
2493 	       collection->collection_id);
2494 	val = cpu_to_le64(val);
2495 
2496 	return vgic_its_write_entry_lock(its, gpa, val, cte);
2497 }
2498 
2499 /*
2500  * Restore a collection entry into the ITS collection table.
2501  * Return +1 on success, 0 if the entry was invalid (which should be
2502  * interpreted as end-of-table), and a negative error value for generic errors.
2503  */
vgic_its_restore_cte(struct vgic_its * its,gpa_t gpa)2504 static int vgic_its_restore_cte(struct vgic_its *its, gpa_t gpa)
2505 {
2506 	struct its_collection *collection;
2507 	struct kvm *kvm = its->dev->kvm;
2508 	u32 target_addr, coll_id;
2509 	u64 val;
2510 	int ret;
2511 
2512 	ret = vgic_its_read_entry_lock(its, gpa, &val, cte);
2513 	if (ret)
2514 		return ret;
2515 	val = le64_to_cpu(val);
2516 	if (!(val & KVM_ITS_CTE_VALID_MASK))
2517 		return 0;
2518 
2519 	target_addr = (u32)(val >> KVM_ITS_CTE_RDBASE_SHIFT);
2520 	coll_id = val & KVM_ITS_CTE_ICID_MASK;
2521 
2522 	if (target_addr != COLLECTION_NOT_MAPPED &&
2523 	    !kvm_get_vcpu_by_id(kvm, target_addr))
2524 		return -EINVAL;
2525 
2526 	collection = find_collection(its, coll_id);
2527 	if (collection)
2528 		return -EEXIST;
2529 
2530 	if (!vgic_its_check_id(its, its->baser_coll_table, coll_id, NULL))
2531 		return -EINVAL;
2532 
2533 	ret = vgic_its_alloc_collection(its, &collection, coll_id);
2534 	if (ret)
2535 		return ret;
2536 	collection->target_addr = target_addr;
2537 	return 1;
2538 }
2539 
2540 /*
2541  * vgic_its_save_collection_table - Save the collection table into
2542  * guest RAM
2543  */
vgic_its_save_collection_table(struct vgic_its * its)2544 static int vgic_its_save_collection_table(struct vgic_its *its)
2545 {
2546 	const struct vgic_its_abi *abi = vgic_its_get_abi(its);
2547 	u64 baser = its->baser_coll_table;
2548 	gpa_t gpa = GITS_BASER_ADDR_48_to_52(baser);
2549 	struct its_collection *collection;
2550 	size_t max_size, filled = 0;
2551 	int ret, cte_esz = abi->cte_esz;
2552 
2553 	if (!(baser & GITS_BASER_VALID))
2554 		return 0;
2555 
2556 	max_size = GITS_BASER_NR_PAGES(baser) * SZ_64K;
2557 
2558 	list_for_each_entry(collection, &its->collection_list, coll_list) {
2559 		ret = vgic_its_save_cte(its, collection, gpa);
2560 		if (ret)
2561 			return ret;
2562 		gpa += cte_esz;
2563 		filled += cte_esz;
2564 	}
2565 
2566 	if (filled == max_size)
2567 		return 0;
2568 
2569 	/*
2570 	 * table is not fully filled, add a last dummy element
2571 	 * with valid bit unset
2572 	 */
2573 	return vgic_its_write_entry_lock(its, gpa, 0ULL, cte);
2574 }
2575 
2576 /*
2577  * vgic_its_restore_collection_table - reads the collection table
2578  * in guest memory and restores the ITS internal state. Requires the
2579  * BASER registers to be restored before.
2580  */
vgic_its_restore_collection_table(struct vgic_its * its)2581 static int vgic_its_restore_collection_table(struct vgic_its *its)
2582 {
2583 	const struct vgic_its_abi *abi = vgic_its_get_abi(its);
2584 	u64 baser = its->baser_coll_table;
2585 	int cte_esz = abi->cte_esz;
2586 	size_t max_size, read = 0;
2587 	gpa_t gpa;
2588 	int ret;
2589 
2590 	if (!(baser & GITS_BASER_VALID))
2591 		return 0;
2592 
2593 	gpa = GITS_BASER_ADDR_48_to_52(baser);
2594 
2595 	max_size = GITS_BASER_NR_PAGES(baser) * SZ_64K;
2596 
2597 	while (read < max_size) {
2598 		ret = vgic_its_restore_cte(its, gpa);
2599 		if (ret <= 0)
2600 			break;
2601 		gpa += cte_esz;
2602 		read += cte_esz;
2603 	}
2604 
2605 	if (ret > 0)
2606 		return 0;
2607 
2608 	if (ret < 0)
2609 		vgic_its_free_collection_list(its->dev->kvm, its);
2610 
2611 	return ret;
2612 }
2613 
2614 /*
2615  * vgic_its_save_tables_v0 - Save the ITS tables into guest ARM
2616  * according to v0 ABI
2617  */
vgic_its_save_tables_v0(struct vgic_its * its)2618 static int vgic_its_save_tables_v0(struct vgic_its *its)
2619 {
2620 	int ret;
2621 
2622 	ret = vgic_its_save_device_tables(its);
2623 	if (ret)
2624 		return ret;
2625 
2626 	return vgic_its_save_collection_table(its);
2627 }
2628 
2629 /*
2630  * vgic_its_restore_tables_v0 - Restore the ITS tables from guest RAM
2631  * to internal data structs according to V0 ABI
2632  *
2633  */
vgic_its_restore_tables_v0(struct vgic_its * its)2634 static int vgic_its_restore_tables_v0(struct vgic_its *its)
2635 {
2636 	int ret;
2637 
2638 	ret = vgic_its_restore_collection_table(its);
2639 	if (ret)
2640 		return ret;
2641 
2642 	ret = vgic_its_restore_device_tables(its);
2643 	if (ret)
2644 		vgic_its_free_collection_list(its->dev->kvm, its);
2645 	return ret;
2646 }
2647 
vgic_its_commit_v0(struct vgic_its * its)2648 static void vgic_its_commit_v0(struct vgic_its *its)
2649 {
2650 	const struct vgic_its_abi *abi;
2651 
2652 	abi = vgic_its_get_abi(its);
2653 	its->baser_coll_table &= ~GITS_BASER_ENTRY_SIZE_MASK;
2654 	its->baser_device_table &= ~GITS_BASER_ENTRY_SIZE_MASK;
2655 
2656 	its->baser_coll_table |= (GIC_ENCODE_SZ(abi->cte_esz, 5)
2657 					<< GITS_BASER_ENTRY_SIZE_SHIFT);
2658 
2659 	its->baser_device_table |= (GIC_ENCODE_SZ(abi->dte_esz, 5)
2660 					<< GITS_BASER_ENTRY_SIZE_SHIFT);
2661 }
2662 
vgic_its_reset(struct kvm * kvm,struct vgic_its * its)2663 static void vgic_its_reset(struct kvm *kvm, struct vgic_its *its)
2664 {
2665 	/* We need to keep the ABI specific field values */
2666 	its->baser_coll_table &= ~GITS_BASER_VALID;
2667 	its->baser_device_table &= ~GITS_BASER_VALID;
2668 	its->cbaser = 0;
2669 	its->creadr = 0;
2670 	its->cwriter = 0;
2671 	its->enabled = 0;
2672 	vgic_its_free_device_list(kvm, its);
2673 	vgic_its_free_collection_list(kvm, its);
2674 }
2675 
vgic_its_has_attr(struct kvm_device * dev,struct kvm_device_attr * attr)2676 static int vgic_its_has_attr(struct kvm_device *dev,
2677 			     struct kvm_device_attr *attr)
2678 {
2679 	switch (attr->group) {
2680 	case KVM_DEV_ARM_VGIC_GRP_ADDR:
2681 		switch (attr->attr) {
2682 		case KVM_VGIC_ITS_ADDR_TYPE:
2683 			return 0;
2684 		}
2685 		break;
2686 	case KVM_DEV_ARM_VGIC_GRP_CTRL:
2687 		switch (attr->attr) {
2688 		case KVM_DEV_ARM_VGIC_CTRL_INIT:
2689 			return 0;
2690 		case KVM_DEV_ARM_ITS_CTRL_RESET:
2691 			return 0;
2692 		case KVM_DEV_ARM_ITS_SAVE_TABLES:
2693 			return 0;
2694 		case KVM_DEV_ARM_ITS_RESTORE_TABLES:
2695 			return 0;
2696 		}
2697 		break;
2698 	case KVM_DEV_ARM_VGIC_GRP_ITS_REGS:
2699 		return vgic_its_has_attr_regs(dev, attr);
2700 	}
2701 	return -ENXIO;
2702 }
2703 
vgic_its_ctrl(struct kvm * kvm,struct vgic_its * its,u64 attr)2704 static int vgic_its_ctrl(struct kvm *kvm, struct vgic_its *its, u64 attr)
2705 {
2706 	const struct vgic_its_abi *abi = vgic_its_get_abi(its);
2707 	int ret = 0;
2708 
2709 	if (attr == KVM_DEV_ARM_VGIC_CTRL_INIT) /* Nothing to do */
2710 		return 0;
2711 
2712 	mutex_lock(&kvm->lock);
2713 
2714 	if (kvm_trylock_all_vcpus(kvm)) {
2715 		mutex_unlock(&kvm->lock);
2716 		return -EBUSY;
2717 	}
2718 
2719 	mutex_lock(&kvm->arch.config_lock);
2720 	mutex_lock(&its->its_lock);
2721 
2722 	switch (attr) {
2723 	case KVM_DEV_ARM_ITS_CTRL_RESET:
2724 		vgic_its_reset(kvm, its);
2725 		break;
2726 	case KVM_DEV_ARM_ITS_SAVE_TABLES:
2727 		ret = abi->save_tables(its);
2728 		break;
2729 	case KVM_DEV_ARM_ITS_RESTORE_TABLES:
2730 		ret = abi->restore_tables(its);
2731 		break;
2732 	default:
2733 		ret = -ENXIO;
2734 		break;
2735 	}
2736 
2737 	mutex_unlock(&its->its_lock);
2738 	mutex_unlock(&kvm->arch.config_lock);
2739 	kvm_unlock_all_vcpus(kvm);
2740 	mutex_unlock(&kvm->lock);
2741 	return ret;
2742 }
2743 
2744 /*
2745  * kvm_arch_allow_write_without_running_vcpu - allow writing guest memory
2746  * without the running VCPU when dirty ring is enabled.
2747  *
2748  * The running VCPU is required to track dirty guest pages when dirty ring
2749  * is enabled. Otherwise, the backup bitmap should be used to track the
2750  * dirty guest pages. When vgic/its tables are being saved, the backup
2751  * bitmap is used to track the dirty guest pages due to the missed running
2752  * VCPU in the period.
2753  */
kvm_arch_allow_write_without_running_vcpu(struct kvm * kvm)2754 bool kvm_arch_allow_write_without_running_vcpu(struct kvm *kvm)
2755 {
2756 	struct vgic_dist *dist = &kvm->arch.vgic;
2757 
2758 	return dist->table_write_in_progress;
2759 }
2760 
vgic_its_set_attr(struct kvm_device * dev,struct kvm_device_attr * attr)2761 static int vgic_its_set_attr(struct kvm_device *dev,
2762 			     struct kvm_device_attr *attr)
2763 {
2764 	struct vgic_its *its = dev->private;
2765 	int ret;
2766 
2767 	switch (attr->group) {
2768 	case KVM_DEV_ARM_VGIC_GRP_ADDR: {
2769 		u64 __user *uaddr = (u64 __user *)(long)attr->addr;
2770 		unsigned long type = (unsigned long)attr->attr;
2771 		u64 addr;
2772 
2773 		if (type != KVM_VGIC_ITS_ADDR_TYPE)
2774 			return -ENODEV;
2775 
2776 		if (copy_from_user(&addr, uaddr, sizeof(addr)))
2777 			return -EFAULT;
2778 
2779 		ret = vgic_check_iorange(dev->kvm, its->vgic_its_base,
2780 					 addr, SZ_64K, KVM_VGIC_V3_ITS_SIZE);
2781 		if (ret)
2782 			return ret;
2783 
2784 		ret = vgic_register_its_iodev(dev->kvm, its, addr);
2785 		if (ret)
2786 			return ret;
2787 
2788 		return vgic_its_debug_init(dev);
2789 
2790 	}
2791 	case KVM_DEV_ARM_VGIC_GRP_CTRL:
2792 		return vgic_its_ctrl(dev->kvm, its, attr->attr);
2793 	case KVM_DEV_ARM_VGIC_GRP_ITS_REGS: {
2794 		u64 __user *uaddr = (u64 __user *)(long)attr->addr;
2795 		u64 reg;
2796 
2797 		if (get_user(reg, uaddr))
2798 			return -EFAULT;
2799 
2800 		return vgic_its_attr_regs_access(dev, attr, &reg, true);
2801 	}
2802 	}
2803 	return -ENXIO;
2804 }
2805 
vgic_its_get_attr(struct kvm_device * dev,struct kvm_device_attr * attr)2806 static int vgic_its_get_attr(struct kvm_device *dev,
2807 			     struct kvm_device_attr *attr)
2808 {
2809 	switch (attr->group) {
2810 	case KVM_DEV_ARM_VGIC_GRP_ADDR: {
2811 		struct vgic_its *its = dev->private;
2812 		u64 addr = its->vgic_its_base;
2813 		u64 __user *uaddr = (u64 __user *)(long)attr->addr;
2814 		unsigned long type = (unsigned long)attr->attr;
2815 
2816 		if (type != KVM_VGIC_ITS_ADDR_TYPE)
2817 			return -ENODEV;
2818 
2819 		if (copy_to_user(uaddr, &addr, sizeof(addr)))
2820 			return -EFAULT;
2821 		break;
2822 	}
2823 	case KVM_DEV_ARM_VGIC_GRP_ITS_REGS: {
2824 		u64 __user *uaddr = (u64 __user *)(long)attr->addr;
2825 		u64 reg;
2826 		int ret;
2827 
2828 		ret = vgic_its_attr_regs_access(dev, attr, &reg, false);
2829 		if (ret)
2830 			return ret;
2831 		return put_user(reg, uaddr);
2832 	}
2833 	default:
2834 		return -ENXIO;
2835 	}
2836 
2837 	return 0;
2838 }
2839 
2840 static struct kvm_device_ops kvm_arm_vgic_its_ops = {
2841 	.name = "kvm-arm-vgic-its",
2842 	.create = vgic_its_create,
2843 	.destroy = vgic_its_destroy,
2844 	.set_attr = vgic_its_set_attr,
2845 	.get_attr = vgic_its_get_attr,
2846 	.has_attr = vgic_its_has_attr,
2847 };
2848 
kvm_vgic_register_its_device(void)2849 int kvm_vgic_register_its_device(void)
2850 {
2851 	return kvm_register_device_ops(&kvm_arm_vgic_its_ops,
2852 				       KVM_DEV_TYPE_ARM_VGIC_ITS);
2853 }
2854