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