xref: /linux/drivers/irqchip/irq-gic-v3-its.c (revision fcc79e1714e8c2b8e216dc3149812edd37884eef)
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  * Copyright (C) 2013-2017 ARM Limited, All Rights Reserved.
4  * Author: Marc Zyngier <marc.zyngier@arm.com>
5  */
6 
7 #include <linux/acpi.h>
8 #include <linux/acpi_iort.h>
9 #include <linux/bitfield.h>
10 #include <linux/bitmap.h>
11 #include <linux/cpu.h>
12 #include <linux/crash_dump.h>
13 #include <linux/delay.h>
14 #include <linux/efi.h>
15 #include <linux/genalloc.h>
16 #include <linux/interrupt.h>
17 #include <linux/iommu.h>
18 #include <linux/iopoll.h>
19 #include <linux/irqdomain.h>
20 #include <linux/list.h>
21 #include <linux/log2.h>
22 #include <linux/mem_encrypt.h>
23 #include <linux/memblock.h>
24 #include <linux/mm.h>
25 #include <linux/msi.h>
26 #include <linux/of.h>
27 #include <linux/of_address.h>
28 #include <linux/of_irq.h>
29 #include <linux/of_pci.h>
30 #include <linux/of_platform.h>
31 #include <linux/percpu.h>
32 #include <linux/set_memory.h>
33 #include <linux/slab.h>
34 #include <linux/syscore_ops.h>
35 
36 #include <linux/irqchip.h>
37 #include <linux/irqchip/arm-gic-v3.h>
38 #include <linux/irqchip/arm-gic-v4.h>
39 
40 #include <asm/cputype.h>
41 #include <asm/exception.h>
42 
43 #include "irq-gic-common.h"
44 #include "irq-msi-lib.h"
45 
46 #define ITS_FLAGS_CMDQ_NEEDS_FLUSHING		(1ULL << 0)
47 #define ITS_FLAGS_WORKAROUND_CAVIUM_22375	(1ULL << 1)
48 #define ITS_FLAGS_WORKAROUND_CAVIUM_23144	(1ULL << 2)
49 #define ITS_FLAGS_FORCE_NON_SHAREABLE		(1ULL << 3)
50 
51 #define RD_LOCAL_LPI_ENABLED                    BIT(0)
52 #define RD_LOCAL_PENDTABLE_PREALLOCATED         BIT(1)
53 #define RD_LOCAL_MEMRESERVE_DONE                BIT(2)
54 
55 static u32 lpi_id_bits;
56 
57 /*
58  * We allocate memory for PROPBASE to cover 2 ^ lpi_id_bits LPIs to
59  * deal with (one configuration byte per interrupt). PENDBASE has to
60  * be 64kB aligned (one bit per LPI, plus 8192 bits for SPI/PPI/SGI).
61  */
62 #define LPI_NRBITS		lpi_id_bits
63 #define LPI_PROPBASE_SZ		ALIGN(BIT(LPI_NRBITS), SZ_64K)
64 #define LPI_PENDBASE_SZ		ALIGN(BIT(LPI_NRBITS) / 8, SZ_64K)
65 
66 static u8 __ro_after_init lpi_prop_prio;
67 
68 /*
69  * Collection structure - just an ID, and a redistributor address to
70  * ping. We use one per CPU as a bag of interrupts assigned to this
71  * CPU.
72  */
73 struct its_collection {
74 	u64			target_address;
75 	u16			col_id;
76 };
77 
78 /*
79  * The ITS_BASER structure - contains memory information, cached
80  * value of BASER register configuration and ITS page size.
81  */
82 struct its_baser {
83 	void		*base;
84 	u64		val;
85 	u32		order;
86 	u32		psz;
87 };
88 
89 struct its_device;
90 
91 /*
92  * The ITS structure - contains most of the infrastructure, with the
93  * top-level MSI domain, the command queue, the collections, and the
94  * list of devices writing to it.
95  *
96  * dev_alloc_lock has to be taken for device allocations, while the
97  * spinlock must be taken to parse data structures such as the device
98  * list.
99  */
100 struct its_node {
101 	raw_spinlock_t		lock;
102 	struct mutex		dev_alloc_lock;
103 	struct list_head	entry;
104 	void __iomem		*base;
105 	void __iomem		*sgir_base;
106 	phys_addr_t		phys_base;
107 	struct its_cmd_block	*cmd_base;
108 	struct its_cmd_block	*cmd_write;
109 	struct its_baser	tables[GITS_BASER_NR_REGS];
110 	struct its_collection	*collections;
111 	struct fwnode_handle	*fwnode_handle;
112 	u64			(*get_msi_base)(struct its_device *its_dev);
113 	u64			typer;
114 	u64			cbaser_save;
115 	u32			ctlr_save;
116 	u32			mpidr;
117 	struct list_head	its_device_list;
118 	u64			flags;
119 	unsigned long		list_nr;
120 	int			numa_node;
121 	unsigned int		msi_domain_flags;
122 	u32			pre_its_base; /* for Socionext Synquacer */
123 	int			vlpi_redist_offset;
124 };
125 
126 #define is_v4(its)		(!!((its)->typer & GITS_TYPER_VLPIS))
127 #define is_v4_1(its)		(!!((its)->typer & GITS_TYPER_VMAPP))
128 #define device_ids(its)		(FIELD_GET(GITS_TYPER_DEVBITS, (its)->typer) + 1)
129 
130 #define ITS_ITT_ALIGN		SZ_256
131 
132 /* The maximum number of VPEID bits supported by VLPI commands */
133 #define ITS_MAX_VPEID_BITS						\
134 	({								\
135 		int nvpeid = 16;					\
136 		if (gic_rdists->has_rvpeid &&				\
137 		    gic_rdists->gicd_typer2 & GICD_TYPER2_VIL)		\
138 			nvpeid = 1 + (gic_rdists->gicd_typer2 &		\
139 				      GICD_TYPER2_VID);			\
140 									\
141 		nvpeid;							\
142 	})
143 #define ITS_MAX_VPEID		(1 << (ITS_MAX_VPEID_BITS))
144 
145 /* Convert page order to size in bytes */
146 #define PAGE_ORDER_TO_SIZE(o)	(PAGE_SIZE << (o))
147 
148 struct event_lpi_map {
149 	unsigned long		*lpi_map;
150 	u16			*col_map;
151 	irq_hw_number_t		lpi_base;
152 	int			nr_lpis;
153 	raw_spinlock_t		vlpi_lock;
154 	struct its_vm		*vm;
155 	struct its_vlpi_map	*vlpi_maps;
156 	int			nr_vlpis;
157 };
158 
159 /*
160  * The ITS view of a device - belongs to an ITS, owns an interrupt
161  * translation table, and a list of interrupts.  If it some of its
162  * LPIs are injected into a guest (GICv4), the event_map.vm field
163  * indicates which one.
164  */
165 struct its_device {
166 	struct list_head	entry;
167 	struct its_node		*its;
168 	struct event_lpi_map	event_map;
169 	void			*itt;
170 	u32			itt_sz;
171 	u32			nr_ites;
172 	u32			device_id;
173 	bool			shared;
174 };
175 
176 static struct {
177 	raw_spinlock_t		lock;
178 	struct its_device	*dev;
179 	struct its_vpe		**vpes;
180 	int			next_victim;
181 } vpe_proxy;
182 
183 struct cpu_lpi_count {
184 	atomic_t	managed;
185 	atomic_t	unmanaged;
186 };
187 
188 static DEFINE_PER_CPU(struct cpu_lpi_count, cpu_lpi_count);
189 
190 static LIST_HEAD(its_nodes);
191 static DEFINE_RAW_SPINLOCK(its_lock);
192 static struct rdists *gic_rdists;
193 static struct irq_domain *its_parent;
194 
195 static unsigned long its_list_map;
196 static u16 vmovp_seq_num;
197 static DEFINE_RAW_SPINLOCK(vmovp_lock);
198 
199 static DEFINE_IDA(its_vpeid_ida);
200 
201 #define gic_data_rdist()		(raw_cpu_ptr(gic_rdists->rdist))
202 #define gic_data_rdist_cpu(cpu)		(per_cpu_ptr(gic_rdists->rdist, cpu))
203 #define gic_data_rdist_rd_base()	(gic_data_rdist()->rd_base)
204 #define gic_data_rdist_vlpi_base()	(gic_data_rdist_rd_base() + SZ_128K)
205 
206 static struct page *its_alloc_pages_node(int node, gfp_t gfp,
207 					 unsigned int order)
208 {
209 	struct page *page;
210 	int ret = 0;
211 
212 	page = alloc_pages_node(node, gfp, order);
213 
214 	if (!page)
215 		return NULL;
216 
217 	ret = set_memory_decrypted((unsigned long)page_address(page),
218 				   1 << order);
219 	/*
220 	 * If set_memory_decrypted() fails then we don't know what state the
221 	 * page is in, so we can't free it. Instead we leak it.
222 	 * set_memory_decrypted() will already have WARNed.
223 	 */
224 	if (ret)
225 		return NULL;
226 
227 	return page;
228 }
229 
230 static struct page *its_alloc_pages(gfp_t gfp, unsigned int order)
231 {
232 	return its_alloc_pages_node(NUMA_NO_NODE, gfp, order);
233 }
234 
235 static void its_free_pages(void *addr, unsigned int order)
236 {
237 	/*
238 	 * If the memory cannot be encrypted again then we must leak the pages.
239 	 * set_memory_encrypted() will already have WARNed.
240 	 */
241 	if (set_memory_encrypted((unsigned long)addr, 1 << order))
242 		return;
243 	free_pages((unsigned long)addr, order);
244 }
245 
246 static struct gen_pool *itt_pool;
247 
248 static void *itt_alloc_pool(int node, int size)
249 {
250 	unsigned long addr;
251 	struct page *page;
252 
253 	if (size >= PAGE_SIZE) {
254 		page = its_alloc_pages_node(node, GFP_KERNEL | __GFP_ZERO, get_order(size));
255 
256 		return page ? page_address(page) : NULL;
257 	}
258 
259 	do {
260 		addr = gen_pool_alloc(itt_pool, size);
261 		if (addr)
262 			break;
263 
264 		page = its_alloc_pages_node(node, GFP_KERNEL | __GFP_ZERO, 0);
265 		if (!page)
266 			break;
267 
268 		gen_pool_add(itt_pool, (unsigned long)page_address(page), PAGE_SIZE, node);
269 	} while (!addr);
270 
271 	return (void *)addr;
272 }
273 
274 static void itt_free_pool(void *addr, int size)
275 {
276 	if (!addr)
277 		return;
278 
279 	if (size >= PAGE_SIZE) {
280 		its_free_pages(addr, get_order(size));
281 		return;
282 	}
283 
284 	gen_pool_free(itt_pool, (unsigned long)addr, size);
285 }
286 
287 /*
288  * Skip ITSs that have no vLPIs mapped, unless we're on GICv4.1, as we
289  * always have vSGIs mapped.
290  */
291 static bool require_its_list_vmovp(struct its_vm *vm, struct its_node *its)
292 {
293 	return (gic_rdists->has_rvpeid || vm->vlpi_count[its->list_nr]);
294 }
295 
296 static bool rdists_support_shareable(void)
297 {
298 	return !(gic_rdists->flags & RDIST_FLAGS_FORCE_NON_SHAREABLE);
299 }
300 
301 static u16 get_its_list(struct its_vm *vm)
302 {
303 	struct its_node *its;
304 	unsigned long its_list = 0;
305 
306 	list_for_each_entry(its, &its_nodes, entry) {
307 		if (!is_v4(its))
308 			continue;
309 
310 		if (require_its_list_vmovp(vm, its))
311 			__set_bit(its->list_nr, &its_list);
312 	}
313 
314 	return (u16)its_list;
315 }
316 
317 static inline u32 its_get_event_id(struct irq_data *d)
318 {
319 	struct its_device *its_dev = irq_data_get_irq_chip_data(d);
320 	return d->hwirq - its_dev->event_map.lpi_base;
321 }
322 
323 static struct its_collection *dev_event_to_col(struct its_device *its_dev,
324 					       u32 event)
325 {
326 	struct its_node *its = its_dev->its;
327 
328 	return its->collections + its_dev->event_map.col_map[event];
329 }
330 
331 static struct its_vlpi_map *dev_event_to_vlpi_map(struct its_device *its_dev,
332 					       u32 event)
333 {
334 	if (WARN_ON_ONCE(event >= its_dev->event_map.nr_lpis))
335 		return NULL;
336 
337 	return &its_dev->event_map.vlpi_maps[event];
338 }
339 
340 static struct its_vlpi_map *get_vlpi_map(struct irq_data *d)
341 {
342 	if (irqd_is_forwarded_to_vcpu(d)) {
343 		struct its_device *its_dev = irq_data_get_irq_chip_data(d);
344 		u32 event = its_get_event_id(d);
345 
346 		return dev_event_to_vlpi_map(its_dev, event);
347 	}
348 
349 	return NULL;
350 }
351 
352 static int vpe_to_cpuid_lock(struct its_vpe *vpe, unsigned long *flags)
353 {
354 	raw_spin_lock_irqsave(&vpe->vpe_lock, *flags);
355 	return vpe->col_idx;
356 }
357 
358 static void vpe_to_cpuid_unlock(struct its_vpe *vpe, unsigned long flags)
359 {
360 	raw_spin_unlock_irqrestore(&vpe->vpe_lock, flags);
361 }
362 
363 static struct irq_chip its_vpe_irq_chip;
364 
365 static int irq_to_cpuid_lock(struct irq_data *d, unsigned long *flags)
366 {
367 	struct its_vpe *vpe = NULL;
368 	int cpu;
369 
370 	if (d->chip == &its_vpe_irq_chip) {
371 		vpe = irq_data_get_irq_chip_data(d);
372 	} else {
373 		struct its_vlpi_map *map = get_vlpi_map(d);
374 		if (map)
375 			vpe = map->vpe;
376 	}
377 
378 	if (vpe) {
379 		cpu = vpe_to_cpuid_lock(vpe, flags);
380 	} else {
381 		/* Physical LPIs are already locked via the irq_desc lock */
382 		struct its_device *its_dev = irq_data_get_irq_chip_data(d);
383 		cpu = its_dev->event_map.col_map[its_get_event_id(d)];
384 		/* Keep GCC quiet... */
385 		*flags = 0;
386 	}
387 
388 	return cpu;
389 }
390 
391 static void irq_to_cpuid_unlock(struct irq_data *d, unsigned long flags)
392 {
393 	struct its_vpe *vpe = NULL;
394 
395 	if (d->chip == &its_vpe_irq_chip) {
396 		vpe = irq_data_get_irq_chip_data(d);
397 	} else {
398 		struct its_vlpi_map *map = get_vlpi_map(d);
399 		if (map)
400 			vpe = map->vpe;
401 	}
402 
403 	if (vpe)
404 		vpe_to_cpuid_unlock(vpe, flags);
405 }
406 
407 static struct its_collection *valid_col(struct its_collection *col)
408 {
409 	if (WARN_ON_ONCE(col->target_address & GENMASK_ULL(15, 0)))
410 		return NULL;
411 
412 	return col;
413 }
414 
415 static struct its_vpe *valid_vpe(struct its_node *its, struct its_vpe *vpe)
416 {
417 	if (valid_col(its->collections + vpe->col_idx))
418 		return vpe;
419 
420 	return NULL;
421 }
422 
423 /*
424  * ITS command descriptors - parameters to be encoded in a command
425  * block.
426  */
427 struct its_cmd_desc {
428 	union {
429 		struct {
430 			struct its_device *dev;
431 			u32 event_id;
432 		} its_inv_cmd;
433 
434 		struct {
435 			struct its_device *dev;
436 			u32 event_id;
437 		} its_clear_cmd;
438 
439 		struct {
440 			struct its_device *dev;
441 			u32 event_id;
442 		} its_int_cmd;
443 
444 		struct {
445 			struct its_device *dev;
446 			int valid;
447 		} its_mapd_cmd;
448 
449 		struct {
450 			struct its_collection *col;
451 			int valid;
452 		} its_mapc_cmd;
453 
454 		struct {
455 			struct its_device *dev;
456 			u32 phys_id;
457 			u32 event_id;
458 		} its_mapti_cmd;
459 
460 		struct {
461 			struct its_device *dev;
462 			struct its_collection *col;
463 			u32 event_id;
464 		} its_movi_cmd;
465 
466 		struct {
467 			struct its_device *dev;
468 			u32 event_id;
469 		} its_discard_cmd;
470 
471 		struct {
472 			struct its_collection *col;
473 		} its_invall_cmd;
474 
475 		struct {
476 			struct its_vpe *vpe;
477 		} its_vinvall_cmd;
478 
479 		struct {
480 			struct its_vpe *vpe;
481 			struct its_collection *col;
482 			bool valid;
483 		} its_vmapp_cmd;
484 
485 		struct {
486 			struct its_vpe *vpe;
487 			struct its_device *dev;
488 			u32 virt_id;
489 			u32 event_id;
490 			bool db_enabled;
491 		} its_vmapti_cmd;
492 
493 		struct {
494 			struct its_vpe *vpe;
495 			struct its_device *dev;
496 			u32 event_id;
497 			bool db_enabled;
498 		} its_vmovi_cmd;
499 
500 		struct {
501 			struct its_vpe *vpe;
502 			struct its_collection *col;
503 			u16 seq_num;
504 			u16 its_list;
505 		} its_vmovp_cmd;
506 
507 		struct {
508 			struct its_vpe *vpe;
509 		} its_invdb_cmd;
510 
511 		struct {
512 			struct its_vpe *vpe;
513 			u8 sgi;
514 			u8 priority;
515 			bool enable;
516 			bool group;
517 			bool clear;
518 		} its_vsgi_cmd;
519 	};
520 };
521 
522 /*
523  * The ITS command block, which is what the ITS actually parses.
524  */
525 struct its_cmd_block {
526 	union {
527 		u64	raw_cmd[4];
528 		__le64	raw_cmd_le[4];
529 	};
530 };
531 
532 #define ITS_CMD_QUEUE_SZ		SZ_64K
533 #define ITS_CMD_QUEUE_NR_ENTRIES	(ITS_CMD_QUEUE_SZ / sizeof(struct its_cmd_block))
534 
535 typedef struct its_collection *(*its_cmd_builder_t)(struct its_node *,
536 						    struct its_cmd_block *,
537 						    struct its_cmd_desc *);
538 
539 typedef struct its_vpe *(*its_cmd_vbuilder_t)(struct its_node *,
540 					      struct its_cmd_block *,
541 					      struct its_cmd_desc *);
542 
543 static void its_mask_encode(u64 *raw_cmd, u64 val, int h, int l)
544 {
545 	u64 mask = GENMASK_ULL(h, l);
546 	*raw_cmd &= ~mask;
547 	*raw_cmd |= (val << l) & mask;
548 }
549 
550 static void its_encode_cmd(struct its_cmd_block *cmd, u8 cmd_nr)
551 {
552 	its_mask_encode(&cmd->raw_cmd[0], cmd_nr, 7, 0);
553 }
554 
555 static void its_encode_devid(struct its_cmd_block *cmd, u32 devid)
556 {
557 	its_mask_encode(&cmd->raw_cmd[0], devid, 63, 32);
558 }
559 
560 static void its_encode_event_id(struct its_cmd_block *cmd, u32 id)
561 {
562 	its_mask_encode(&cmd->raw_cmd[1], id, 31, 0);
563 }
564 
565 static void its_encode_phys_id(struct its_cmd_block *cmd, u32 phys_id)
566 {
567 	its_mask_encode(&cmd->raw_cmd[1], phys_id, 63, 32);
568 }
569 
570 static void its_encode_size(struct its_cmd_block *cmd, u8 size)
571 {
572 	its_mask_encode(&cmd->raw_cmd[1], size, 4, 0);
573 }
574 
575 static void its_encode_itt(struct its_cmd_block *cmd, u64 itt_addr)
576 {
577 	its_mask_encode(&cmd->raw_cmd[2], itt_addr >> 8, 51, 8);
578 }
579 
580 static void its_encode_valid(struct its_cmd_block *cmd, int valid)
581 {
582 	its_mask_encode(&cmd->raw_cmd[2], !!valid, 63, 63);
583 }
584 
585 static void its_encode_target(struct its_cmd_block *cmd, u64 target_addr)
586 {
587 	its_mask_encode(&cmd->raw_cmd[2], target_addr >> 16, 51, 16);
588 }
589 
590 static void its_encode_collection(struct its_cmd_block *cmd, u16 col)
591 {
592 	its_mask_encode(&cmd->raw_cmd[2], col, 15, 0);
593 }
594 
595 static void its_encode_vpeid(struct its_cmd_block *cmd, u16 vpeid)
596 {
597 	its_mask_encode(&cmd->raw_cmd[1], vpeid, 47, 32);
598 }
599 
600 static void its_encode_virt_id(struct its_cmd_block *cmd, u32 virt_id)
601 {
602 	its_mask_encode(&cmd->raw_cmd[2], virt_id, 31, 0);
603 }
604 
605 static void its_encode_db_phys_id(struct its_cmd_block *cmd, u32 db_phys_id)
606 {
607 	its_mask_encode(&cmd->raw_cmd[2], db_phys_id, 63, 32);
608 }
609 
610 static void its_encode_db_valid(struct its_cmd_block *cmd, bool db_valid)
611 {
612 	its_mask_encode(&cmd->raw_cmd[2], db_valid, 0, 0);
613 }
614 
615 static void its_encode_seq_num(struct its_cmd_block *cmd, u16 seq_num)
616 {
617 	its_mask_encode(&cmd->raw_cmd[0], seq_num, 47, 32);
618 }
619 
620 static void its_encode_its_list(struct its_cmd_block *cmd, u16 its_list)
621 {
622 	its_mask_encode(&cmd->raw_cmd[1], its_list, 15, 0);
623 }
624 
625 static void its_encode_vpt_addr(struct its_cmd_block *cmd, u64 vpt_pa)
626 {
627 	its_mask_encode(&cmd->raw_cmd[3], vpt_pa >> 16, 51, 16);
628 }
629 
630 static void its_encode_vpt_size(struct its_cmd_block *cmd, u8 vpt_size)
631 {
632 	its_mask_encode(&cmd->raw_cmd[3], vpt_size, 4, 0);
633 }
634 
635 static void its_encode_vconf_addr(struct its_cmd_block *cmd, u64 vconf_pa)
636 {
637 	its_mask_encode(&cmd->raw_cmd[0], vconf_pa >> 16, 51, 16);
638 }
639 
640 static void its_encode_alloc(struct its_cmd_block *cmd, bool alloc)
641 {
642 	its_mask_encode(&cmd->raw_cmd[0], alloc, 8, 8);
643 }
644 
645 static void its_encode_ptz(struct its_cmd_block *cmd, bool ptz)
646 {
647 	its_mask_encode(&cmd->raw_cmd[0], ptz, 9, 9);
648 }
649 
650 static void its_encode_vmapp_default_db(struct its_cmd_block *cmd,
651 					u32 vpe_db_lpi)
652 {
653 	its_mask_encode(&cmd->raw_cmd[1], vpe_db_lpi, 31, 0);
654 }
655 
656 static void its_encode_vmovp_default_db(struct its_cmd_block *cmd,
657 					u32 vpe_db_lpi)
658 {
659 	its_mask_encode(&cmd->raw_cmd[3], vpe_db_lpi, 31, 0);
660 }
661 
662 static void its_encode_db(struct its_cmd_block *cmd, bool db)
663 {
664 	its_mask_encode(&cmd->raw_cmd[2], db, 63, 63);
665 }
666 
667 static void its_encode_sgi_intid(struct its_cmd_block *cmd, u8 sgi)
668 {
669 	its_mask_encode(&cmd->raw_cmd[0], sgi, 35, 32);
670 }
671 
672 static void its_encode_sgi_priority(struct its_cmd_block *cmd, u8 prio)
673 {
674 	its_mask_encode(&cmd->raw_cmd[0], prio >> 4, 23, 20);
675 }
676 
677 static void its_encode_sgi_group(struct its_cmd_block *cmd, bool grp)
678 {
679 	its_mask_encode(&cmd->raw_cmd[0], grp, 10, 10);
680 }
681 
682 static void its_encode_sgi_clear(struct its_cmd_block *cmd, bool clr)
683 {
684 	its_mask_encode(&cmd->raw_cmd[0], clr, 9, 9);
685 }
686 
687 static void its_encode_sgi_enable(struct its_cmd_block *cmd, bool en)
688 {
689 	its_mask_encode(&cmd->raw_cmd[0], en, 8, 8);
690 }
691 
692 static inline void its_fixup_cmd(struct its_cmd_block *cmd)
693 {
694 	/* Let's fixup BE commands */
695 	cmd->raw_cmd_le[0] = cpu_to_le64(cmd->raw_cmd[0]);
696 	cmd->raw_cmd_le[1] = cpu_to_le64(cmd->raw_cmd[1]);
697 	cmd->raw_cmd_le[2] = cpu_to_le64(cmd->raw_cmd[2]);
698 	cmd->raw_cmd_le[3] = cpu_to_le64(cmd->raw_cmd[3]);
699 }
700 
701 static struct its_collection *its_build_mapd_cmd(struct its_node *its,
702 						 struct its_cmd_block *cmd,
703 						 struct its_cmd_desc *desc)
704 {
705 	unsigned long itt_addr;
706 	u8 size = ilog2(desc->its_mapd_cmd.dev->nr_ites);
707 
708 	itt_addr = virt_to_phys(desc->its_mapd_cmd.dev->itt);
709 
710 	its_encode_cmd(cmd, GITS_CMD_MAPD);
711 	its_encode_devid(cmd, desc->its_mapd_cmd.dev->device_id);
712 	its_encode_size(cmd, size - 1);
713 	its_encode_itt(cmd, itt_addr);
714 	its_encode_valid(cmd, desc->its_mapd_cmd.valid);
715 
716 	its_fixup_cmd(cmd);
717 
718 	return NULL;
719 }
720 
721 static struct its_collection *its_build_mapc_cmd(struct its_node *its,
722 						 struct its_cmd_block *cmd,
723 						 struct its_cmd_desc *desc)
724 {
725 	its_encode_cmd(cmd, GITS_CMD_MAPC);
726 	its_encode_collection(cmd, desc->its_mapc_cmd.col->col_id);
727 	its_encode_target(cmd, desc->its_mapc_cmd.col->target_address);
728 	its_encode_valid(cmd, desc->its_mapc_cmd.valid);
729 
730 	its_fixup_cmd(cmd);
731 
732 	return desc->its_mapc_cmd.col;
733 }
734 
735 static struct its_collection *its_build_mapti_cmd(struct its_node *its,
736 						  struct its_cmd_block *cmd,
737 						  struct its_cmd_desc *desc)
738 {
739 	struct its_collection *col;
740 
741 	col = dev_event_to_col(desc->its_mapti_cmd.dev,
742 			       desc->its_mapti_cmd.event_id);
743 
744 	its_encode_cmd(cmd, GITS_CMD_MAPTI);
745 	its_encode_devid(cmd, desc->its_mapti_cmd.dev->device_id);
746 	its_encode_event_id(cmd, desc->its_mapti_cmd.event_id);
747 	its_encode_phys_id(cmd, desc->its_mapti_cmd.phys_id);
748 	its_encode_collection(cmd, col->col_id);
749 
750 	its_fixup_cmd(cmd);
751 
752 	return valid_col(col);
753 }
754 
755 static struct its_collection *its_build_movi_cmd(struct its_node *its,
756 						 struct its_cmd_block *cmd,
757 						 struct its_cmd_desc *desc)
758 {
759 	struct its_collection *col;
760 
761 	col = dev_event_to_col(desc->its_movi_cmd.dev,
762 			       desc->its_movi_cmd.event_id);
763 
764 	its_encode_cmd(cmd, GITS_CMD_MOVI);
765 	its_encode_devid(cmd, desc->its_movi_cmd.dev->device_id);
766 	its_encode_event_id(cmd, desc->its_movi_cmd.event_id);
767 	its_encode_collection(cmd, desc->its_movi_cmd.col->col_id);
768 
769 	its_fixup_cmd(cmd);
770 
771 	return valid_col(col);
772 }
773 
774 static struct its_collection *its_build_discard_cmd(struct its_node *its,
775 						    struct its_cmd_block *cmd,
776 						    struct its_cmd_desc *desc)
777 {
778 	struct its_collection *col;
779 
780 	col = dev_event_to_col(desc->its_discard_cmd.dev,
781 			       desc->its_discard_cmd.event_id);
782 
783 	its_encode_cmd(cmd, GITS_CMD_DISCARD);
784 	its_encode_devid(cmd, desc->its_discard_cmd.dev->device_id);
785 	its_encode_event_id(cmd, desc->its_discard_cmd.event_id);
786 
787 	its_fixup_cmd(cmd);
788 
789 	return valid_col(col);
790 }
791 
792 static struct its_collection *its_build_inv_cmd(struct its_node *its,
793 						struct its_cmd_block *cmd,
794 						struct its_cmd_desc *desc)
795 {
796 	struct its_collection *col;
797 
798 	col = dev_event_to_col(desc->its_inv_cmd.dev,
799 			       desc->its_inv_cmd.event_id);
800 
801 	its_encode_cmd(cmd, GITS_CMD_INV);
802 	its_encode_devid(cmd, desc->its_inv_cmd.dev->device_id);
803 	its_encode_event_id(cmd, desc->its_inv_cmd.event_id);
804 
805 	its_fixup_cmd(cmd);
806 
807 	return valid_col(col);
808 }
809 
810 static struct its_collection *its_build_int_cmd(struct its_node *its,
811 						struct its_cmd_block *cmd,
812 						struct its_cmd_desc *desc)
813 {
814 	struct its_collection *col;
815 
816 	col = dev_event_to_col(desc->its_int_cmd.dev,
817 			       desc->its_int_cmd.event_id);
818 
819 	its_encode_cmd(cmd, GITS_CMD_INT);
820 	its_encode_devid(cmd, desc->its_int_cmd.dev->device_id);
821 	its_encode_event_id(cmd, desc->its_int_cmd.event_id);
822 
823 	its_fixup_cmd(cmd);
824 
825 	return valid_col(col);
826 }
827 
828 static struct its_collection *its_build_clear_cmd(struct its_node *its,
829 						  struct its_cmd_block *cmd,
830 						  struct its_cmd_desc *desc)
831 {
832 	struct its_collection *col;
833 
834 	col = dev_event_to_col(desc->its_clear_cmd.dev,
835 			       desc->its_clear_cmd.event_id);
836 
837 	its_encode_cmd(cmd, GITS_CMD_CLEAR);
838 	its_encode_devid(cmd, desc->its_clear_cmd.dev->device_id);
839 	its_encode_event_id(cmd, desc->its_clear_cmd.event_id);
840 
841 	its_fixup_cmd(cmd);
842 
843 	return valid_col(col);
844 }
845 
846 static struct its_collection *its_build_invall_cmd(struct its_node *its,
847 						   struct its_cmd_block *cmd,
848 						   struct its_cmd_desc *desc)
849 {
850 	its_encode_cmd(cmd, GITS_CMD_INVALL);
851 	its_encode_collection(cmd, desc->its_invall_cmd.col->col_id);
852 
853 	its_fixup_cmd(cmd);
854 
855 	return desc->its_invall_cmd.col;
856 }
857 
858 static struct its_vpe *its_build_vinvall_cmd(struct its_node *its,
859 					     struct its_cmd_block *cmd,
860 					     struct its_cmd_desc *desc)
861 {
862 	its_encode_cmd(cmd, GITS_CMD_VINVALL);
863 	its_encode_vpeid(cmd, desc->its_vinvall_cmd.vpe->vpe_id);
864 
865 	its_fixup_cmd(cmd);
866 
867 	return valid_vpe(its, desc->its_vinvall_cmd.vpe);
868 }
869 
870 static struct its_vpe *its_build_vmapp_cmd(struct its_node *its,
871 					   struct its_cmd_block *cmd,
872 					   struct its_cmd_desc *desc)
873 {
874 	struct its_vpe *vpe = valid_vpe(its, desc->its_vmapp_cmd.vpe);
875 	unsigned long vpt_addr, vconf_addr;
876 	u64 target;
877 	bool alloc;
878 
879 	its_encode_cmd(cmd, GITS_CMD_VMAPP);
880 	its_encode_vpeid(cmd, desc->its_vmapp_cmd.vpe->vpe_id);
881 	its_encode_valid(cmd, desc->its_vmapp_cmd.valid);
882 
883 	if (!desc->its_vmapp_cmd.valid) {
884 		alloc = !atomic_dec_return(&desc->its_vmapp_cmd.vpe->vmapp_count);
885 		if (is_v4_1(its)) {
886 			its_encode_alloc(cmd, alloc);
887 			/*
888 			 * Unmapping a VPE is self-synchronizing on GICv4.1,
889 			 * no need to issue a VSYNC.
890 			 */
891 			vpe = NULL;
892 		}
893 
894 		goto out;
895 	}
896 
897 	vpt_addr = virt_to_phys(page_address(desc->its_vmapp_cmd.vpe->vpt_page));
898 	target = desc->its_vmapp_cmd.col->target_address + its->vlpi_redist_offset;
899 
900 	its_encode_target(cmd, target);
901 	its_encode_vpt_addr(cmd, vpt_addr);
902 	its_encode_vpt_size(cmd, LPI_NRBITS - 1);
903 
904 	alloc = !atomic_fetch_inc(&desc->its_vmapp_cmd.vpe->vmapp_count);
905 
906 	if (!is_v4_1(its))
907 		goto out;
908 
909 	vconf_addr = virt_to_phys(page_address(desc->its_vmapp_cmd.vpe->its_vm->vprop_page));
910 
911 	its_encode_alloc(cmd, alloc);
912 
913 	/*
914 	 * GICv4.1 provides a way to get the VLPI state, which needs the vPE
915 	 * to be unmapped first, and in this case, we may remap the vPE
916 	 * back while the VPT is not empty. So we can't assume that the
917 	 * VPT is empty on map. This is why we never advertise PTZ.
918 	 */
919 	its_encode_ptz(cmd, false);
920 	its_encode_vconf_addr(cmd, vconf_addr);
921 	its_encode_vmapp_default_db(cmd, desc->its_vmapp_cmd.vpe->vpe_db_lpi);
922 
923 out:
924 	its_fixup_cmd(cmd);
925 
926 	return vpe;
927 }
928 
929 static struct its_vpe *its_build_vmapti_cmd(struct its_node *its,
930 					    struct its_cmd_block *cmd,
931 					    struct its_cmd_desc *desc)
932 {
933 	u32 db;
934 
935 	if (!is_v4_1(its) && desc->its_vmapti_cmd.db_enabled)
936 		db = desc->its_vmapti_cmd.vpe->vpe_db_lpi;
937 	else
938 		db = 1023;
939 
940 	its_encode_cmd(cmd, GITS_CMD_VMAPTI);
941 	its_encode_devid(cmd, desc->its_vmapti_cmd.dev->device_id);
942 	its_encode_vpeid(cmd, desc->its_vmapti_cmd.vpe->vpe_id);
943 	its_encode_event_id(cmd, desc->its_vmapti_cmd.event_id);
944 	its_encode_db_phys_id(cmd, db);
945 	its_encode_virt_id(cmd, desc->its_vmapti_cmd.virt_id);
946 
947 	its_fixup_cmd(cmd);
948 
949 	return valid_vpe(its, desc->its_vmapti_cmd.vpe);
950 }
951 
952 static struct its_vpe *its_build_vmovi_cmd(struct its_node *its,
953 					   struct its_cmd_block *cmd,
954 					   struct its_cmd_desc *desc)
955 {
956 	u32 db;
957 
958 	if (!is_v4_1(its) && desc->its_vmovi_cmd.db_enabled)
959 		db = desc->its_vmovi_cmd.vpe->vpe_db_lpi;
960 	else
961 		db = 1023;
962 
963 	its_encode_cmd(cmd, GITS_CMD_VMOVI);
964 	its_encode_devid(cmd, desc->its_vmovi_cmd.dev->device_id);
965 	its_encode_vpeid(cmd, desc->its_vmovi_cmd.vpe->vpe_id);
966 	its_encode_event_id(cmd, desc->its_vmovi_cmd.event_id);
967 	its_encode_db_phys_id(cmd, db);
968 	its_encode_db_valid(cmd, true);
969 
970 	its_fixup_cmd(cmd);
971 
972 	return valid_vpe(its, desc->its_vmovi_cmd.vpe);
973 }
974 
975 static struct its_vpe *its_build_vmovp_cmd(struct its_node *its,
976 					   struct its_cmd_block *cmd,
977 					   struct its_cmd_desc *desc)
978 {
979 	u64 target;
980 
981 	target = desc->its_vmovp_cmd.col->target_address + its->vlpi_redist_offset;
982 	its_encode_cmd(cmd, GITS_CMD_VMOVP);
983 	its_encode_seq_num(cmd, desc->its_vmovp_cmd.seq_num);
984 	its_encode_its_list(cmd, desc->its_vmovp_cmd.its_list);
985 	its_encode_vpeid(cmd, desc->its_vmovp_cmd.vpe->vpe_id);
986 	its_encode_target(cmd, target);
987 
988 	if (is_v4_1(its)) {
989 		its_encode_db(cmd, true);
990 		its_encode_vmovp_default_db(cmd, desc->its_vmovp_cmd.vpe->vpe_db_lpi);
991 	}
992 
993 	its_fixup_cmd(cmd);
994 
995 	return valid_vpe(its, desc->its_vmovp_cmd.vpe);
996 }
997 
998 static struct its_vpe *its_build_vinv_cmd(struct its_node *its,
999 					  struct its_cmd_block *cmd,
1000 					  struct its_cmd_desc *desc)
1001 {
1002 	struct its_vlpi_map *map;
1003 
1004 	map = dev_event_to_vlpi_map(desc->its_inv_cmd.dev,
1005 				    desc->its_inv_cmd.event_id);
1006 
1007 	its_encode_cmd(cmd, GITS_CMD_INV);
1008 	its_encode_devid(cmd, desc->its_inv_cmd.dev->device_id);
1009 	its_encode_event_id(cmd, desc->its_inv_cmd.event_id);
1010 
1011 	its_fixup_cmd(cmd);
1012 
1013 	return valid_vpe(its, map->vpe);
1014 }
1015 
1016 static struct its_vpe *its_build_vint_cmd(struct its_node *its,
1017 					  struct its_cmd_block *cmd,
1018 					  struct its_cmd_desc *desc)
1019 {
1020 	struct its_vlpi_map *map;
1021 
1022 	map = dev_event_to_vlpi_map(desc->its_int_cmd.dev,
1023 				    desc->its_int_cmd.event_id);
1024 
1025 	its_encode_cmd(cmd, GITS_CMD_INT);
1026 	its_encode_devid(cmd, desc->its_int_cmd.dev->device_id);
1027 	its_encode_event_id(cmd, desc->its_int_cmd.event_id);
1028 
1029 	its_fixup_cmd(cmd);
1030 
1031 	return valid_vpe(its, map->vpe);
1032 }
1033 
1034 static struct its_vpe *its_build_vclear_cmd(struct its_node *its,
1035 					    struct its_cmd_block *cmd,
1036 					    struct its_cmd_desc *desc)
1037 {
1038 	struct its_vlpi_map *map;
1039 
1040 	map = dev_event_to_vlpi_map(desc->its_clear_cmd.dev,
1041 				    desc->its_clear_cmd.event_id);
1042 
1043 	its_encode_cmd(cmd, GITS_CMD_CLEAR);
1044 	its_encode_devid(cmd, desc->its_clear_cmd.dev->device_id);
1045 	its_encode_event_id(cmd, desc->its_clear_cmd.event_id);
1046 
1047 	its_fixup_cmd(cmd);
1048 
1049 	return valid_vpe(its, map->vpe);
1050 }
1051 
1052 static struct its_vpe *its_build_invdb_cmd(struct its_node *its,
1053 					   struct its_cmd_block *cmd,
1054 					   struct its_cmd_desc *desc)
1055 {
1056 	if (WARN_ON(!is_v4_1(its)))
1057 		return NULL;
1058 
1059 	its_encode_cmd(cmd, GITS_CMD_INVDB);
1060 	its_encode_vpeid(cmd, desc->its_invdb_cmd.vpe->vpe_id);
1061 
1062 	its_fixup_cmd(cmd);
1063 
1064 	return valid_vpe(its, desc->its_invdb_cmd.vpe);
1065 }
1066 
1067 static struct its_vpe *its_build_vsgi_cmd(struct its_node *its,
1068 					  struct its_cmd_block *cmd,
1069 					  struct its_cmd_desc *desc)
1070 {
1071 	if (WARN_ON(!is_v4_1(its)))
1072 		return NULL;
1073 
1074 	its_encode_cmd(cmd, GITS_CMD_VSGI);
1075 	its_encode_vpeid(cmd, desc->its_vsgi_cmd.vpe->vpe_id);
1076 	its_encode_sgi_intid(cmd, desc->its_vsgi_cmd.sgi);
1077 	its_encode_sgi_priority(cmd, desc->its_vsgi_cmd.priority);
1078 	its_encode_sgi_group(cmd, desc->its_vsgi_cmd.group);
1079 	its_encode_sgi_clear(cmd, desc->its_vsgi_cmd.clear);
1080 	its_encode_sgi_enable(cmd, desc->its_vsgi_cmd.enable);
1081 
1082 	its_fixup_cmd(cmd);
1083 
1084 	return valid_vpe(its, desc->its_vsgi_cmd.vpe);
1085 }
1086 
1087 static u64 its_cmd_ptr_to_offset(struct its_node *its,
1088 				 struct its_cmd_block *ptr)
1089 {
1090 	return (ptr - its->cmd_base) * sizeof(*ptr);
1091 }
1092 
1093 static int its_queue_full(struct its_node *its)
1094 {
1095 	int widx;
1096 	int ridx;
1097 
1098 	widx = its->cmd_write - its->cmd_base;
1099 	ridx = readl_relaxed(its->base + GITS_CREADR) / sizeof(struct its_cmd_block);
1100 
1101 	/* This is incredibly unlikely to happen, unless the ITS locks up. */
1102 	if (((widx + 1) % ITS_CMD_QUEUE_NR_ENTRIES) == ridx)
1103 		return 1;
1104 
1105 	return 0;
1106 }
1107 
1108 static struct its_cmd_block *its_allocate_entry(struct its_node *its)
1109 {
1110 	struct its_cmd_block *cmd;
1111 	u32 count = 1000000;	/* 1s! */
1112 
1113 	while (its_queue_full(its)) {
1114 		count--;
1115 		if (!count) {
1116 			pr_err_ratelimited("ITS queue not draining\n");
1117 			return NULL;
1118 		}
1119 		cpu_relax();
1120 		udelay(1);
1121 	}
1122 
1123 	cmd = its->cmd_write++;
1124 
1125 	/* Handle queue wrapping */
1126 	if (its->cmd_write == (its->cmd_base + ITS_CMD_QUEUE_NR_ENTRIES))
1127 		its->cmd_write = its->cmd_base;
1128 
1129 	/* Clear command  */
1130 	cmd->raw_cmd[0] = 0;
1131 	cmd->raw_cmd[1] = 0;
1132 	cmd->raw_cmd[2] = 0;
1133 	cmd->raw_cmd[3] = 0;
1134 
1135 	return cmd;
1136 }
1137 
1138 static struct its_cmd_block *its_post_commands(struct its_node *its)
1139 {
1140 	u64 wr = its_cmd_ptr_to_offset(its, its->cmd_write);
1141 
1142 	writel_relaxed(wr, its->base + GITS_CWRITER);
1143 
1144 	return its->cmd_write;
1145 }
1146 
1147 static void its_flush_cmd(struct its_node *its, struct its_cmd_block *cmd)
1148 {
1149 	/*
1150 	 * Make sure the commands written to memory are observable by
1151 	 * the ITS.
1152 	 */
1153 	if (its->flags & ITS_FLAGS_CMDQ_NEEDS_FLUSHING)
1154 		gic_flush_dcache_to_poc(cmd, sizeof(*cmd));
1155 	else
1156 		dsb(ishst);
1157 }
1158 
1159 static int its_wait_for_range_completion(struct its_node *its,
1160 					 u64	prev_idx,
1161 					 struct its_cmd_block *to)
1162 {
1163 	u64 rd_idx, to_idx, linear_idx;
1164 	u32 count = 1000000;	/* 1s! */
1165 
1166 	/* Linearize to_idx if the command set has wrapped around */
1167 	to_idx = its_cmd_ptr_to_offset(its, to);
1168 	if (to_idx < prev_idx)
1169 		to_idx += ITS_CMD_QUEUE_SZ;
1170 
1171 	linear_idx = prev_idx;
1172 
1173 	while (1) {
1174 		s64 delta;
1175 
1176 		rd_idx = readl_relaxed(its->base + GITS_CREADR);
1177 
1178 		/*
1179 		 * Compute the read pointer progress, taking the
1180 		 * potential wrap-around into account.
1181 		 */
1182 		delta = rd_idx - prev_idx;
1183 		if (rd_idx < prev_idx)
1184 			delta += ITS_CMD_QUEUE_SZ;
1185 
1186 		linear_idx += delta;
1187 		if (linear_idx >= to_idx)
1188 			break;
1189 
1190 		count--;
1191 		if (!count) {
1192 			pr_err_ratelimited("ITS queue timeout (%llu %llu)\n",
1193 					   to_idx, linear_idx);
1194 			return -1;
1195 		}
1196 		prev_idx = rd_idx;
1197 		cpu_relax();
1198 		udelay(1);
1199 	}
1200 
1201 	return 0;
1202 }
1203 
1204 /* Warning, macro hell follows */
1205 #define BUILD_SINGLE_CMD_FUNC(name, buildtype, synctype, buildfn)	\
1206 void name(struct its_node *its,						\
1207 	  buildtype builder,						\
1208 	  struct its_cmd_desc *desc)					\
1209 {									\
1210 	struct its_cmd_block *cmd, *sync_cmd, *next_cmd;		\
1211 	synctype *sync_obj;						\
1212 	unsigned long flags;						\
1213 	u64 rd_idx;							\
1214 									\
1215 	raw_spin_lock_irqsave(&its->lock, flags);			\
1216 									\
1217 	cmd = its_allocate_entry(its);					\
1218 	if (!cmd) {		/* We're soooooo screewed... */		\
1219 		raw_spin_unlock_irqrestore(&its->lock, flags);		\
1220 		return;							\
1221 	}								\
1222 	sync_obj = builder(its, cmd, desc);				\
1223 	its_flush_cmd(its, cmd);					\
1224 									\
1225 	if (sync_obj) {							\
1226 		sync_cmd = its_allocate_entry(its);			\
1227 		if (!sync_cmd)						\
1228 			goto post;					\
1229 									\
1230 		buildfn(its, sync_cmd, sync_obj);			\
1231 		its_flush_cmd(its, sync_cmd);				\
1232 	}								\
1233 									\
1234 post:									\
1235 	rd_idx = readl_relaxed(its->base + GITS_CREADR);		\
1236 	next_cmd = its_post_commands(its);				\
1237 	raw_spin_unlock_irqrestore(&its->lock, flags);			\
1238 									\
1239 	if (its_wait_for_range_completion(its, rd_idx, next_cmd))	\
1240 		pr_err_ratelimited("ITS cmd %ps failed\n", builder);	\
1241 }
1242 
1243 static void its_build_sync_cmd(struct its_node *its,
1244 			       struct its_cmd_block *sync_cmd,
1245 			       struct its_collection *sync_col)
1246 {
1247 	its_encode_cmd(sync_cmd, GITS_CMD_SYNC);
1248 	its_encode_target(sync_cmd, sync_col->target_address);
1249 
1250 	its_fixup_cmd(sync_cmd);
1251 }
1252 
1253 static BUILD_SINGLE_CMD_FUNC(its_send_single_command, its_cmd_builder_t,
1254 			     struct its_collection, its_build_sync_cmd)
1255 
1256 static void its_build_vsync_cmd(struct its_node *its,
1257 				struct its_cmd_block *sync_cmd,
1258 				struct its_vpe *sync_vpe)
1259 {
1260 	its_encode_cmd(sync_cmd, GITS_CMD_VSYNC);
1261 	its_encode_vpeid(sync_cmd, sync_vpe->vpe_id);
1262 
1263 	its_fixup_cmd(sync_cmd);
1264 }
1265 
1266 static BUILD_SINGLE_CMD_FUNC(its_send_single_vcommand, its_cmd_vbuilder_t,
1267 			     struct its_vpe, its_build_vsync_cmd)
1268 
1269 static void its_send_int(struct its_device *dev, u32 event_id)
1270 {
1271 	struct its_cmd_desc desc;
1272 
1273 	desc.its_int_cmd.dev = dev;
1274 	desc.its_int_cmd.event_id = event_id;
1275 
1276 	its_send_single_command(dev->its, its_build_int_cmd, &desc);
1277 }
1278 
1279 static void its_send_clear(struct its_device *dev, u32 event_id)
1280 {
1281 	struct its_cmd_desc desc;
1282 
1283 	desc.its_clear_cmd.dev = dev;
1284 	desc.its_clear_cmd.event_id = event_id;
1285 
1286 	its_send_single_command(dev->its, its_build_clear_cmd, &desc);
1287 }
1288 
1289 static void its_send_inv(struct its_device *dev, u32 event_id)
1290 {
1291 	struct its_cmd_desc desc;
1292 
1293 	desc.its_inv_cmd.dev = dev;
1294 	desc.its_inv_cmd.event_id = event_id;
1295 
1296 	its_send_single_command(dev->its, its_build_inv_cmd, &desc);
1297 }
1298 
1299 static void its_send_mapd(struct its_device *dev, int valid)
1300 {
1301 	struct its_cmd_desc desc;
1302 
1303 	desc.its_mapd_cmd.dev = dev;
1304 	desc.its_mapd_cmd.valid = !!valid;
1305 
1306 	its_send_single_command(dev->its, its_build_mapd_cmd, &desc);
1307 }
1308 
1309 static void its_send_mapc(struct its_node *its, struct its_collection *col,
1310 			  int valid)
1311 {
1312 	struct its_cmd_desc desc;
1313 
1314 	desc.its_mapc_cmd.col = col;
1315 	desc.its_mapc_cmd.valid = !!valid;
1316 
1317 	its_send_single_command(its, its_build_mapc_cmd, &desc);
1318 }
1319 
1320 static void its_send_mapti(struct its_device *dev, u32 irq_id, u32 id)
1321 {
1322 	struct its_cmd_desc desc;
1323 
1324 	desc.its_mapti_cmd.dev = dev;
1325 	desc.its_mapti_cmd.phys_id = irq_id;
1326 	desc.its_mapti_cmd.event_id = id;
1327 
1328 	its_send_single_command(dev->its, its_build_mapti_cmd, &desc);
1329 }
1330 
1331 static void its_send_movi(struct its_device *dev,
1332 			  struct its_collection *col, u32 id)
1333 {
1334 	struct its_cmd_desc desc;
1335 
1336 	desc.its_movi_cmd.dev = dev;
1337 	desc.its_movi_cmd.col = col;
1338 	desc.its_movi_cmd.event_id = id;
1339 
1340 	its_send_single_command(dev->its, its_build_movi_cmd, &desc);
1341 }
1342 
1343 static void its_send_discard(struct its_device *dev, u32 id)
1344 {
1345 	struct its_cmd_desc desc;
1346 
1347 	desc.its_discard_cmd.dev = dev;
1348 	desc.its_discard_cmd.event_id = id;
1349 
1350 	its_send_single_command(dev->its, its_build_discard_cmd, &desc);
1351 }
1352 
1353 static void its_send_invall(struct its_node *its, struct its_collection *col)
1354 {
1355 	struct its_cmd_desc desc;
1356 
1357 	desc.its_invall_cmd.col = col;
1358 
1359 	its_send_single_command(its, its_build_invall_cmd, &desc);
1360 }
1361 
1362 static void its_send_vmapti(struct its_device *dev, u32 id)
1363 {
1364 	struct its_vlpi_map *map = dev_event_to_vlpi_map(dev, id);
1365 	struct its_cmd_desc desc;
1366 
1367 	desc.its_vmapti_cmd.vpe = map->vpe;
1368 	desc.its_vmapti_cmd.dev = dev;
1369 	desc.its_vmapti_cmd.virt_id = map->vintid;
1370 	desc.its_vmapti_cmd.event_id = id;
1371 	desc.its_vmapti_cmd.db_enabled = map->db_enabled;
1372 
1373 	its_send_single_vcommand(dev->its, its_build_vmapti_cmd, &desc);
1374 }
1375 
1376 static void its_send_vmovi(struct its_device *dev, u32 id)
1377 {
1378 	struct its_vlpi_map *map = dev_event_to_vlpi_map(dev, id);
1379 	struct its_cmd_desc desc;
1380 
1381 	desc.its_vmovi_cmd.vpe = map->vpe;
1382 	desc.its_vmovi_cmd.dev = dev;
1383 	desc.its_vmovi_cmd.event_id = id;
1384 	desc.its_vmovi_cmd.db_enabled = map->db_enabled;
1385 
1386 	its_send_single_vcommand(dev->its, its_build_vmovi_cmd, &desc);
1387 }
1388 
1389 static void its_send_vmapp(struct its_node *its,
1390 			   struct its_vpe *vpe, bool valid)
1391 {
1392 	struct its_cmd_desc desc;
1393 
1394 	desc.its_vmapp_cmd.vpe = vpe;
1395 	desc.its_vmapp_cmd.valid = valid;
1396 	desc.its_vmapp_cmd.col = &its->collections[vpe->col_idx];
1397 
1398 	its_send_single_vcommand(its, its_build_vmapp_cmd, &desc);
1399 }
1400 
1401 static void its_send_vmovp(struct its_vpe *vpe)
1402 {
1403 	struct its_cmd_desc desc = {};
1404 	struct its_node *its;
1405 	int col_id = vpe->col_idx;
1406 
1407 	desc.its_vmovp_cmd.vpe = vpe;
1408 
1409 	if (!its_list_map) {
1410 		its = list_first_entry(&its_nodes, struct its_node, entry);
1411 		desc.its_vmovp_cmd.col = &its->collections[col_id];
1412 		its_send_single_vcommand(its, its_build_vmovp_cmd, &desc);
1413 		return;
1414 	}
1415 
1416 	/*
1417 	 * Yet another marvel of the architecture. If using the
1418 	 * its_list "feature", we need to make sure that all ITSs
1419 	 * receive all VMOVP commands in the same order. The only way
1420 	 * to guarantee this is to make vmovp a serialization point.
1421 	 *
1422 	 * Wall <-- Head.
1423 	 */
1424 	guard(raw_spinlock)(&vmovp_lock);
1425 	desc.its_vmovp_cmd.seq_num = vmovp_seq_num++;
1426 	desc.its_vmovp_cmd.its_list = get_its_list(vpe->its_vm);
1427 
1428 	/* Emit VMOVPs */
1429 	list_for_each_entry(its, &its_nodes, entry) {
1430 		if (!is_v4(its))
1431 			continue;
1432 
1433 		if (!require_its_list_vmovp(vpe->its_vm, its))
1434 			continue;
1435 
1436 		desc.its_vmovp_cmd.col = &its->collections[col_id];
1437 		its_send_single_vcommand(its, its_build_vmovp_cmd, &desc);
1438 	}
1439 }
1440 
1441 static void its_send_vinvall(struct its_node *its, struct its_vpe *vpe)
1442 {
1443 	struct its_cmd_desc desc;
1444 
1445 	desc.its_vinvall_cmd.vpe = vpe;
1446 	its_send_single_vcommand(its, its_build_vinvall_cmd, &desc);
1447 }
1448 
1449 static void its_send_vinv(struct its_device *dev, u32 event_id)
1450 {
1451 	struct its_cmd_desc desc;
1452 
1453 	/*
1454 	 * There is no real VINV command. This is just a normal INV,
1455 	 * with a VSYNC instead of a SYNC.
1456 	 */
1457 	desc.its_inv_cmd.dev = dev;
1458 	desc.its_inv_cmd.event_id = event_id;
1459 
1460 	its_send_single_vcommand(dev->its, its_build_vinv_cmd, &desc);
1461 }
1462 
1463 static void its_send_vint(struct its_device *dev, u32 event_id)
1464 {
1465 	struct its_cmd_desc desc;
1466 
1467 	/*
1468 	 * There is no real VINT command. This is just a normal INT,
1469 	 * with a VSYNC instead of a SYNC.
1470 	 */
1471 	desc.its_int_cmd.dev = dev;
1472 	desc.its_int_cmd.event_id = event_id;
1473 
1474 	its_send_single_vcommand(dev->its, its_build_vint_cmd, &desc);
1475 }
1476 
1477 static void its_send_vclear(struct its_device *dev, u32 event_id)
1478 {
1479 	struct its_cmd_desc desc;
1480 
1481 	/*
1482 	 * There is no real VCLEAR command. This is just a normal CLEAR,
1483 	 * with a VSYNC instead of a SYNC.
1484 	 */
1485 	desc.its_clear_cmd.dev = dev;
1486 	desc.its_clear_cmd.event_id = event_id;
1487 
1488 	its_send_single_vcommand(dev->its, its_build_vclear_cmd, &desc);
1489 }
1490 
1491 static void its_send_invdb(struct its_node *its, struct its_vpe *vpe)
1492 {
1493 	struct its_cmd_desc desc;
1494 
1495 	desc.its_invdb_cmd.vpe = vpe;
1496 	its_send_single_vcommand(its, its_build_invdb_cmd, &desc);
1497 }
1498 
1499 /*
1500  * irqchip functions - assumes MSI, mostly.
1501  */
1502 static void lpi_write_config(struct irq_data *d, u8 clr, u8 set)
1503 {
1504 	struct its_vlpi_map *map = get_vlpi_map(d);
1505 	irq_hw_number_t hwirq;
1506 	void *va;
1507 	u8 *cfg;
1508 
1509 	if (map) {
1510 		va = page_address(map->vm->vprop_page);
1511 		hwirq = map->vintid;
1512 
1513 		/* Remember the updated property */
1514 		map->properties &= ~clr;
1515 		map->properties |= set | LPI_PROP_GROUP1;
1516 	} else {
1517 		va = gic_rdists->prop_table_va;
1518 		hwirq = d->hwirq;
1519 	}
1520 
1521 	cfg = va + hwirq - 8192;
1522 	*cfg &= ~clr;
1523 	*cfg |= set | LPI_PROP_GROUP1;
1524 
1525 	/*
1526 	 * Make the above write visible to the redistributors.
1527 	 * And yes, we're flushing exactly: One. Single. Byte.
1528 	 * Humpf...
1529 	 */
1530 	if (gic_rdists->flags & RDIST_FLAGS_PROPBASE_NEEDS_FLUSHING)
1531 		gic_flush_dcache_to_poc(cfg, sizeof(*cfg));
1532 	else
1533 		dsb(ishst);
1534 }
1535 
1536 static void wait_for_syncr(void __iomem *rdbase)
1537 {
1538 	while (readl_relaxed(rdbase + GICR_SYNCR) & 1)
1539 		cpu_relax();
1540 }
1541 
1542 static void __direct_lpi_inv(struct irq_data *d, u64 val)
1543 {
1544 	void __iomem *rdbase;
1545 	unsigned long flags;
1546 	int cpu;
1547 
1548 	/* Target the redistributor this LPI is currently routed to */
1549 	cpu = irq_to_cpuid_lock(d, &flags);
1550 	raw_spin_lock(&gic_data_rdist_cpu(cpu)->rd_lock);
1551 
1552 	rdbase = per_cpu_ptr(gic_rdists->rdist, cpu)->rd_base;
1553 	gic_write_lpir(val, rdbase + GICR_INVLPIR);
1554 	wait_for_syncr(rdbase);
1555 
1556 	raw_spin_unlock(&gic_data_rdist_cpu(cpu)->rd_lock);
1557 	irq_to_cpuid_unlock(d, flags);
1558 }
1559 
1560 static void direct_lpi_inv(struct irq_data *d)
1561 {
1562 	struct its_vlpi_map *map = get_vlpi_map(d);
1563 	u64 val;
1564 
1565 	if (map) {
1566 		struct its_device *its_dev = irq_data_get_irq_chip_data(d);
1567 
1568 		WARN_ON(!is_v4_1(its_dev->its));
1569 
1570 		val  = GICR_INVLPIR_V;
1571 		val |= FIELD_PREP(GICR_INVLPIR_VPEID, map->vpe->vpe_id);
1572 		val |= FIELD_PREP(GICR_INVLPIR_INTID, map->vintid);
1573 	} else {
1574 		val = d->hwirq;
1575 	}
1576 
1577 	__direct_lpi_inv(d, val);
1578 }
1579 
1580 static void lpi_update_config(struct irq_data *d, u8 clr, u8 set)
1581 {
1582 	struct its_device *its_dev = irq_data_get_irq_chip_data(d);
1583 
1584 	lpi_write_config(d, clr, set);
1585 	if (gic_rdists->has_direct_lpi &&
1586 	    (is_v4_1(its_dev->its) || !irqd_is_forwarded_to_vcpu(d)))
1587 		direct_lpi_inv(d);
1588 	else if (!irqd_is_forwarded_to_vcpu(d))
1589 		its_send_inv(its_dev, its_get_event_id(d));
1590 	else
1591 		its_send_vinv(its_dev, its_get_event_id(d));
1592 }
1593 
1594 static void its_vlpi_set_doorbell(struct irq_data *d, bool enable)
1595 {
1596 	struct its_device *its_dev = irq_data_get_irq_chip_data(d);
1597 	u32 event = its_get_event_id(d);
1598 	struct its_vlpi_map *map;
1599 
1600 	/*
1601 	 * GICv4.1 does away with the per-LPI nonsense, nothing to do
1602 	 * here.
1603 	 */
1604 	if (is_v4_1(its_dev->its))
1605 		return;
1606 
1607 	map = dev_event_to_vlpi_map(its_dev, event);
1608 
1609 	if (map->db_enabled == enable)
1610 		return;
1611 
1612 	map->db_enabled = enable;
1613 
1614 	/*
1615 	 * More fun with the architecture:
1616 	 *
1617 	 * Ideally, we'd issue a VMAPTI to set the doorbell to its LPI
1618 	 * value or to 1023, depending on the enable bit. But that
1619 	 * would be issuing a mapping for an /existing/ DevID+EventID
1620 	 * pair, which is UNPREDICTABLE. Instead, let's issue a VMOVI
1621 	 * to the /same/ vPE, using this opportunity to adjust the
1622 	 * doorbell. Mouahahahaha. We loves it, Precious.
1623 	 */
1624 	its_send_vmovi(its_dev, event);
1625 }
1626 
1627 static void its_mask_irq(struct irq_data *d)
1628 {
1629 	if (irqd_is_forwarded_to_vcpu(d))
1630 		its_vlpi_set_doorbell(d, false);
1631 
1632 	lpi_update_config(d, LPI_PROP_ENABLED, 0);
1633 }
1634 
1635 static void its_unmask_irq(struct irq_data *d)
1636 {
1637 	if (irqd_is_forwarded_to_vcpu(d))
1638 		its_vlpi_set_doorbell(d, true);
1639 
1640 	lpi_update_config(d, 0, LPI_PROP_ENABLED);
1641 }
1642 
1643 static __maybe_unused u32 its_read_lpi_count(struct irq_data *d, int cpu)
1644 {
1645 	if (irqd_affinity_is_managed(d))
1646 		return atomic_read(&per_cpu_ptr(&cpu_lpi_count, cpu)->managed);
1647 
1648 	return atomic_read(&per_cpu_ptr(&cpu_lpi_count, cpu)->unmanaged);
1649 }
1650 
1651 static void its_inc_lpi_count(struct irq_data *d, int cpu)
1652 {
1653 	if (irqd_affinity_is_managed(d))
1654 		atomic_inc(&per_cpu_ptr(&cpu_lpi_count, cpu)->managed);
1655 	else
1656 		atomic_inc(&per_cpu_ptr(&cpu_lpi_count, cpu)->unmanaged);
1657 }
1658 
1659 static void its_dec_lpi_count(struct irq_data *d, int cpu)
1660 {
1661 	if (irqd_affinity_is_managed(d))
1662 		atomic_dec(&per_cpu_ptr(&cpu_lpi_count, cpu)->managed);
1663 	else
1664 		atomic_dec(&per_cpu_ptr(&cpu_lpi_count, cpu)->unmanaged);
1665 }
1666 
1667 static unsigned int cpumask_pick_least_loaded(struct irq_data *d,
1668 					      const struct cpumask *cpu_mask)
1669 {
1670 	unsigned int cpu = nr_cpu_ids, tmp;
1671 	int count = S32_MAX;
1672 
1673 	for_each_cpu(tmp, cpu_mask) {
1674 		int this_count = its_read_lpi_count(d, tmp);
1675 		if (this_count < count) {
1676 			cpu = tmp;
1677 		        count = this_count;
1678 		}
1679 	}
1680 
1681 	return cpu;
1682 }
1683 
1684 /*
1685  * As suggested by Thomas Gleixner in:
1686  * https://lore.kernel.org/r/87h80q2aoc.fsf@nanos.tec.linutronix.de
1687  */
1688 static int its_select_cpu(struct irq_data *d,
1689 			  const struct cpumask *aff_mask)
1690 {
1691 	struct its_device *its_dev = irq_data_get_irq_chip_data(d);
1692 	static DEFINE_RAW_SPINLOCK(tmpmask_lock);
1693 	static struct cpumask __tmpmask;
1694 	struct cpumask *tmpmask;
1695 	unsigned long flags;
1696 	int cpu, node;
1697 	node = its_dev->its->numa_node;
1698 	tmpmask = &__tmpmask;
1699 
1700 	raw_spin_lock_irqsave(&tmpmask_lock, flags);
1701 
1702 	if (!irqd_affinity_is_managed(d)) {
1703 		/* First try the NUMA node */
1704 		if (node != NUMA_NO_NODE) {
1705 			/*
1706 			 * Try the intersection of the affinity mask and the
1707 			 * node mask (and the online mask, just to be safe).
1708 			 */
1709 			cpumask_and(tmpmask, cpumask_of_node(node), aff_mask);
1710 			cpumask_and(tmpmask, tmpmask, cpu_online_mask);
1711 
1712 			/*
1713 			 * Ideally, we would check if the mask is empty, and
1714 			 * try again on the full node here.
1715 			 *
1716 			 * But it turns out that the way ACPI describes the
1717 			 * affinity for ITSs only deals about memory, and
1718 			 * not target CPUs, so it cannot describe a single
1719 			 * ITS placed next to two NUMA nodes.
1720 			 *
1721 			 * Instead, just fallback on the online mask. This
1722 			 * diverges from Thomas' suggestion above.
1723 			 */
1724 			cpu = cpumask_pick_least_loaded(d, tmpmask);
1725 			if (cpu < nr_cpu_ids)
1726 				goto out;
1727 
1728 			/* If we can't cross sockets, give up */
1729 			if ((its_dev->its->flags & ITS_FLAGS_WORKAROUND_CAVIUM_23144))
1730 				goto out;
1731 
1732 			/* If the above failed, expand the search */
1733 		}
1734 
1735 		/* Try the intersection of the affinity and online masks */
1736 		cpumask_and(tmpmask, aff_mask, cpu_online_mask);
1737 
1738 		/* If that doesn't fly, the online mask is the last resort */
1739 		if (cpumask_empty(tmpmask))
1740 			cpumask_copy(tmpmask, cpu_online_mask);
1741 
1742 		cpu = cpumask_pick_least_loaded(d, tmpmask);
1743 	} else {
1744 		cpumask_copy(tmpmask, aff_mask);
1745 
1746 		/* If we cannot cross sockets, limit the search to that node */
1747 		if ((its_dev->its->flags & ITS_FLAGS_WORKAROUND_CAVIUM_23144) &&
1748 		    node != NUMA_NO_NODE)
1749 			cpumask_and(tmpmask, tmpmask, cpumask_of_node(node));
1750 
1751 		cpu = cpumask_pick_least_loaded(d, tmpmask);
1752 	}
1753 out:
1754 	raw_spin_unlock_irqrestore(&tmpmask_lock, flags);
1755 
1756 	pr_debug("IRQ%d -> %*pbl CPU%d\n", d->irq, cpumask_pr_args(aff_mask), cpu);
1757 	return cpu;
1758 }
1759 
1760 static int its_set_affinity(struct irq_data *d, const struct cpumask *mask_val,
1761 			    bool force)
1762 {
1763 	struct its_device *its_dev = irq_data_get_irq_chip_data(d);
1764 	struct its_collection *target_col;
1765 	u32 id = its_get_event_id(d);
1766 	int cpu, prev_cpu;
1767 
1768 	/* A forwarded interrupt should use irq_set_vcpu_affinity */
1769 	if (irqd_is_forwarded_to_vcpu(d))
1770 		return -EINVAL;
1771 
1772 	prev_cpu = its_dev->event_map.col_map[id];
1773 	its_dec_lpi_count(d, prev_cpu);
1774 
1775 	if (!force)
1776 		cpu = its_select_cpu(d, mask_val);
1777 	else
1778 		cpu = cpumask_pick_least_loaded(d, mask_val);
1779 
1780 	if (cpu < 0 || cpu >= nr_cpu_ids)
1781 		goto err;
1782 
1783 	/* don't set the affinity when the target cpu is same as current one */
1784 	if (cpu != prev_cpu) {
1785 		target_col = &its_dev->its->collections[cpu];
1786 		its_send_movi(its_dev, target_col, id);
1787 		its_dev->event_map.col_map[id] = cpu;
1788 		irq_data_update_effective_affinity(d, cpumask_of(cpu));
1789 	}
1790 
1791 	its_inc_lpi_count(d, cpu);
1792 
1793 	return IRQ_SET_MASK_OK_DONE;
1794 
1795 err:
1796 	its_inc_lpi_count(d, prev_cpu);
1797 	return -EINVAL;
1798 }
1799 
1800 static u64 its_irq_get_msi_base(struct its_device *its_dev)
1801 {
1802 	struct its_node *its = its_dev->its;
1803 
1804 	return its->phys_base + GITS_TRANSLATER;
1805 }
1806 
1807 static void its_irq_compose_msi_msg(struct irq_data *d, struct msi_msg *msg)
1808 {
1809 	struct its_device *its_dev = irq_data_get_irq_chip_data(d);
1810 	struct its_node *its;
1811 	u64 addr;
1812 
1813 	its = its_dev->its;
1814 	addr = its->get_msi_base(its_dev);
1815 
1816 	msg->address_lo		= lower_32_bits(addr);
1817 	msg->address_hi		= upper_32_bits(addr);
1818 	msg->data		= its_get_event_id(d);
1819 
1820 	iommu_dma_compose_msi_msg(irq_data_get_msi_desc(d), msg);
1821 }
1822 
1823 static int its_irq_set_irqchip_state(struct irq_data *d,
1824 				     enum irqchip_irq_state which,
1825 				     bool state)
1826 {
1827 	struct its_device *its_dev = irq_data_get_irq_chip_data(d);
1828 	u32 event = its_get_event_id(d);
1829 
1830 	if (which != IRQCHIP_STATE_PENDING)
1831 		return -EINVAL;
1832 
1833 	if (irqd_is_forwarded_to_vcpu(d)) {
1834 		if (state)
1835 			its_send_vint(its_dev, event);
1836 		else
1837 			its_send_vclear(its_dev, event);
1838 	} else {
1839 		if (state)
1840 			its_send_int(its_dev, event);
1841 		else
1842 			its_send_clear(its_dev, event);
1843 	}
1844 
1845 	return 0;
1846 }
1847 
1848 static int its_irq_retrigger(struct irq_data *d)
1849 {
1850 	return !its_irq_set_irqchip_state(d, IRQCHIP_STATE_PENDING, true);
1851 }
1852 
1853 /*
1854  * Two favourable cases:
1855  *
1856  * (a) Either we have a GICv4.1, and all vPEs have to be mapped at all times
1857  *     for vSGI delivery
1858  *
1859  * (b) Or the ITSs do not use a list map, meaning that VMOVP is cheap enough
1860  *     and we're better off mapping all VPEs always
1861  *
1862  * If neither (a) nor (b) is true, then we map vPEs on demand.
1863  *
1864  */
1865 static bool gic_requires_eager_mapping(void)
1866 {
1867 	if (!its_list_map || gic_rdists->has_rvpeid)
1868 		return true;
1869 
1870 	return false;
1871 }
1872 
1873 static void its_map_vm(struct its_node *its, struct its_vm *vm)
1874 {
1875 	if (gic_requires_eager_mapping())
1876 		return;
1877 
1878 	guard(raw_spinlock_irqsave)(&vm->vmapp_lock);
1879 
1880 	/*
1881 	 * If the VM wasn't mapped yet, iterate over the vpes and get
1882 	 * them mapped now.
1883 	 */
1884 	vm->vlpi_count[its->list_nr]++;
1885 
1886 	if (vm->vlpi_count[its->list_nr] == 1) {
1887 		int i;
1888 
1889 		for (i = 0; i < vm->nr_vpes; i++) {
1890 			struct its_vpe *vpe = vm->vpes[i];
1891 
1892 			scoped_guard(raw_spinlock, &vpe->vpe_lock)
1893 				its_send_vmapp(its, vpe, true);
1894 
1895 			its_send_vinvall(its, vpe);
1896 		}
1897 	}
1898 }
1899 
1900 static void its_unmap_vm(struct its_node *its, struct its_vm *vm)
1901 {
1902 	/* Not using the ITS list? Everything is always mapped. */
1903 	if (gic_requires_eager_mapping())
1904 		return;
1905 
1906 	guard(raw_spinlock_irqsave)(&vm->vmapp_lock);
1907 
1908 	if (!--vm->vlpi_count[its->list_nr]) {
1909 		int i;
1910 
1911 		for (i = 0; i < vm->nr_vpes; i++) {
1912 			guard(raw_spinlock)(&vm->vpes[i]->vpe_lock);
1913 			its_send_vmapp(its, vm->vpes[i], false);
1914 		}
1915 	}
1916 }
1917 
1918 static int its_vlpi_map(struct irq_data *d, struct its_cmd_info *info)
1919 {
1920 	struct its_device *its_dev = irq_data_get_irq_chip_data(d);
1921 	u32 event = its_get_event_id(d);
1922 
1923 	if (!info->map)
1924 		return -EINVAL;
1925 
1926 	if (!its_dev->event_map.vm) {
1927 		struct its_vlpi_map *maps;
1928 
1929 		maps = kcalloc(its_dev->event_map.nr_lpis, sizeof(*maps),
1930 			       GFP_ATOMIC);
1931 		if (!maps)
1932 			return -ENOMEM;
1933 
1934 		its_dev->event_map.vm = info->map->vm;
1935 		its_dev->event_map.vlpi_maps = maps;
1936 	} else if (its_dev->event_map.vm != info->map->vm) {
1937 		return -EINVAL;
1938 	}
1939 
1940 	/* Get our private copy of the mapping information */
1941 	its_dev->event_map.vlpi_maps[event] = *info->map;
1942 
1943 	if (irqd_is_forwarded_to_vcpu(d)) {
1944 		/* Already mapped, move it around */
1945 		its_send_vmovi(its_dev, event);
1946 	} else {
1947 		/* Ensure all the VPEs are mapped on this ITS */
1948 		its_map_vm(its_dev->its, info->map->vm);
1949 
1950 		/*
1951 		 * Flag the interrupt as forwarded so that we can
1952 		 * start poking the virtual property table.
1953 		 */
1954 		irqd_set_forwarded_to_vcpu(d);
1955 
1956 		/* Write out the property to the prop table */
1957 		lpi_write_config(d, 0xff, info->map->properties);
1958 
1959 		/* Drop the physical mapping */
1960 		its_send_discard(its_dev, event);
1961 
1962 		/* and install the virtual one */
1963 		its_send_vmapti(its_dev, event);
1964 
1965 		/* Increment the number of VLPIs */
1966 		its_dev->event_map.nr_vlpis++;
1967 	}
1968 
1969 	return 0;
1970 }
1971 
1972 static int its_vlpi_get(struct irq_data *d, struct its_cmd_info *info)
1973 {
1974 	struct its_device *its_dev = irq_data_get_irq_chip_data(d);
1975 	struct its_vlpi_map *map;
1976 
1977 	map = get_vlpi_map(d);
1978 
1979 	if (!its_dev->event_map.vm || !map)
1980 		return -EINVAL;
1981 
1982 	/* Copy our mapping information to the incoming request */
1983 	*info->map = *map;
1984 
1985 	return 0;
1986 }
1987 
1988 static int its_vlpi_unmap(struct irq_data *d)
1989 {
1990 	struct its_device *its_dev = irq_data_get_irq_chip_data(d);
1991 	u32 event = its_get_event_id(d);
1992 
1993 	if (!its_dev->event_map.vm || !irqd_is_forwarded_to_vcpu(d))
1994 		return -EINVAL;
1995 
1996 	/* Drop the virtual mapping */
1997 	its_send_discard(its_dev, event);
1998 
1999 	/* and restore the physical one */
2000 	irqd_clr_forwarded_to_vcpu(d);
2001 	its_send_mapti(its_dev, d->hwirq, event);
2002 	lpi_update_config(d, 0xff, (lpi_prop_prio |
2003 				    LPI_PROP_ENABLED |
2004 				    LPI_PROP_GROUP1));
2005 
2006 	/* Potentially unmap the VM from this ITS */
2007 	its_unmap_vm(its_dev->its, its_dev->event_map.vm);
2008 
2009 	/*
2010 	 * Drop the refcount and make the device available again if
2011 	 * this was the last VLPI.
2012 	 */
2013 	if (!--its_dev->event_map.nr_vlpis) {
2014 		its_dev->event_map.vm = NULL;
2015 		kfree(its_dev->event_map.vlpi_maps);
2016 	}
2017 
2018 	return 0;
2019 }
2020 
2021 static int its_vlpi_prop_update(struct irq_data *d, struct its_cmd_info *info)
2022 {
2023 	struct its_device *its_dev = irq_data_get_irq_chip_data(d);
2024 
2025 	if (!its_dev->event_map.vm || !irqd_is_forwarded_to_vcpu(d))
2026 		return -EINVAL;
2027 
2028 	if (info->cmd_type == PROP_UPDATE_AND_INV_VLPI)
2029 		lpi_update_config(d, 0xff, info->config);
2030 	else
2031 		lpi_write_config(d, 0xff, info->config);
2032 	its_vlpi_set_doorbell(d, !!(info->config & LPI_PROP_ENABLED));
2033 
2034 	return 0;
2035 }
2036 
2037 static int its_irq_set_vcpu_affinity(struct irq_data *d, void *vcpu_info)
2038 {
2039 	struct its_device *its_dev = irq_data_get_irq_chip_data(d);
2040 	struct its_cmd_info *info = vcpu_info;
2041 
2042 	/* Need a v4 ITS */
2043 	if (!is_v4(its_dev->its))
2044 		return -EINVAL;
2045 
2046 	guard(raw_spinlock_irq)(&its_dev->event_map.vlpi_lock);
2047 
2048 	/* Unmap request? */
2049 	if (!info)
2050 		return its_vlpi_unmap(d);
2051 
2052 	switch (info->cmd_type) {
2053 	case MAP_VLPI:
2054 		return its_vlpi_map(d, info);
2055 
2056 	case GET_VLPI:
2057 		return its_vlpi_get(d, info);
2058 
2059 	case PROP_UPDATE_VLPI:
2060 	case PROP_UPDATE_AND_INV_VLPI:
2061 		return its_vlpi_prop_update(d, info);
2062 
2063 	default:
2064 		return -EINVAL;
2065 	}
2066 }
2067 
2068 static struct irq_chip its_irq_chip = {
2069 	.name			= "ITS",
2070 	.irq_mask		= its_mask_irq,
2071 	.irq_unmask		= its_unmask_irq,
2072 	.irq_eoi		= irq_chip_eoi_parent,
2073 	.irq_set_affinity	= its_set_affinity,
2074 	.irq_compose_msi_msg	= its_irq_compose_msi_msg,
2075 	.irq_set_irqchip_state	= its_irq_set_irqchip_state,
2076 	.irq_retrigger		= its_irq_retrigger,
2077 	.irq_set_vcpu_affinity	= its_irq_set_vcpu_affinity,
2078 };
2079 
2080 
2081 /*
2082  * How we allocate LPIs:
2083  *
2084  * lpi_range_list contains ranges of LPIs that are to available to
2085  * allocate from. To allocate LPIs, just pick the first range that
2086  * fits the required allocation, and reduce it by the required
2087  * amount. Once empty, remove the range from the list.
2088  *
2089  * To free a range of LPIs, add a free range to the list, sort it and
2090  * merge the result if the new range happens to be adjacent to an
2091  * already free block.
2092  *
2093  * The consequence of the above is that allocation is cost is low, but
2094  * freeing is expensive. We assumes that freeing rarely occurs.
2095  */
2096 #define ITS_MAX_LPI_NRBITS	16 /* 64K LPIs */
2097 
2098 static DEFINE_MUTEX(lpi_range_lock);
2099 static LIST_HEAD(lpi_range_list);
2100 
2101 struct lpi_range {
2102 	struct list_head	entry;
2103 	u32			base_id;
2104 	u32			span;
2105 };
2106 
2107 static struct lpi_range *mk_lpi_range(u32 base, u32 span)
2108 {
2109 	struct lpi_range *range;
2110 
2111 	range = kmalloc(sizeof(*range), GFP_KERNEL);
2112 	if (range) {
2113 		range->base_id = base;
2114 		range->span = span;
2115 	}
2116 
2117 	return range;
2118 }
2119 
2120 static int alloc_lpi_range(u32 nr_lpis, u32 *base)
2121 {
2122 	struct lpi_range *range, *tmp;
2123 	int err = -ENOSPC;
2124 
2125 	mutex_lock(&lpi_range_lock);
2126 
2127 	list_for_each_entry_safe(range, tmp, &lpi_range_list, entry) {
2128 		if (range->span >= nr_lpis) {
2129 			*base = range->base_id;
2130 			range->base_id += nr_lpis;
2131 			range->span -= nr_lpis;
2132 
2133 			if (range->span == 0) {
2134 				list_del(&range->entry);
2135 				kfree(range);
2136 			}
2137 
2138 			err = 0;
2139 			break;
2140 		}
2141 	}
2142 
2143 	mutex_unlock(&lpi_range_lock);
2144 
2145 	pr_debug("ITS: alloc %u:%u\n", *base, nr_lpis);
2146 	return err;
2147 }
2148 
2149 static void merge_lpi_ranges(struct lpi_range *a, struct lpi_range *b)
2150 {
2151 	if (&a->entry == &lpi_range_list || &b->entry == &lpi_range_list)
2152 		return;
2153 	if (a->base_id + a->span != b->base_id)
2154 		return;
2155 	b->base_id = a->base_id;
2156 	b->span += a->span;
2157 	list_del(&a->entry);
2158 	kfree(a);
2159 }
2160 
2161 static int free_lpi_range(u32 base, u32 nr_lpis)
2162 {
2163 	struct lpi_range *new, *old;
2164 
2165 	new = mk_lpi_range(base, nr_lpis);
2166 	if (!new)
2167 		return -ENOMEM;
2168 
2169 	mutex_lock(&lpi_range_lock);
2170 
2171 	list_for_each_entry_reverse(old, &lpi_range_list, entry) {
2172 		if (old->base_id < base)
2173 			break;
2174 	}
2175 	/*
2176 	 * old is the last element with ->base_id smaller than base,
2177 	 * so new goes right after it. If there are no elements with
2178 	 * ->base_id smaller than base, &old->entry ends up pointing
2179 	 * at the head of the list, and inserting new it the start of
2180 	 * the list is the right thing to do in that case as well.
2181 	 */
2182 	list_add(&new->entry, &old->entry);
2183 	/*
2184 	 * Now check if we can merge with the preceding and/or
2185 	 * following ranges.
2186 	 */
2187 	merge_lpi_ranges(old, new);
2188 	merge_lpi_ranges(new, list_next_entry(new, entry));
2189 
2190 	mutex_unlock(&lpi_range_lock);
2191 	return 0;
2192 }
2193 
2194 static int __init its_lpi_init(u32 id_bits)
2195 {
2196 	u32 lpis = (1UL << id_bits) - 8192;
2197 	u32 numlpis;
2198 	int err;
2199 
2200 	numlpis = 1UL << GICD_TYPER_NUM_LPIS(gic_rdists->gicd_typer);
2201 
2202 	if (numlpis > 2 && !WARN_ON(numlpis > lpis)) {
2203 		lpis = numlpis;
2204 		pr_info("ITS: Using hypervisor restricted LPI range [%u]\n",
2205 			lpis);
2206 	}
2207 
2208 	/*
2209 	 * Initializing the allocator is just the same as freeing the
2210 	 * full range of LPIs.
2211 	 */
2212 	err = free_lpi_range(8192, lpis);
2213 	pr_debug("ITS: Allocator initialized for %u LPIs\n", lpis);
2214 	return err;
2215 }
2216 
2217 static unsigned long *its_lpi_alloc(int nr_irqs, u32 *base, int *nr_ids)
2218 {
2219 	unsigned long *bitmap = NULL;
2220 	int err = 0;
2221 
2222 	do {
2223 		err = alloc_lpi_range(nr_irqs, base);
2224 		if (!err)
2225 			break;
2226 
2227 		nr_irqs /= 2;
2228 	} while (nr_irqs > 0);
2229 
2230 	if (!nr_irqs)
2231 		err = -ENOSPC;
2232 
2233 	if (err)
2234 		goto out;
2235 
2236 	bitmap = bitmap_zalloc(nr_irqs, GFP_ATOMIC);
2237 	if (!bitmap)
2238 		goto out;
2239 
2240 	*nr_ids = nr_irqs;
2241 
2242 out:
2243 	if (!bitmap)
2244 		*base = *nr_ids = 0;
2245 
2246 	return bitmap;
2247 }
2248 
2249 static void its_lpi_free(unsigned long *bitmap, u32 base, u32 nr_ids)
2250 {
2251 	WARN_ON(free_lpi_range(base, nr_ids));
2252 	bitmap_free(bitmap);
2253 }
2254 
2255 static void gic_reset_prop_table(void *va)
2256 {
2257 	/* Regular IRQ priority, Group-1, disabled */
2258 	memset(va, lpi_prop_prio | LPI_PROP_GROUP1, LPI_PROPBASE_SZ);
2259 
2260 	/* Make sure the GIC will observe the written configuration */
2261 	gic_flush_dcache_to_poc(va, LPI_PROPBASE_SZ);
2262 }
2263 
2264 static struct page *its_allocate_prop_table(gfp_t gfp_flags)
2265 {
2266 	struct page *prop_page;
2267 
2268 	prop_page = its_alloc_pages(gfp_flags,
2269 				    get_order(LPI_PROPBASE_SZ));
2270 	if (!prop_page)
2271 		return NULL;
2272 
2273 	gic_reset_prop_table(page_address(prop_page));
2274 
2275 	return prop_page;
2276 }
2277 
2278 static void its_free_prop_table(struct page *prop_page)
2279 {
2280 	its_free_pages(page_address(prop_page), get_order(LPI_PROPBASE_SZ));
2281 }
2282 
2283 static bool gic_check_reserved_range(phys_addr_t addr, unsigned long size)
2284 {
2285 	phys_addr_t start, end, addr_end;
2286 	u64 i;
2287 
2288 	/*
2289 	 * We don't bother checking for a kdump kernel as by
2290 	 * construction, the LPI tables are out of this kernel's
2291 	 * memory map.
2292 	 */
2293 	if (is_kdump_kernel())
2294 		return true;
2295 
2296 	addr_end = addr + size - 1;
2297 
2298 	for_each_reserved_mem_range(i, &start, &end) {
2299 		if (addr >= start && addr_end <= end)
2300 			return true;
2301 	}
2302 
2303 	/* Not found, not a good sign... */
2304 	pr_warn("GICv3: Expected reserved range [%pa:%pa], not found\n",
2305 		&addr, &addr_end);
2306 	add_taint(TAINT_CRAP, LOCKDEP_STILL_OK);
2307 	return false;
2308 }
2309 
2310 static int gic_reserve_range(phys_addr_t addr, unsigned long size)
2311 {
2312 	if (efi_enabled(EFI_CONFIG_TABLES))
2313 		return efi_mem_reserve_persistent(addr, size);
2314 
2315 	return 0;
2316 }
2317 
2318 static int __init its_setup_lpi_prop_table(void)
2319 {
2320 	if (gic_rdists->flags & RDIST_FLAGS_RD_TABLES_PREALLOCATED) {
2321 		u64 val;
2322 
2323 		val = gicr_read_propbaser(gic_data_rdist_rd_base() + GICR_PROPBASER);
2324 		lpi_id_bits = (val & GICR_PROPBASER_IDBITS_MASK) + 1;
2325 
2326 		gic_rdists->prop_table_pa = val & GENMASK_ULL(51, 12);
2327 		gic_rdists->prop_table_va = memremap(gic_rdists->prop_table_pa,
2328 						     LPI_PROPBASE_SZ,
2329 						     MEMREMAP_WB);
2330 		gic_reset_prop_table(gic_rdists->prop_table_va);
2331 	} else {
2332 		struct page *page;
2333 
2334 		lpi_id_bits = min_t(u32,
2335 				    GICD_TYPER_ID_BITS(gic_rdists->gicd_typer),
2336 				    ITS_MAX_LPI_NRBITS);
2337 		page = its_allocate_prop_table(GFP_NOWAIT);
2338 		if (!page) {
2339 			pr_err("Failed to allocate PROPBASE\n");
2340 			return -ENOMEM;
2341 		}
2342 
2343 		gic_rdists->prop_table_pa = page_to_phys(page);
2344 		gic_rdists->prop_table_va = page_address(page);
2345 		WARN_ON(gic_reserve_range(gic_rdists->prop_table_pa,
2346 					  LPI_PROPBASE_SZ));
2347 	}
2348 
2349 	pr_info("GICv3: using LPI property table @%pa\n",
2350 		&gic_rdists->prop_table_pa);
2351 
2352 	return its_lpi_init(lpi_id_bits);
2353 }
2354 
2355 static const char *its_base_type_string[] = {
2356 	[GITS_BASER_TYPE_DEVICE]	= "Devices",
2357 	[GITS_BASER_TYPE_VCPU]		= "Virtual CPUs",
2358 	[GITS_BASER_TYPE_RESERVED3]	= "Reserved (3)",
2359 	[GITS_BASER_TYPE_COLLECTION]	= "Interrupt Collections",
2360 	[GITS_BASER_TYPE_RESERVED5] 	= "Reserved (5)",
2361 	[GITS_BASER_TYPE_RESERVED6] 	= "Reserved (6)",
2362 	[GITS_BASER_TYPE_RESERVED7] 	= "Reserved (7)",
2363 };
2364 
2365 static u64 its_read_baser(struct its_node *its, struct its_baser *baser)
2366 {
2367 	u32 idx = baser - its->tables;
2368 
2369 	return gits_read_baser(its->base + GITS_BASER + (idx << 3));
2370 }
2371 
2372 static void its_write_baser(struct its_node *its, struct its_baser *baser,
2373 			    u64 val)
2374 {
2375 	u32 idx = baser - its->tables;
2376 
2377 	gits_write_baser(val, its->base + GITS_BASER + (idx << 3));
2378 	baser->val = its_read_baser(its, baser);
2379 }
2380 
2381 static int its_setup_baser(struct its_node *its, struct its_baser *baser,
2382 			   u64 cache, u64 shr, u32 order, bool indirect)
2383 {
2384 	u64 val = its_read_baser(its, baser);
2385 	u64 esz = GITS_BASER_ENTRY_SIZE(val);
2386 	u64 type = GITS_BASER_TYPE(val);
2387 	u64 baser_phys, tmp;
2388 	u32 alloc_pages, psz;
2389 	struct page *page;
2390 	void *base;
2391 
2392 	psz = baser->psz;
2393 	alloc_pages = (PAGE_ORDER_TO_SIZE(order) / psz);
2394 	if (alloc_pages > GITS_BASER_PAGES_MAX) {
2395 		pr_warn("ITS@%pa: %s too large, reduce ITS pages %u->%u\n",
2396 			&its->phys_base, its_base_type_string[type],
2397 			alloc_pages, GITS_BASER_PAGES_MAX);
2398 		alloc_pages = GITS_BASER_PAGES_MAX;
2399 		order = get_order(GITS_BASER_PAGES_MAX * psz);
2400 	}
2401 
2402 	page = its_alloc_pages_node(its->numa_node, GFP_KERNEL | __GFP_ZERO, order);
2403 	if (!page)
2404 		return -ENOMEM;
2405 
2406 	base = (void *)page_address(page);
2407 	baser_phys = virt_to_phys(base);
2408 
2409 	/* Check if the physical address of the memory is above 48bits */
2410 	if (IS_ENABLED(CONFIG_ARM64_64K_PAGES) && (baser_phys >> 48)) {
2411 
2412 		/* 52bit PA is supported only when PageSize=64K */
2413 		if (psz != SZ_64K) {
2414 			pr_err("ITS: no 52bit PA support when psz=%d\n", psz);
2415 			its_free_pages(base, order);
2416 			return -ENXIO;
2417 		}
2418 
2419 		/* Convert 52bit PA to 48bit field */
2420 		baser_phys = GITS_BASER_PHYS_52_to_48(baser_phys);
2421 	}
2422 
2423 retry_baser:
2424 	val = (baser_phys					 |
2425 		(type << GITS_BASER_TYPE_SHIFT)			 |
2426 		((esz - 1) << GITS_BASER_ENTRY_SIZE_SHIFT)	 |
2427 		((alloc_pages - 1) << GITS_BASER_PAGES_SHIFT)	 |
2428 		cache						 |
2429 		shr						 |
2430 		GITS_BASER_VALID);
2431 
2432 	val |=	indirect ? GITS_BASER_INDIRECT : 0x0;
2433 
2434 	switch (psz) {
2435 	case SZ_4K:
2436 		val |= GITS_BASER_PAGE_SIZE_4K;
2437 		break;
2438 	case SZ_16K:
2439 		val |= GITS_BASER_PAGE_SIZE_16K;
2440 		break;
2441 	case SZ_64K:
2442 		val |= GITS_BASER_PAGE_SIZE_64K;
2443 		break;
2444 	}
2445 
2446 	if (!shr)
2447 		gic_flush_dcache_to_poc(base, PAGE_ORDER_TO_SIZE(order));
2448 
2449 	its_write_baser(its, baser, val);
2450 	tmp = baser->val;
2451 
2452 	if ((val ^ tmp) & GITS_BASER_SHAREABILITY_MASK) {
2453 		/*
2454 		 * Shareability didn't stick. Just use
2455 		 * whatever the read reported, which is likely
2456 		 * to be the only thing this redistributor
2457 		 * supports. If that's zero, make it
2458 		 * non-cacheable as well.
2459 		 */
2460 		shr = tmp & GITS_BASER_SHAREABILITY_MASK;
2461 		if (!shr)
2462 			cache = GITS_BASER_nC;
2463 
2464 		goto retry_baser;
2465 	}
2466 
2467 	if (val != tmp) {
2468 		pr_err("ITS@%pa: %s doesn't stick: %llx %llx\n",
2469 		       &its->phys_base, its_base_type_string[type],
2470 		       val, tmp);
2471 		its_free_pages(base, order);
2472 		return -ENXIO;
2473 	}
2474 
2475 	baser->order = order;
2476 	baser->base = base;
2477 	baser->psz = psz;
2478 	tmp = indirect ? GITS_LVL1_ENTRY_SIZE : esz;
2479 
2480 	pr_info("ITS@%pa: allocated %d %s @%lx (%s, esz %d, psz %dK, shr %d)\n",
2481 		&its->phys_base, (int)(PAGE_ORDER_TO_SIZE(order) / (int)tmp),
2482 		its_base_type_string[type],
2483 		(unsigned long)virt_to_phys(base),
2484 		indirect ? "indirect" : "flat", (int)esz,
2485 		psz / SZ_1K, (int)shr >> GITS_BASER_SHAREABILITY_SHIFT);
2486 
2487 	return 0;
2488 }
2489 
2490 static bool its_parse_indirect_baser(struct its_node *its,
2491 				     struct its_baser *baser,
2492 				     u32 *order, u32 ids)
2493 {
2494 	u64 tmp = its_read_baser(its, baser);
2495 	u64 type = GITS_BASER_TYPE(tmp);
2496 	u64 esz = GITS_BASER_ENTRY_SIZE(tmp);
2497 	u64 val = GITS_BASER_InnerShareable | GITS_BASER_RaWaWb;
2498 	u32 new_order = *order;
2499 	u32 psz = baser->psz;
2500 	bool indirect = false;
2501 
2502 	/* No need to enable Indirection if memory requirement < (psz*2)bytes */
2503 	if ((esz << ids) > (psz * 2)) {
2504 		/*
2505 		 * Find out whether hw supports a single or two-level table by
2506 		 * table by reading bit at offset '62' after writing '1' to it.
2507 		 */
2508 		its_write_baser(its, baser, val | GITS_BASER_INDIRECT);
2509 		indirect = !!(baser->val & GITS_BASER_INDIRECT);
2510 
2511 		if (indirect) {
2512 			/*
2513 			 * The size of the lvl2 table is equal to ITS page size
2514 			 * which is 'psz'. For computing lvl1 table size,
2515 			 * subtract ID bits that sparse lvl2 table from 'ids'
2516 			 * which is reported by ITS hardware times lvl1 table
2517 			 * entry size.
2518 			 */
2519 			ids -= ilog2(psz / (int)esz);
2520 			esz = GITS_LVL1_ENTRY_SIZE;
2521 		}
2522 	}
2523 
2524 	/*
2525 	 * Allocate as many entries as required to fit the
2526 	 * range of device IDs that the ITS can grok... The ID
2527 	 * space being incredibly sparse, this results in a
2528 	 * massive waste of memory if two-level device table
2529 	 * feature is not supported by hardware.
2530 	 */
2531 	new_order = max_t(u32, get_order(esz << ids), new_order);
2532 	if (new_order > MAX_PAGE_ORDER) {
2533 		new_order = MAX_PAGE_ORDER;
2534 		ids = ilog2(PAGE_ORDER_TO_SIZE(new_order) / (int)esz);
2535 		pr_warn("ITS@%pa: %s Table too large, reduce ids %llu->%u\n",
2536 			&its->phys_base, its_base_type_string[type],
2537 			device_ids(its), ids);
2538 	}
2539 
2540 	*order = new_order;
2541 
2542 	return indirect;
2543 }
2544 
2545 static u32 compute_common_aff(u64 val)
2546 {
2547 	u32 aff, clpiaff;
2548 
2549 	aff = FIELD_GET(GICR_TYPER_AFFINITY, val);
2550 	clpiaff = FIELD_GET(GICR_TYPER_COMMON_LPI_AFF, val);
2551 
2552 	return aff & ~(GENMASK(31, 0) >> (clpiaff * 8));
2553 }
2554 
2555 static u32 compute_its_aff(struct its_node *its)
2556 {
2557 	u64 val;
2558 	u32 svpet;
2559 
2560 	/*
2561 	 * Reencode the ITS SVPET and MPIDR as a GICR_TYPER, and compute
2562 	 * the resulting affinity. We then use that to see if this match
2563 	 * our own affinity.
2564 	 */
2565 	svpet = FIELD_GET(GITS_TYPER_SVPET, its->typer);
2566 	val  = FIELD_PREP(GICR_TYPER_COMMON_LPI_AFF, svpet);
2567 	val |= FIELD_PREP(GICR_TYPER_AFFINITY, its->mpidr);
2568 	return compute_common_aff(val);
2569 }
2570 
2571 static struct its_node *find_sibling_its(struct its_node *cur_its)
2572 {
2573 	struct its_node *its;
2574 	u32 aff;
2575 
2576 	if (!FIELD_GET(GITS_TYPER_SVPET, cur_its->typer))
2577 		return NULL;
2578 
2579 	aff = compute_its_aff(cur_its);
2580 
2581 	list_for_each_entry(its, &its_nodes, entry) {
2582 		u64 baser;
2583 
2584 		if (!is_v4_1(its) || its == cur_its)
2585 			continue;
2586 
2587 		if (!FIELD_GET(GITS_TYPER_SVPET, its->typer))
2588 			continue;
2589 
2590 		if (aff != compute_its_aff(its))
2591 			continue;
2592 
2593 		/* GICv4.1 guarantees that the vPE table is GITS_BASER2 */
2594 		baser = its->tables[2].val;
2595 		if (!(baser & GITS_BASER_VALID))
2596 			continue;
2597 
2598 		return its;
2599 	}
2600 
2601 	return NULL;
2602 }
2603 
2604 static void its_free_tables(struct its_node *its)
2605 {
2606 	int i;
2607 
2608 	for (i = 0; i < GITS_BASER_NR_REGS; i++) {
2609 		if (its->tables[i].base) {
2610 			its_free_pages(its->tables[i].base, its->tables[i].order);
2611 			its->tables[i].base = NULL;
2612 		}
2613 	}
2614 }
2615 
2616 static int its_probe_baser_psz(struct its_node *its, struct its_baser *baser)
2617 {
2618 	u64 psz = SZ_64K;
2619 
2620 	while (psz) {
2621 		u64 val, gpsz;
2622 
2623 		val = its_read_baser(its, baser);
2624 		val &= ~GITS_BASER_PAGE_SIZE_MASK;
2625 
2626 		switch (psz) {
2627 		case SZ_64K:
2628 			gpsz = GITS_BASER_PAGE_SIZE_64K;
2629 			break;
2630 		case SZ_16K:
2631 			gpsz = GITS_BASER_PAGE_SIZE_16K;
2632 			break;
2633 		case SZ_4K:
2634 		default:
2635 			gpsz = GITS_BASER_PAGE_SIZE_4K;
2636 			break;
2637 		}
2638 
2639 		gpsz >>= GITS_BASER_PAGE_SIZE_SHIFT;
2640 
2641 		val |= FIELD_PREP(GITS_BASER_PAGE_SIZE_MASK, gpsz);
2642 		its_write_baser(its, baser, val);
2643 
2644 		if (FIELD_GET(GITS_BASER_PAGE_SIZE_MASK, baser->val) == gpsz)
2645 			break;
2646 
2647 		switch (psz) {
2648 		case SZ_64K:
2649 			psz = SZ_16K;
2650 			break;
2651 		case SZ_16K:
2652 			psz = SZ_4K;
2653 			break;
2654 		case SZ_4K:
2655 		default:
2656 			return -1;
2657 		}
2658 	}
2659 
2660 	baser->psz = psz;
2661 	return 0;
2662 }
2663 
2664 static int its_alloc_tables(struct its_node *its)
2665 {
2666 	u64 shr = GITS_BASER_InnerShareable;
2667 	u64 cache = GITS_BASER_RaWaWb;
2668 	int err, i;
2669 
2670 	if (its->flags & ITS_FLAGS_WORKAROUND_CAVIUM_22375)
2671 		/* erratum 24313: ignore memory access type */
2672 		cache = GITS_BASER_nCnB;
2673 
2674 	if (its->flags & ITS_FLAGS_FORCE_NON_SHAREABLE) {
2675 		cache = GITS_BASER_nC;
2676 		shr = 0;
2677 	}
2678 
2679 	for (i = 0; i < GITS_BASER_NR_REGS; i++) {
2680 		struct its_baser *baser = its->tables + i;
2681 		u64 val = its_read_baser(its, baser);
2682 		u64 type = GITS_BASER_TYPE(val);
2683 		bool indirect = false;
2684 		u32 order;
2685 
2686 		if (type == GITS_BASER_TYPE_NONE)
2687 			continue;
2688 
2689 		if (its_probe_baser_psz(its, baser)) {
2690 			its_free_tables(its);
2691 			return -ENXIO;
2692 		}
2693 
2694 		order = get_order(baser->psz);
2695 
2696 		switch (type) {
2697 		case GITS_BASER_TYPE_DEVICE:
2698 			indirect = its_parse_indirect_baser(its, baser, &order,
2699 							    device_ids(its));
2700 			break;
2701 
2702 		case GITS_BASER_TYPE_VCPU:
2703 			if (is_v4_1(its)) {
2704 				struct its_node *sibling;
2705 
2706 				WARN_ON(i != 2);
2707 				if ((sibling = find_sibling_its(its))) {
2708 					*baser = sibling->tables[2];
2709 					its_write_baser(its, baser, baser->val);
2710 					continue;
2711 				}
2712 			}
2713 
2714 			indirect = its_parse_indirect_baser(its, baser, &order,
2715 							    ITS_MAX_VPEID_BITS);
2716 			break;
2717 		}
2718 
2719 		err = its_setup_baser(its, baser, cache, shr, order, indirect);
2720 		if (err < 0) {
2721 			its_free_tables(its);
2722 			return err;
2723 		}
2724 
2725 		/* Update settings which will be used for next BASERn */
2726 		cache = baser->val & GITS_BASER_CACHEABILITY_MASK;
2727 		shr = baser->val & GITS_BASER_SHAREABILITY_MASK;
2728 	}
2729 
2730 	return 0;
2731 }
2732 
2733 static u64 inherit_vpe_l1_table_from_its(void)
2734 {
2735 	struct its_node *its;
2736 	u64 val;
2737 	u32 aff;
2738 
2739 	val = gic_read_typer(gic_data_rdist_rd_base() + GICR_TYPER);
2740 	aff = compute_common_aff(val);
2741 
2742 	list_for_each_entry(its, &its_nodes, entry) {
2743 		u64 baser, addr;
2744 
2745 		if (!is_v4_1(its))
2746 			continue;
2747 
2748 		if (!FIELD_GET(GITS_TYPER_SVPET, its->typer))
2749 			continue;
2750 
2751 		if (aff != compute_its_aff(its))
2752 			continue;
2753 
2754 		/* GICv4.1 guarantees that the vPE table is GITS_BASER2 */
2755 		baser = its->tables[2].val;
2756 		if (!(baser & GITS_BASER_VALID))
2757 			continue;
2758 
2759 		/* We have a winner! */
2760 		gic_data_rdist()->vpe_l1_base = its->tables[2].base;
2761 
2762 		val  = GICR_VPROPBASER_4_1_VALID;
2763 		if (baser & GITS_BASER_INDIRECT)
2764 			val |= GICR_VPROPBASER_4_1_INDIRECT;
2765 		val |= FIELD_PREP(GICR_VPROPBASER_4_1_PAGE_SIZE,
2766 				  FIELD_GET(GITS_BASER_PAGE_SIZE_MASK, baser));
2767 		switch (FIELD_GET(GITS_BASER_PAGE_SIZE_MASK, baser)) {
2768 		case GIC_PAGE_SIZE_64K:
2769 			addr = GITS_BASER_ADDR_48_to_52(baser);
2770 			break;
2771 		default:
2772 			addr = baser & GENMASK_ULL(47, 12);
2773 			break;
2774 		}
2775 		val |= FIELD_PREP(GICR_VPROPBASER_4_1_ADDR, addr >> 12);
2776 		if (rdists_support_shareable()) {
2777 			val |= FIELD_PREP(GICR_VPROPBASER_SHAREABILITY_MASK,
2778 					  FIELD_GET(GITS_BASER_SHAREABILITY_MASK, baser));
2779 			val |= FIELD_PREP(GICR_VPROPBASER_INNER_CACHEABILITY_MASK,
2780 					  FIELD_GET(GITS_BASER_INNER_CACHEABILITY_MASK, baser));
2781 		}
2782 		val |= FIELD_PREP(GICR_VPROPBASER_4_1_SIZE, GITS_BASER_NR_PAGES(baser) - 1);
2783 
2784 		return val;
2785 	}
2786 
2787 	return 0;
2788 }
2789 
2790 static u64 inherit_vpe_l1_table_from_rd(cpumask_t **mask)
2791 {
2792 	u32 aff;
2793 	u64 val;
2794 	int cpu;
2795 
2796 	val = gic_read_typer(gic_data_rdist_rd_base() + GICR_TYPER);
2797 	aff = compute_common_aff(val);
2798 
2799 	for_each_possible_cpu(cpu) {
2800 		void __iomem *base = gic_data_rdist_cpu(cpu)->rd_base;
2801 
2802 		if (!base || cpu == smp_processor_id())
2803 			continue;
2804 
2805 		val = gic_read_typer(base + GICR_TYPER);
2806 		if (aff != compute_common_aff(val))
2807 			continue;
2808 
2809 		/*
2810 		 * At this point, we have a victim. This particular CPU
2811 		 * has already booted, and has an affinity that matches
2812 		 * ours wrt CommonLPIAff. Let's use its own VPROPBASER.
2813 		 * Make sure we don't write the Z bit in that case.
2814 		 */
2815 		val = gicr_read_vpropbaser(base + SZ_128K + GICR_VPROPBASER);
2816 		val &= ~GICR_VPROPBASER_4_1_Z;
2817 
2818 		gic_data_rdist()->vpe_l1_base = gic_data_rdist_cpu(cpu)->vpe_l1_base;
2819 		*mask = gic_data_rdist_cpu(cpu)->vpe_table_mask;
2820 
2821 		return val;
2822 	}
2823 
2824 	return 0;
2825 }
2826 
2827 static bool allocate_vpe_l2_table(int cpu, u32 id)
2828 {
2829 	void __iomem *base = gic_data_rdist_cpu(cpu)->rd_base;
2830 	unsigned int psz, esz, idx, npg, gpsz;
2831 	u64 val;
2832 	struct page *page;
2833 	__le64 *table;
2834 
2835 	if (!gic_rdists->has_rvpeid)
2836 		return true;
2837 
2838 	/* Skip non-present CPUs */
2839 	if (!base)
2840 		return true;
2841 
2842 	val  = gicr_read_vpropbaser(base + SZ_128K + GICR_VPROPBASER);
2843 
2844 	esz  = FIELD_GET(GICR_VPROPBASER_4_1_ENTRY_SIZE, val) + 1;
2845 	gpsz = FIELD_GET(GICR_VPROPBASER_4_1_PAGE_SIZE, val);
2846 	npg  = FIELD_GET(GICR_VPROPBASER_4_1_SIZE, val) + 1;
2847 
2848 	switch (gpsz) {
2849 	default:
2850 		WARN_ON(1);
2851 		fallthrough;
2852 	case GIC_PAGE_SIZE_4K:
2853 		psz = SZ_4K;
2854 		break;
2855 	case GIC_PAGE_SIZE_16K:
2856 		psz = SZ_16K;
2857 		break;
2858 	case GIC_PAGE_SIZE_64K:
2859 		psz = SZ_64K;
2860 		break;
2861 	}
2862 
2863 	/* Don't allow vpe_id that exceeds single, flat table limit */
2864 	if (!(val & GICR_VPROPBASER_4_1_INDIRECT))
2865 		return (id < (npg * psz / (esz * SZ_8)));
2866 
2867 	/* Compute 1st level table index & check if that exceeds table limit */
2868 	idx = id >> ilog2(psz / (esz * SZ_8));
2869 	if (idx >= (npg * psz / GITS_LVL1_ENTRY_SIZE))
2870 		return false;
2871 
2872 	table = gic_data_rdist_cpu(cpu)->vpe_l1_base;
2873 
2874 	/* Allocate memory for 2nd level table */
2875 	if (!table[idx]) {
2876 		page = its_alloc_pages(GFP_KERNEL | __GFP_ZERO, get_order(psz));
2877 		if (!page)
2878 			return false;
2879 
2880 		/* Flush Lvl2 table to PoC if hw doesn't support coherency */
2881 		if (!(val & GICR_VPROPBASER_SHAREABILITY_MASK))
2882 			gic_flush_dcache_to_poc(page_address(page), psz);
2883 
2884 		table[idx] = cpu_to_le64(page_to_phys(page) | GITS_BASER_VALID);
2885 
2886 		/* Flush Lvl1 entry to PoC if hw doesn't support coherency */
2887 		if (!(val & GICR_VPROPBASER_SHAREABILITY_MASK))
2888 			gic_flush_dcache_to_poc(table + idx, GITS_LVL1_ENTRY_SIZE);
2889 
2890 		/* Ensure updated table contents are visible to RD hardware */
2891 		dsb(sy);
2892 	}
2893 
2894 	return true;
2895 }
2896 
2897 static int allocate_vpe_l1_table(void)
2898 {
2899 	void __iomem *vlpi_base = gic_data_rdist_vlpi_base();
2900 	u64 val, gpsz, npg, pa;
2901 	unsigned int psz = SZ_64K;
2902 	unsigned int np, epp, esz;
2903 	struct page *page;
2904 
2905 	if (!gic_rdists->has_rvpeid)
2906 		return 0;
2907 
2908 	/*
2909 	 * if VPENDBASER.Valid is set, disable any previously programmed
2910 	 * VPE by setting PendingLast while clearing Valid. This has the
2911 	 * effect of making sure no doorbell will be generated and we can
2912 	 * then safely clear VPROPBASER.Valid.
2913 	 */
2914 	if (gicr_read_vpendbaser(vlpi_base + GICR_VPENDBASER) & GICR_VPENDBASER_Valid)
2915 		gicr_write_vpendbaser(GICR_VPENDBASER_PendingLast,
2916 				      vlpi_base + GICR_VPENDBASER);
2917 
2918 	/*
2919 	 * If we can inherit the configuration from another RD, let's do
2920 	 * so. Otherwise, we have to go through the allocation process. We
2921 	 * assume that all RDs have the exact same requirements, as
2922 	 * nothing will work otherwise.
2923 	 */
2924 	val = inherit_vpe_l1_table_from_rd(&gic_data_rdist()->vpe_table_mask);
2925 	if (val & GICR_VPROPBASER_4_1_VALID)
2926 		goto out;
2927 
2928 	gic_data_rdist()->vpe_table_mask = kzalloc(sizeof(cpumask_t), GFP_ATOMIC);
2929 	if (!gic_data_rdist()->vpe_table_mask)
2930 		return -ENOMEM;
2931 
2932 	val = inherit_vpe_l1_table_from_its();
2933 	if (val & GICR_VPROPBASER_4_1_VALID)
2934 		goto out;
2935 
2936 	/* First probe the page size */
2937 	val = FIELD_PREP(GICR_VPROPBASER_4_1_PAGE_SIZE, GIC_PAGE_SIZE_64K);
2938 	gicr_write_vpropbaser(val, vlpi_base + GICR_VPROPBASER);
2939 	val = gicr_read_vpropbaser(vlpi_base + GICR_VPROPBASER);
2940 	gpsz = FIELD_GET(GICR_VPROPBASER_4_1_PAGE_SIZE, val);
2941 	esz = FIELD_GET(GICR_VPROPBASER_4_1_ENTRY_SIZE, val);
2942 
2943 	switch (gpsz) {
2944 	default:
2945 		gpsz = GIC_PAGE_SIZE_4K;
2946 		fallthrough;
2947 	case GIC_PAGE_SIZE_4K:
2948 		psz = SZ_4K;
2949 		break;
2950 	case GIC_PAGE_SIZE_16K:
2951 		psz = SZ_16K;
2952 		break;
2953 	case GIC_PAGE_SIZE_64K:
2954 		psz = SZ_64K;
2955 		break;
2956 	}
2957 
2958 	/*
2959 	 * Start populating the register from scratch, including RO fields
2960 	 * (which we want to print in debug cases...)
2961 	 */
2962 	val = 0;
2963 	val |= FIELD_PREP(GICR_VPROPBASER_4_1_PAGE_SIZE, gpsz);
2964 	val |= FIELD_PREP(GICR_VPROPBASER_4_1_ENTRY_SIZE, esz);
2965 
2966 	/* How many entries per GIC page? */
2967 	esz++;
2968 	epp = psz / (esz * SZ_8);
2969 
2970 	/*
2971 	 * If we need more than just a single L1 page, flag the table
2972 	 * as indirect and compute the number of required L1 pages.
2973 	 */
2974 	if (epp < ITS_MAX_VPEID) {
2975 		int nl2;
2976 
2977 		val |= GICR_VPROPBASER_4_1_INDIRECT;
2978 
2979 		/* Number of L2 pages required to cover the VPEID space */
2980 		nl2 = DIV_ROUND_UP(ITS_MAX_VPEID, epp);
2981 
2982 		/* Number of L1 pages to point to the L2 pages */
2983 		npg = DIV_ROUND_UP(nl2 * SZ_8, psz);
2984 	} else {
2985 		npg = 1;
2986 	}
2987 
2988 	val |= FIELD_PREP(GICR_VPROPBASER_4_1_SIZE, npg - 1);
2989 
2990 	/* Right, that's the number of CPU pages we need for L1 */
2991 	np = DIV_ROUND_UP(npg * psz, PAGE_SIZE);
2992 
2993 	pr_debug("np = %d, npg = %lld, psz = %d, epp = %d, esz = %d\n",
2994 		 np, npg, psz, epp, esz);
2995 	page = its_alloc_pages(GFP_ATOMIC | __GFP_ZERO, get_order(np * PAGE_SIZE));
2996 	if (!page)
2997 		return -ENOMEM;
2998 
2999 	gic_data_rdist()->vpe_l1_base = page_address(page);
3000 	pa = virt_to_phys(page_address(page));
3001 	WARN_ON(!IS_ALIGNED(pa, psz));
3002 
3003 	val |= FIELD_PREP(GICR_VPROPBASER_4_1_ADDR, pa >> 12);
3004 	if (rdists_support_shareable()) {
3005 		val |= GICR_VPROPBASER_RaWb;
3006 		val |= GICR_VPROPBASER_InnerShareable;
3007 	}
3008 	val |= GICR_VPROPBASER_4_1_Z;
3009 	val |= GICR_VPROPBASER_4_1_VALID;
3010 
3011 out:
3012 	gicr_write_vpropbaser(val, vlpi_base + GICR_VPROPBASER);
3013 	cpumask_set_cpu(smp_processor_id(), gic_data_rdist()->vpe_table_mask);
3014 
3015 	pr_debug("CPU%d: VPROPBASER = %llx %*pbl\n",
3016 		 smp_processor_id(), val,
3017 		 cpumask_pr_args(gic_data_rdist()->vpe_table_mask));
3018 
3019 	return 0;
3020 }
3021 
3022 static int its_alloc_collections(struct its_node *its)
3023 {
3024 	int i;
3025 
3026 	its->collections = kcalloc(nr_cpu_ids, sizeof(*its->collections),
3027 				   GFP_KERNEL);
3028 	if (!its->collections)
3029 		return -ENOMEM;
3030 
3031 	for (i = 0; i < nr_cpu_ids; i++)
3032 		its->collections[i].target_address = ~0ULL;
3033 
3034 	return 0;
3035 }
3036 
3037 static struct page *its_allocate_pending_table(gfp_t gfp_flags)
3038 {
3039 	struct page *pend_page;
3040 
3041 	pend_page = its_alloc_pages(gfp_flags | __GFP_ZERO, get_order(LPI_PENDBASE_SZ));
3042 	if (!pend_page)
3043 		return NULL;
3044 
3045 	/* Make sure the GIC will observe the zero-ed page */
3046 	gic_flush_dcache_to_poc(page_address(pend_page), LPI_PENDBASE_SZ);
3047 
3048 	return pend_page;
3049 }
3050 
3051 static void its_free_pending_table(struct page *pt)
3052 {
3053 	its_free_pages(page_address(pt), get_order(LPI_PENDBASE_SZ));
3054 }
3055 
3056 /*
3057  * Booting with kdump and LPIs enabled is generally fine. Any other
3058  * case is wrong in the absence of firmware/EFI support.
3059  */
3060 static bool enabled_lpis_allowed(void)
3061 {
3062 	phys_addr_t addr;
3063 	u64 val;
3064 
3065 	/* Check whether the property table is in a reserved region */
3066 	val = gicr_read_propbaser(gic_data_rdist_rd_base() + GICR_PROPBASER);
3067 	addr = val & GENMASK_ULL(51, 12);
3068 
3069 	return gic_check_reserved_range(addr, LPI_PROPBASE_SZ);
3070 }
3071 
3072 static int __init allocate_lpi_tables(void)
3073 {
3074 	u64 val;
3075 	int err, cpu;
3076 
3077 	/*
3078 	 * If LPIs are enabled while we run this from the boot CPU,
3079 	 * flag the RD tables as pre-allocated if the stars do align.
3080 	 */
3081 	val = readl_relaxed(gic_data_rdist_rd_base() + GICR_CTLR);
3082 	if ((val & GICR_CTLR_ENABLE_LPIS) && enabled_lpis_allowed()) {
3083 		gic_rdists->flags |= (RDIST_FLAGS_RD_TABLES_PREALLOCATED |
3084 				      RDIST_FLAGS_PROPBASE_NEEDS_FLUSHING);
3085 		pr_info("GICv3: Using preallocated redistributor tables\n");
3086 	}
3087 
3088 	err = its_setup_lpi_prop_table();
3089 	if (err)
3090 		return err;
3091 
3092 	/*
3093 	 * We allocate all the pending tables anyway, as we may have a
3094 	 * mix of RDs that have had LPIs enabled, and some that
3095 	 * don't. We'll free the unused ones as each CPU comes online.
3096 	 */
3097 	for_each_possible_cpu(cpu) {
3098 		struct page *pend_page;
3099 
3100 		pend_page = its_allocate_pending_table(GFP_NOWAIT);
3101 		if (!pend_page) {
3102 			pr_err("Failed to allocate PENDBASE for CPU%d\n", cpu);
3103 			return -ENOMEM;
3104 		}
3105 
3106 		gic_data_rdist_cpu(cpu)->pend_page = pend_page;
3107 	}
3108 
3109 	return 0;
3110 }
3111 
3112 static u64 read_vpend_dirty_clear(void __iomem *vlpi_base)
3113 {
3114 	u32 count = 1000000;	/* 1s! */
3115 	bool clean;
3116 	u64 val;
3117 
3118 	do {
3119 		val = gicr_read_vpendbaser(vlpi_base + GICR_VPENDBASER);
3120 		clean = !(val & GICR_VPENDBASER_Dirty);
3121 		if (!clean) {
3122 			count--;
3123 			cpu_relax();
3124 			udelay(1);
3125 		}
3126 	} while (!clean && count);
3127 
3128 	if (unlikely(!clean))
3129 		pr_err_ratelimited("ITS virtual pending table not cleaning\n");
3130 
3131 	return val;
3132 }
3133 
3134 static u64 its_clear_vpend_valid(void __iomem *vlpi_base, u64 clr, u64 set)
3135 {
3136 	u64 val;
3137 
3138 	/* Make sure we wait until the RD is done with the initial scan */
3139 	val = read_vpend_dirty_clear(vlpi_base);
3140 	val &= ~GICR_VPENDBASER_Valid;
3141 	val &= ~clr;
3142 	val |= set;
3143 	gicr_write_vpendbaser(val, vlpi_base + GICR_VPENDBASER);
3144 
3145 	val = read_vpend_dirty_clear(vlpi_base);
3146 	if (unlikely(val & GICR_VPENDBASER_Dirty))
3147 		val |= GICR_VPENDBASER_PendingLast;
3148 
3149 	return val;
3150 }
3151 
3152 static void its_cpu_init_lpis(void)
3153 {
3154 	void __iomem *rbase = gic_data_rdist_rd_base();
3155 	struct page *pend_page;
3156 	phys_addr_t paddr;
3157 	u64 val, tmp;
3158 
3159 	if (gic_data_rdist()->flags & RD_LOCAL_LPI_ENABLED)
3160 		return;
3161 
3162 	val = readl_relaxed(rbase + GICR_CTLR);
3163 	if ((gic_rdists->flags & RDIST_FLAGS_RD_TABLES_PREALLOCATED) &&
3164 	    (val & GICR_CTLR_ENABLE_LPIS)) {
3165 		/*
3166 		 * Check that we get the same property table on all
3167 		 * RDs. If we don't, this is hopeless.
3168 		 */
3169 		paddr = gicr_read_propbaser(rbase + GICR_PROPBASER);
3170 		paddr &= GENMASK_ULL(51, 12);
3171 		if (WARN_ON(gic_rdists->prop_table_pa != paddr))
3172 			add_taint(TAINT_CRAP, LOCKDEP_STILL_OK);
3173 
3174 		paddr = gicr_read_pendbaser(rbase + GICR_PENDBASER);
3175 		paddr &= GENMASK_ULL(51, 16);
3176 
3177 		WARN_ON(!gic_check_reserved_range(paddr, LPI_PENDBASE_SZ));
3178 		gic_data_rdist()->flags |= RD_LOCAL_PENDTABLE_PREALLOCATED;
3179 
3180 		goto out;
3181 	}
3182 
3183 	pend_page = gic_data_rdist()->pend_page;
3184 	paddr = page_to_phys(pend_page);
3185 
3186 	/* set PROPBASE */
3187 	val = (gic_rdists->prop_table_pa |
3188 	       GICR_PROPBASER_InnerShareable |
3189 	       GICR_PROPBASER_RaWaWb |
3190 	       ((LPI_NRBITS - 1) & GICR_PROPBASER_IDBITS_MASK));
3191 
3192 	gicr_write_propbaser(val, rbase + GICR_PROPBASER);
3193 	tmp = gicr_read_propbaser(rbase + GICR_PROPBASER);
3194 
3195 	if (!rdists_support_shareable())
3196 		tmp &= ~GICR_PROPBASER_SHAREABILITY_MASK;
3197 
3198 	if ((tmp ^ val) & GICR_PROPBASER_SHAREABILITY_MASK) {
3199 		if (!(tmp & GICR_PROPBASER_SHAREABILITY_MASK)) {
3200 			/*
3201 			 * The HW reports non-shareable, we must
3202 			 * remove the cacheability attributes as
3203 			 * well.
3204 			 */
3205 			val &= ~(GICR_PROPBASER_SHAREABILITY_MASK |
3206 				 GICR_PROPBASER_CACHEABILITY_MASK);
3207 			val |= GICR_PROPBASER_nC;
3208 			gicr_write_propbaser(val, rbase + GICR_PROPBASER);
3209 		}
3210 		pr_info_once("GIC: using cache flushing for LPI property table\n");
3211 		gic_rdists->flags |= RDIST_FLAGS_PROPBASE_NEEDS_FLUSHING;
3212 	}
3213 
3214 	/* set PENDBASE */
3215 	val = (page_to_phys(pend_page) |
3216 	       GICR_PENDBASER_InnerShareable |
3217 	       GICR_PENDBASER_RaWaWb);
3218 
3219 	gicr_write_pendbaser(val, rbase + GICR_PENDBASER);
3220 	tmp = gicr_read_pendbaser(rbase + GICR_PENDBASER);
3221 
3222 	if (!rdists_support_shareable())
3223 		tmp &= ~GICR_PENDBASER_SHAREABILITY_MASK;
3224 
3225 	if (!(tmp & GICR_PENDBASER_SHAREABILITY_MASK)) {
3226 		/*
3227 		 * The HW reports non-shareable, we must remove the
3228 		 * cacheability attributes as well.
3229 		 */
3230 		val &= ~(GICR_PENDBASER_SHAREABILITY_MASK |
3231 			 GICR_PENDBASER_CACHEABILITY_MASK);
3232 		val |= GICR_PENDBASER_nC;
3233 		gicr_write_pendbaser(val, rbase + GICR_PENDBASER);
3234 	}
3235 
3236 	/* Enable LPIs */
3237 	val = readl_relaxed(rbase + GICR_CTLR);
3238 	val |= GICR_CTLR_ENABLE_LPIS;
3239 	writel_relaxed(val, rbase + GICR_CTLR);
3240 
3241 out:
3242 	if (gic_rdists->has_vlpis && !gic_rdists->has_rvpeid) {
3243 		void __iomem *vlpi_base = gic_data_rdist_vlpi_base();
3244 
3245 		/*
3246 		 * It's possible for CPU to receive VLPIs before it is
3247 		 * scheduled as a vPE, especially for the first CPU, and the
3248 		 * VLPI with INTID larger than 2^(IDbits+1) will be considered
3249 		 * as out of range and dropped by GIC.
3250 		 * So we initialize IDbits to known value to avoid VLPI drop.
3251 		 */
3252 		val = (LPI_NRBITS - 1) & GICR_VPROPBASER_IDBITS_MASK;
3253 		pr_debug("GICv4: CPU%d: Init IDbits to 0x%llx for GICR_VPROPBASER\n",
3254 			smp_processor_id(), val);
3255 		gicr_write_vpropbaser(val, vlpi_base + GICR_VPROPBASER);
3256 
3257 		/*
3258 		 * Also clear Valid bit of GICR_VPENDBASER, in case some
3259 		 * ancient programming gets left in and has possibility of
3260 		 * corrupting memory.
3261 		 */
3262 		val = its_clear_vpend_valid(vlpi_base, 0, 0);
3263 	}
3264 
3265 	if (allocate_vpe_l1_table()) {
3266 		/*
3267 		 * If the allocation has failed, we're in massive trouble.
3268 		 * Disable direct injection, and pray that no VM was
3269 		 * already running...
3270 		 */
3271 		gic_rdists->has_rvpeid = false;
3272 		gic_rdists->has_vlpis = false;
3273 	}
3274 
3275 	/* Make sure the GIC has seen the above */
3276 	dsb(sy);
3277 	gic_data_rdist()->flags |= RD_LOCAL_LPI_ENABLED;
3278 	pr_info("GICv3: CPU%d: using %s LPI pending table @%pa\n",
3279 		smp_processor_id(),
3280 		gic_data_rdist()->flags & RD_LOCAL_PENDTABLE_PREALLOCATED ?
3281 		"reserved" : "allocated",
3282 		&paddr);
3283 }
3284 
3285 static void its_cpu_init_collection(struct its_node *its)
3286 {
3287 	int cpu = smp_processor_id();
3288 	u64 target;
3289 
3290 	/* avoid cross node collections and its mapping */
3291 	if (its->flags & ITS_FLAGS_WORKAROUND_CAVIUM_23144) {
3292 		struct device_node *cpu_node;
3293 
3294 		cpu_node = of_get_cpu_node(cpu, NULL);
3295 		if (its->numa_node != NUMA_NO_NODE &&
3296 			its->numa_node != of_node_to_nid(cpu_node))
3297 			return;
3298 	}
3299 
3300 	/*
3301 	 * We now have to bind each collection to its target
3302 	 * redistributor.
3303 	 */
3304 	if (gic_read_typer(its->base + GITS_TYPER) & GITS_TYPER_PTA) {
3305 		/*
3306 		 * This ITS wants the physical address of the
3307 		 * redistributor.
3308 		 */
3309 		target = gic_data_rdist()->phys_base;
3310 	} else {
3311 		/* This ITS wants a linear CPU number. */
3312 		target = gic_read_typer(gic_data_rdist_rd_base() + GICR_TYPER);
3313 		target = GICR_TYPER_CPU_NUMBER(target) << 16;
3314 	}
3315 
3316 	/* Perform collection mapping */
3317 	its->collections[cpu].target_address = target;
3318 	its->collections[cpu].col_id = cpu;
3319 
3320 	its_send_mapc(its, &its->collections[cpu], 1);
3321 	its_send_invall(its, &its->collections[cpu]);
3322 }
3323 
3324 static void its_cpu_init_collections(void)
3325 {
3326 	struct its_node *its;
3327 
3328 	raw_spin_lock(&its_lock);
3329 
3330 	list_for_each_entry(its, &its_nodes, entry)
3331 		its_cpu_init_collection(its);
3332 
3333 	raw_spin_unlock(&its_lock);
3334 }
3335 
3336 static struct its_device *its_find_device(struct its_node *its, u32 dev_id)
3337 {
3338 	struct its_device *its_dev = NULL, *tmp;
3339 	unsigned long flags;
3340 
3341 	raw_spin_lock_irqsave(&its->lock, flags);
3342 
3343 	list_for_each_entry(tmp, &its->its_device_list, entry) {
3344 		if (tmp->device_id == dev_id) {
3345 			its_dev = tmp;
3346 			break;
3347 		}
3348 	}
3349 
3350 	raw_spin_unlock_irqrestore(&its->lock, flags);
3351 
3352 	return its_dev;
3353 }
3354 
3355 static struct its_baser *its_get_baser(struct its_node *its, u32 type)
3356 {
3357 	int i;
3358 
3359 	for (i = 0; i < GITS_BASER_NR_REGS; i++) {
3360 		if (GITS_BASER_TYPE(its->tables[i].val) == type)
3361 			return &its->tables[i];
3362 	}
3363 
3364 	return NULL;
3365 }
3366 
3367 static bool its_alloc_table_entry(struct its_node *its,
3368 				  struct its_baser *baser, u32 id)
3369 {
3370 	struct page *page;
3371 	u32 esz, idx;
3372 	__le64 *table;
3373 
3374 	/* Don't allow device id that exceeds single, flat table limit */
3375 	esz = GITS_BASER_ENTRY_SIZE(baser->val);
3376 	if (!(baser->val & GITS_BASER_INDIRECT))
3377 		return (id < (PAGE_ORDER_TO_SIZE(baser->order) / esz));
3378 
3379 	/* Compute 1st level table index & check if that exceeds table limit */
3380 	idx = id >> ilog2(baser->psz / esz);
3381 	if (idx >= (PAGE_ORDER_TO_SIZE(baser->order) / GITS_LVL1_ENTRY_SIZE))
3382 		return false;
3383 
3384 	table = baser->base;
3385 
3386 	/* Allocate memory for 2nd level table */
3387 	if (!table[idx]) {
3388 		page = its_alloc_pages_node(its->numa_node, GFP_KERNEL | __GFP_ZERO,
3389 					    get_order(baser->psz));
3390 		if (!page)
3391 			return false;
3392 
3393 		/* Flush Lvl2 table to PoC if hw doesn't support coherency */
3394 		if (!(baser->val & GITS_BASER_SHAREABILITY_MASK))
3395 			gic_flush_dcache_to_poc(page_address(page), baser->psz);
3396 
3397 		table[idx] = cpu_to_le64(page_to_phys(page) | GITS_BASER_VALID);
3398 
3399 		/* Flush Lvl1 entry to PoC if hw doesn't support coherency */
3400 		if (!(baser->val & GITS_BASER_SHAREABILITY_MASK))
3401 			gic_flush_dcache_to_poc(table + idx, GITS_LVL1_ENTRY_SIZE);
3402 
3403 		/* Ensure updated table contents are visible to ITS hardware */
3404 		dsb(sy);
3405 	}
3406 
3407 	return true;
3408 }
3409 
3410 static bool its_alloc_device_table(struct its_node *its, u32 dev_id)
3411 {
3412 	struct its_baser *baser;
3413 
3414 	baser = its_get_baser(its, GITS_BASER_TYPE_DEVICE);
3415 
3416 	/* Don't allow device id that exceeds ITS hardware limit */
3417 	if (!baser)
3418 		return (ilog2(dev_id) < device_ids(its));
3419 
3420 	return its_alloc_table_entry(its, baser, dev_id);
3421 }
3422 
3423 static bool its_alloc_vpe_table(u32 vpe_id)
3424 {
3425 	struct its_node *its;
3426 	int cpu;
3427 
3428 	/*
3429 	 * Make sure the L2 tables are allocated on *all* v4 ITSs. We
3430 	 * could try and only do it on ITSs corresponding to devices
3431 	 * that have interrupts targeted at this VPE, but the
3432 	 * complexity becomes crazy (and you have tons of memory
3433 	 * anyway, right?).
3434 	 */
3435 	list_for_each_entry(its, &its_nodes, entry) {
3436 		struct its_baser *baser;
3437 
3438 		if (!is_v4(its))
3439 			continue;
3440 
3441 		baser = its_get_baser(its, GITS_BASER_TYPE_VCPU);
3442 		if (!baser)
3443 			return false;
3444 
3445 		if (!its_alloc_table_entry(its, baser, vpe_id))
3446 			return false;
3447 	}
3448 
3449 	/* Non v4.1? No need to iterate RDs and go back early. */
3450 	if (!gic_rdists->has_rvpeid)
3451 		return true;
3452 
3453 	/*
3454 	 * Make sure the L2 tables are allocated for all copies of
3455 	 * the L1 table on *all* v4.1 RDs.
3456 	 */
3457 	for_each_possible_cpu(cpu) {
3458 		if (!allocate_vpe_l2_table(cpu, vpe_id))
3459 			return false;
3460 	}
3461 
3462 	return true;
3463 }
3464 
3465 static struct its_device *its_create_device(struct its_node *its, u32 dev_id,
3466 					    int nvecs, bool alloc_lpis)
3467 {
3468 	struct its_device *dev;
3469 	unsigned long *lpi_map = NULL;
3470 	unsigned long flags;
3471 	u16 *col_map = NULL;
3472 	void *itt;
3473 	int lpi_base;
3474 	int nr_lpis;
3475 	int nr_ites;
3476 	int sz;
3477 
3478 	if (!its_alloc_device_table(its, dev_id))
3479 		return NULL;
3480 
3481 	if (WARN_ON(!is_power_of_2(nvecs)))
3482 		nvecs = roundup_pow_of_two(nvecs);
3483 
3484 	/*
3485 	 * Even if the device wants a single LPI, the ITT must be
3486 	 * sized as a power of two (and you need at least one bit...).
3487 	 */
3488 	nr_ites = max(2, nvecs);
3489 	sz = nr_ites * (FIELD_GET(GITS_TYPER_ITT_ENTRY_SIZE, its->typer) + 1);
3490 	sz = max(sz, ITS_ITT_ALIGN);
3491 
3492 	itt = itt_alloc_pool(its->numa_node, sz);
3493 
3494 	dev = kzalloc(sizeof(*dev), GFP_KERNEL);
3495 
3496 	if (alloc_lpis) {
3497 		lpi_map = its_lpi_alloc(nvecs, &lpi_base, &nr_lpis);
3498 		if (lpi_map)
3499 			col_map = kcalloc(nr_lpis, sizeof(*col_map),
3500 					  GFP_KERNEL);
3501 	} else {
3502 		col_map = kcalloc(nr_ites, sizeof(*col_map), GFP_KERNEL);
3503 		nr_lpis = 0;
3504 		lpi_base = 0;
3505 	}
3506 
3507 	if (!dev || !itt || !col_map || (!lpi_map && alloc_lpis)) {
3508 		kfree(dev);
3509 		itt_free_pool(itt, sz);
3510 		bitmap_free(lpi_map);
3511 		kfree(col_map);
3512 		return NULL;
3513 	}
3514 
3515 	gic_flush_dcache_to_poc(itt, sz);
3516 
3517 	dev->its = its;
3518 	dev->itt = itt;
3519 	dev->itt_sz = sz;
3520 	dev->nr_ites = nr_ites;
3521 	dev->event_map.lpi_map = lpi_map;
3522 	dev->event_map.col_map = col_map;
3523 	dev->event_map.lpi_base = lpi_base;
3524 	dev->event_map.nr_lpis = nr_lpis;
3525 	raw_spin_lock_init(&dev->event_map.vlpi_lock);
3526 	dev->device_id = dev_id;
3527 	INIT_LIST_HEAD(&dev->entry);
3528 
3529 	raw_spin_lock_irqsave(&its->lock, flags);
3530 	list_add(&dev->entry, &its->its_device_list);
3531 	raw_spin_unlock_irqrestore(&its->lock, flags);
3532 
3533 	/* Map device to its ITT */
3534 	its_send_mapd(dev, 1);
3535 
3536 	return dev;
3537 }
3538 
3539 static void its_free_device(struct its_device *its_dev)
3540 {
3541 	unsigned long flags;
3542 
3543 	raw_spin_lock_irqsave(&its_dev->its->lock, flags);
3544 	list_del(&its_dev->entry);
3545 	raw_spin_unlock_irqrestore(&its_dev->its->lock, flags);
3546 	kfree(its_dev->event_map.col_map);
3547 	itt_free_pool(its_dev->itt, its_dev->itt_sz);
3548 	kfree(its_dev);
3549 }
3550 
3551 static int its_alloc_device_irq(struct its_device *dev, int nvecs, irq_hw_number_t *hwirq)
3552 {
3553 	int idx;
3554 
3555 	/* Find a free LPI region in lpi_map and allocate them. */
3556 	idx = bitmap_find_free_region(dev->event_map.lpi_map,
3557 				      dev->event_map.nr_lpis,
3558 				      get_count_order(nvecs));
3559 	if (idx < 0)
3560 		return -ENOSPC;
3561 
3562 	*hwirq = dev->event_map.lpi_base + idx;
3563 
3564 	return 0;
3565 }
3566 
3567 static int its_msi_prepare(struct irq_domain *domain, struct device *dev,
3568 			   int nvec, msi_alloc_info_t *info)
3569 {
3570 	struct its_node *its;
3571 	struct its_device *its_dev;
3572 	struct msi_domain_info *msi_info;
3573 	u32 dev_id;
3574 	int err = 0;
3575 
3576 	/*
3577 	 * We ignore "dev" entirely, and rely on the dev_id that has
3578 	 * been passed via the scratchpad. This limits this domain's
3579 	 * usefulness to upper layers that definitely know that they
3580 	 * are built on top of the ITS.
3581 	 */
3582 	dev_id = info->scratchpad[0].ul;
3583 
3584 	msi_info = msi_get_domain_info(domain);
3585 	its = msi_info->data;
3586 
3587 	if (!gic_rdists->has_direct_lpi &&
3588 	    vpe_proxy.dev &&
3589 	    vpe_proxy.dev->its == its &&
3590 	    dev_id == vpe_proxy.dev->device_id) {
3591 		/* Bad luck. Get yourself a better implementation */
3592 		WARN_ONCE(1, "DevId %x clashes with GICv4 VPE proxy device\n",
3593 			  dev_id);
3594 		return -EINVAL;
3595 	}
3596 
3597 	mutex_lock(&its->dev_alloc_lock);
3598 	its_dev = its_find_device(its, dev_id);
3599 	if (its_dev) {
3600 		/*
3601 		 * We already have seen this ID, probably through
3602 		 * another alias (PCI bridge of some sort). No need to
3603 		 * create the device.
3604 		 */
3605 		its_dev->shared = true;
3606 		pr_debug("Reusing ITT for devID %x\n", dev_id);
3607 		goto out;
3608 	}
3609 
3610 	its_dev = its_create_device(its, dev_id, nvec, true);
3611 	if (!its_dev) {
3612 		err = -ENOMEM;
3613 		goto out;
3614 	}
3615 
3616 	if (info->flags & MSI_ALLOC_FLAGS_PROXY_DEVICE)
3617 		its_dev->shared = true;
3618 
3619 	pr_debug("ITT %d entries, %d bits\n", nvec, ilog2(nvec));
3620 out:
3621 	mutex_unlock(&its->dev_alloc_lock);
3622 	info->scratchpad[0].ptr = its_dev;
3623 	return err;
3624 }
3625 
3626 static struct msi_domain_ops its_msi_domain_ops = {
3627 	.msi_prepare	= its_msi_prepare,
3628 };
3629 
3630 static int its_irq_gic_domain_alloc(struct irq_domain *domain,
3631 				    unsigned int virq,
3632 				    irq_hw_number_t hwirq)
3633 {
3634 	struct irq_fwspec fwspec;
3635 
3636 	if (irq_domain_get_of_node(domain->parent)) {
3637 		fwspec.fwnode = domain->parent->fwnode;
3638 		fwspec.param_count = 3;
3639 		fwspec.param[0] = GIC_IRQ_TYPE_LPI;
3640 		fwspec.param[1] = hwirq;
3641 		fwspec.param[2] = IRQ_TYPE_EDGE_RISING;
3642 	} else if (is_fwnode_irqchip(domain->parent->fwnode)) {
3643 		fwspec.fwnode = domain->parent->fwnode;
3644 		fwspec.param_count = 2;
3645 		fwspec.param[0] = hwirq;
3646 		fwspec.param[1] = IRQ_TYPE_EDGE_RISING;
3647 	} else {
3648 		return -EINVAL;
3649 	}
3650 
3651 	return irq_domain_alloc_irqs_parent(domain, virq, 1, &fwspec);
3652 }
3653 
3654 static int its_irq_domain_alloc(struct irq_domain *domain, unsigned int virq,
3655 				unsigned int nr_irqs, void *args)
3656 {
3657 	msi_alloc_info_t *info = args;
3658 	struct its_device *its_dev = info->scratchpad[0].ptr;
3659 	struct its_node *its = its_dev->its;
3660 	struct irq_data *irqd;
3661 	irq_hw_number_t hwirq;
3662 	int err;
3663 	int i;
3664 
3665 	err = its_alloc_device_irq(its_dev, nr_irqs, &hwirq);
3666 	if (err)
3667 		return err;
3668 
3669 	err = iommu_dma_prepare_msi(info->desc, its->get_msi_base(its_dev));
3670 	if (err)
3671 		return err;
3672 
3673 	for (i = 0; i < nr_irqs; i++) {
3674 		err = its_irq_gic_domain_alloc(domain, virq + i, hwirq + i);
3675 		if (err)
3676 			return err;
3677 
3678 		irq_domain_set_hwirq_and_chip(domain, virq + i,
3679 					      hwirq + i, &its_irq_chip, its_dev);
3680 		irqd = irq_get_irq_data(virq + i);
3681 		irqd_set_single_target(irqd);
3682 		irqd_set_affinity_on_activate(irqd);
3683 		irqd_set_resend_when_in_progress(irqd);
3684 		pr_debug("ID:%d pID:%d vID:%d\n",
3685 			 (int)(hwirq + i - its_dev->event_map.lpi_base),
3686 			 (int)(hwirq + i), virq + i);
3687 	}
3688 
3689 	return 0;
3690 }
3691 
3692 static int its_irq_domain_activate(struct irq_domain *domain,
3693 				   struct irq_data *d, bool reserve)
3694 {
3695 	struct its_device *its_dev = irq_data_get_irq_chip_data(d);
3696 	u32 event = its_get_event_id(d);
3697 	int cpu;
3698 
3699 	cpu = its_select_cpu(d, cpu_online_mask);
3700 	if (cpu < 0 || cpu >= nr_cpu_ids)
3701 		return -EINVAL;
3702 
3703 	its_inc_lpi_count(d, cpu);
3704 	its_dev->event_map.col_map[event] = cpu;
3705 	irq_data_update_effective_affinity(d, cpumask_of(cpu));
3706 
3707 	/* Map the GIC IRQ and event to the device */
3708 	its_send_mapti(its_dev, d->hwirq, event);
3709 	return 0;
3710 }
3711 
3712 static void its_irq_domain_deactivate(struct irq_domain *domain,
3713 				      struct irq_data *d)
3714 {
3715 	struct its_device *its_dev = irq_data_get_irq_chip_data(d);
3716 	u32 event = its_get_event_id(d);
3717 
3718 	its_dec_lpi_count(d, its_dev->event_map.col_map[event]);
3719 	/* Stop the delivery of interrupts */
3720 	its_send_discard(its_dev, event);
3721 }
3722 
3723 static void its_irq_domain_free(struct irq_domain *domain, unsigned int virq,
3724 				unsigned int nr_irqs)
3725 {
3726 	struct irq_data *d = irq_domain_get_irq_data(domain, virq);
3727 	struct its_device *its_dev = irq_data_get_irq_chip_data(d);
3728 	struct its_node *its = its_dev->its;
3729 	int i;
3730 
3731 	bitmap_release_region(its_dev->event_map.lpi_map,
3732 			      its_get_event_id(irq_domain_get_irq_data(domain, virq)),
3733 			      get_count_order(nr_irqs));
3734 
3735 	for (i = 0; i < nr_irqs; i++) {
3736 		struct irq_data *data = irq_domain_get_irq_data(domain,
3737 								virq + i);
3738 		/* Nuke the entry in the domain */
3739 		irq_domain_reset_irq_data(data);
3740 	}
3741 
3742 	mutex_lock(&its->dev_alloc_lock);
3743 
3744 	/*
3745 	 * If all interrupts have been freed, start mopping the
3746 	 * floor. This is conditioned on the device not being shared.
3747 	 */
3748 	if (!its_dev->shared &&
3749 	    bitmap_empty(its_dev->event_map.lpi_map,
3750 			 its_dev->event_map.nr_lpis)) {
3751 		its_lpi_free(its_dev->event_map.lpi_map,
3752 			     its_dev->event_map.lpi_base,
3753 			     its_dev->event_map.nr_lpis);
3754 
3755 		/* Unmap device/itt */
3756 		its_send_mapd(its_dev, 0);
3757 		its_free_device(its_dev);
3758 	}
3759 
3760 	mutex_unlock(&its->dev_alloc_lock);
3761 
3762 	irq_domain_free_irqs_parent(domain, virq, nr_irqs);
3763 }
3764 
3765 static const struct irq_domain_ops its_domain_ops = {
3766 	.select			= msi_lib_irq_domain_select,
3767 	.alloc			= its_irq_domain_alloc,
3768 	.free			= its_irq_domain_free,
3769 	.activate		= its_irq_domain_activate,
3770 	.deactivate		= its_irq_domain_deactivate,
3771 };
3772 
3773 /*
3774  * This is insane.
3775  *
3776  * If a GICv4.0 doesn't implement Direct LPIs (which is extremely
3777  * likely), the only way to perform an invalidate is to use a fake
3778  * device to issue an INV command, implying that the LPI has first
3779  * been mapped to some event on that device. Since this is not exactly
3780  * cheap, we try to keep that mapping around as long as possible, and
3781  * only issue an UNMAP if we're short on available slots.
3782  *
3783  * Broken by design(tm).
3784  *
3785  * GICv4.1, on the other hand, mandates that we're able to invalidate
3786  * by writing to a MMIO register. It doesn't implement the whole of
3787  * DirectLPI, but that's good enough. And most of the time, we don't
3788  * even have to invalidate anything, as the redistributor can be told
3789  * whether to generate a doorbell or not (we thus leave it enabled,
3790  * always).
3791  */
3792 static void its_vpe_db_proxy_unmap_locked(struct its_vpe *vpe)
3793 {
3794 	/* GICv4.1 doesn't use a proxy, so nothing to do here */
3795 	if (gic_rdists->has_rvpeid)
3796 		return;
3797 
3798 	/* Already unmapped? */
3799 	if (vpe->vpe_proxy_event == -1)
3800 		return;
3801 
3802 	its_send_discard(vpe_proxy.dev, vpe->vpe_proxy_event);
3803 	vpe_proxy.vpes[vpe->vpe_proxy_event] = NULL;
3804 
3805 	/*
3806 	 * We don't track empty slots at all, so let's move the
3807 	 * next_victim pointer if we can quickly reuse that slot
3808 	 * instead of nuking an existing entry. Not clear that this is
3809 	 * always a win though, and this might just generate a ripple
3810 	 * effect... Let's just hope VPEs don't migrate too often.
3811 	 */
3812 	if (vpe_proxy.vpes[vpe_proxy.next_victim])
3813 		vpe_proxy.next_victim = vpe->vpe_proxy_event;
3814 
3815 	vpe->vpe_proxy_event = -1;
3816 }
3817 
3818 static void its_vpe_db_proxy_unmap(struct its_vpe *vpe)
3819 {
3820 	/* GICv4.1 doesn't use a proxy, so nothing to do here */
3821 	if (gic_rdists->has_rvpeid)
3822 		return;
3823 
3824 	if (!gic_rdists->has_direct_lpi) {
3825 		unsigned long flags;
3826 
3827 		raw_spin_lock_irqsave(&vpe_proxy.lock, flags);
3828 		its_vpe_db_proxy_unmap_locked(vpe);
3829 		raw_spin_unlock_irqrestore(&vpe_proxy.lock, flags);
3830 	}
3831 }
3832 
3833 static void its_vpe_db_proxy_map_locked(struct its_vpe *vpe)
3834 {
3835 	/* GICv4.1 doesn't use a proxy, so nothing to do here */
3836 	if (gic_rdists->has_rvpeid)
3837 		return;
3838 
3839 	/* Already mapped? */
3840 	if (vpe->vpe_proxy_event != -1)
3841 		return;
3842 
3843 	/* This slot was already allocated. Kick the other VPE out. */
3844 	if (vpe_proxy.vpes[vpe_proxy.next_victim])
3845 		its_vpe_db_proxy_unmap_locked(vpe_proxy.vpes[vpe_proxy.next_victim]);
3846 
3847 	/* Map the new VPE instead */
3848 	vpe_proxy.vpes[vpe_proxy.next_victim] = vpe;
3849 	vpe->vpe_proxy_event = vpe_proxy.next_victim;
3850 	vpe_proxy.next_victim = (vpe_proxy.next_victim + 1) % vpe_proxy.dev->nr_ites;
3851 
3852 	vpe_proxy.dev->event_map.col_map[vpe->vpe_proxy_event] = vpe->col_idx;
3853 	its_send_mapti(vpe_proxy.dev, vpe->vpe_db_lpi, vpe->vpe_proxy_event);
3854 }
3855 
3856 static void its_vpe_db_proxy_move(struct its_vpe *vpe, int from, int to)
3857 {
3858 	unsigned long flags;
3859 	struct its_collection *target_col;
3860 
3861 	/* GICv4.1 doesn't use a proxy, so nothing to do here */
3862 	if (gic_rdists->has_rvpeid)
3863 		return;
3864 
3865 	if (gic_rdists->has_direct_lpi) {
3866 		void __iomem *rdbase;
3867 
3868 		rdbase = per_cpu_ptr(gic_rdists->rdist, from)->rd_base;
3869 		gic_write_lpir(vpe->vpe_db_lpi, rdbase + GICR_CLRLPIR);
3870 		wait_for_syncr(rdbase);
3871 
3872 		return;
3873 	}
3874 
3875 	raw_spin_lock_irqsave(&vpe_proxy.lock, flags);
3876 
3877 	its_vpe_db_proxy_map_locked(vpe);
3878 
3879 	target_col = &vpe_proxy.dev->its->collections[to];
3880 	its_send_movi(vpe_proxy.dev, target_col, vpe->vpe_proxy_event);
3881 	vpe_proxy.dev->event_map.col_map[vpe->vpe_proxy_event] = to;
3882 
3883 	raw_spin_unlock_irqrestore(&vpe_proxy.lock, flags);
3884 }
3885 
3886 static int its_vpe_set_affinity(struct irq_data *d,
3887 				const struct cpumask *mask_val,
3888 				bool force)
3889 {
3890 	struct its_vpe *vpe = irq_data_get_irq_chip_data(d);
3891 	unsigned int from, cpu = nr_cpu_ids;
3892 	struct cpumask *table_mask;
3893 	unsigned long flags;
3894 
3895 	/*
3896 	 * Check if we're racing against a VPE being destroyed, for
3897 	 * which we don't want to allow a VMOVP.
3898 	 */
3899 	if (!atomic_read(&vpe->vmapp_count)) {
3900 		if (gic_requires_eager_mapping())
3901 			return -EINVAL;
3902 
3903 		/*
3904 		 * If we lazily map the VPEs, this isn't an error and
3905 		 * we can exit cleanly.
3906 		 */
3907 		cpu = cpumask_first(mask_val);
3908 		irq_data_update_effective_affinity(d, cpumask_of(cpu));
3909 		return IRQ_SET_MASK_OK_DONE;
3910 	}
3911 
3912 	/*
3913 	 * Changing affinity is mega expensive, so let's be as lazy as
3914 	 * we can and only do it if we really have to. Also, if mapped
3915 	 * into the proxy device, we need to move the doorbell
3916 	 * interrupt to its new location.
3917 	 *
3918 	 * Another thing is that changing the affinity of a vPE affects
3919 	 * *other interrupts* such as all the vLPIs that are routed to
3920 	 * this vPE. This means that the irq_desc lock is not enough to
3921 	 * protect us, and that we must ensure nobody samples vpe->col_idx
3922 	 * during the update, hence the lock below which must also be
3923 	 * taken on any vLPI handling path that evaluates vpe->col_idx.
3924 	 *
3925 	 * Finally, we must protect ourselves against concurrent updates of
3926 	 * the mapping state on this VM should the ITS list be in use (see
3927 	 * the shortcut in its_send_vmovp() otherewise).
3928 	 */
3929 	if (its_list_map)
3930 		raw_spin_lock(&vpe->its_vm->vmapp_lock);
3931 
3932 	from = vpe_to_cpuid_lock(vpe, &flags);
3933 	table_mask = gic_data_rdist_cpu(from)->vpe_table_mask;
3934 
3935 	/*
3936 	 * If we are offered another CPU in the same GICv4.1 ITS
3937 	 * affinity, pick this one. Otherwise, any CPU will do.
3938 	 */
3939 	if (table_mask)
3940 		cpu = cpumask_any_and(mask_val, table_mask);
3941 	if (cpu < nr_cpu_ids) {
3942 		if (cpumask_test_cpu(from, mask_val) &&
3943 		    cpumask_test_cpu(from, table_mask))
3944 			cpu = from;
3945 	} else {
3946 		cpu = cpumask_first(mask_val);
3947 	}
3948 
3949 	if (from == cpu)
3950 		goto out;
3951 
3952 	vpe->col_idx = cpu;
3953 
3954 	its_send_vmovp(vpe);
3955 	its_vpe_db_proxy_move(vpe, from, cpu);
3956 
3957 out:
3958 	irq_data_update_effective_affinity(d, cpumask_of(cpu));
3959 	vpe_to_cpuid_unlock(vpe, flags);
3960 
3961 	if (its_list_map)
3962 		raw_spin_unlock(&vpe->its_vm->vmapp_lock);
3963 
3964 	return IRQ_SET_MASK_OK_DONE;
3965 }
3966 
3967 static void its_wait_vpt_parse_complete(void)
3968 {
3969 	void __iomem *vlpi_base = gic_data_rdist_vlpi_base();
3970 	u64 val;
3971 
3972 	if (!gic_rdists->has_vpend_valid_dirty)
3973 		return;
3974 
3975 	WARN_ON_ONCE(readq_relaxed_poll_timeout_atomic(vlpi_base + GICR_VPENDBASER,
3976 						       val,
3977 						       !(val & GICR_VPENDBASER_Dirty),
3978 						       1, 500));
3979 }
3980 
3981 static void its_vpe_schedule(struct its_vpe *vpe)
3982 {
3983 	void __iomem *vlpi_base = gic_data_rdist_vlpi_base();
3984 	u64 val;
3985 
3986 	/* Schedule the VPE */
3987 	val  = virt_to_phys(page_address(vpe->its_vm->vprop_page)) &
3988 		GENMASK_ULL(51, 12);
3989 	val |= (LPI_NRBITS - 1) & GICR_VPROPBASER_IDBITS_MASK;
3990 	if (rdists_support_shareable()) {
3991 		val |= GICR_VPROPBASER_RaWb;
3992 		val |= GICR_VPROPBASER_InnerShareable;
3993 	}
3994 	gicr_write_vpropbaser(val, vlpi_base + GICR_VPROPBASER);
3995 
3996 	val  = virt_to_phys(page_address(vpe->vpt_page)) &
3997 		GENMASK_ULL(51, 16);
3998 	if (rdists_support_shareable()) {
3999 		val |= GICR_VPENDBASER_RaWaWb;
4000 		val |= GICR_VPENDBASER_InnerShareable;
4001 	}
4002 	/*
4003 	 * There is no good way of finding out if the pending table is
4004 	 * empty as we can race against the doorbell interrupt very
4005 	 * easily. So in the end, vpe->pending_last is only an
4006 	 * indication that the vcpu has something pending, not one
4007 	 * that the pending table is empty. A good implementation
4008 	 * would be able to read its coarse map pretty quickly anyway,
4009 	 * making this a tolerable issue.
4010 	 */
4011 	val |= GICR_VPENDBASER_PendingLast;
4012 	val |= vpe->idai ? GICR_VPENDBASER_IDAI : 0;
4013 	val |= GICR_VPENDBASER_Valid;
4014 	gicr_write_vpendbaser(val, vlpi_base + GICR_VPENDBASER);
4015 }
4016 
4017 static void its_vpe_deschedule(struct its_vpe *vpe)
4018 {
4019 	void __iomem *vlpi_base = gic_data_rdist_vlpi_base();
4020 	u64 val;
4021 
4022 	val = its_clear_vpend_valid(vlpi_base, 0, 0);
4023 
4024 	vpe->idai = !!(val & GICR_VPENDBASER_IDAI);
4025 	vpe->pending_last = !!(val & GICR_VPENDBASER_PendingLast);
4026 }
4027 
4028 static void its_vpe_invall(struct its_vpe *vpe)
4029 {
4030 	struct its_node *its;
4031 
4032 	guard(raw_spinlock_irqsave)(&vpe->its_vm->vmapp_lock);
4033 
4034 	list_for_each_entry(its, &its_nodes, entry) {
4035 		if (!is_v4(its))
4036 			continue;
4037 
4038 		if (its_list_map && !vpe->its_vm->vlpi_count[its->list_nr])
4039 			continue;
4040 
4041 		/*
4042 		 * Sending a VINVALL to a single ITS is enough, as all
4043 		 * we need is to reach the redistributors.
4044 		 */
4045 		its_send_vinvall(its, vpe);
4046 		return;
4047 	}
4048 }
4049 
4050 static int its_vpe_set_vcpu_affinity(struct irq_data *d, void *vcpu_info)
4051 {
4052 	struct its_vpe *vpe = irq_data_get_irq_chip_data(d);
4053 	struct its_cmd_info *info = vcpu_info;
4054 
4055 	switch (info->cmd_type) {
4056 	case SCHEDULE_VPE:
4057 		its_vpe_schedule(vpe);
4058 		return 0;
4059 
4060 	case DESCHEDULE_VPE:
4061 		its_vpe_deschedule(vpe);
4062 		return 0;
4063 
4064 	case COMMIT_VPE:
4065 		its_wait_vpt_parse_complete();
4066 		return 0;
4067 
4068 	case INVALL_VPE:
4069 		its_vpe_invall(vpe);
4070 		return 0;
4071 
4072 	default:
4073 		return -EINVAL;
4074 	}
4075 }
4076 
4077 static void its_vpe_send_cmd(struct its_vpe *vpe,
4078 			     void (*cmd)(struct its_device *, u32))
4079 {
4080 	unsigned long flags;
4081 
4082 	raw_spin_lock_irqsave(&vpe_proxy.lock, flags);
4083 
4084 	its_vpe_db_proxy_map_locked(vpe);
4085 	cmd(vpe_proxy.dev, vpe->vpe_proxy_event);
4086 
4087 	raw_spin_unlock_irqrestore(&vpe_proxy.lock, flags);
4088 }
4089 
4090 static void its_vpe_send_inv(struct irq_data *d)
4091 {
4092 	struct its_vpe *vpe = irq_data_get_irq_chip_data(d);
4093 
4094 	if (gic_rdists->has_direct_lpi)
4095 		__direct_lpi_inv(d, d->parent_data->hwirq);
4096 	else
4097 		its_vpe_send_cmd(vpe, its_send_inv);
4098 }
4099 
4100 static void its_vpe_mask_irq(struct irq_data *d)
4101 {
4102 	/*
4103 	 * We need to unmask the LPI, which is described by the parent
4104 	 * irq_data. Instead of calling into the parent (which won't
4105 	 * exactly do the right thing, let's simply use the
4106 	 * parent_data pointer. Yes, I'm naughty.
4107 	 */
4108 	lpi_write_config(d->parent_data, LPI_PROP_ENABLED, 0);
4109 	its_vpe_send_inv(d);
4110 }
4111 
4112 static void its_vpe_unmask_irq(struct irq_data *d)
4113 {
4114 	/* Same hack as above... */
4115 	lpi_write_config(d->parent_data, 0, LPI_PROP_ENABLED);
4116 	its_vpe_send_inv(d);
4117 }
4118 
4119 static int its_vpe_set_irqchip_state(struct irq_data *d,
4120 				     enum irqchip_irq_state which,
4121 				     bool state)
4122 {
4123 	struct its_vpe *vpe = irq_data_get_irq_chip_data(d);
4124 
4125 	if (which != IRQCHIP_STATE_PENDING)
4126 		return -EINVAL;
4127 
4128 	if (gic_rdists->has_direct_lpi) {
4129 		void __iomem *rdbase;
4130 
4131 		rdbase = per_cpu_ptr(gic_rdists->rdist, vpe->col_idx)->rd_base;
4132 		if (state) {
4133 			gic_write_lpir(vpe->vpe_db_lpi, rdbase + GICR_SETLPIR);
4134 		} else {
4135 			gic_write_lpir(vpe->vpe_db_lpi, rdbase + GICR_CLRLPIR);
4136 			wait_for_syncr(rdbase);
4137 		}
4138 	} else {
4139 		if (state)
4140 			its_vpe_send_cmd(vpe, its_send_int);
4141 		else
4142 			its_vpe_send_cmd(vpe, its_send_clear);
4143 	}
4144 
4145 	return 0;
4146 }
4147 
4148 static int its_vpe_retrigger(struct irq_data *d)
4149 {
4150 	return !its_vpe_set_irqchip_state(d, IRQCHIP_STATE_PENDING, true);
4151 }
4152 
4153 static struct irq_chip its_vpe_irq_chip = {
4154 	.name			= "GICv4-vpe",
4155 	.irq_mask		= its_vpe_mask_irq,
4156 	.irq_unmask		= its_vpe_unmask_irq,
4157 	.irq_eoi		= irq_chip_eoi_parent,
4158 	.irq_set_affinity	= its_vpe_set_affinity,
4159 	.irq_retrigger		= its_vpe_retrigger,
4160 	.irq_set_irqchip_state	= its_vpe_set_irqchip_state,
4161 	.irq_set_vcpu_affinity	= its_vpe_set_vcpu_affinity,
4162 };
4163 
4164 static struct its_node *find_4_1_its(void)
4165 {
4166 	static struct its_node *its = NULL;
4167 
4168 	if (!its) {
4169 		list_for_each_entry(its, &its_nodes, entry) {
4170 			if (is_v4_1(its))
4171 				return its;
4172 		}
4173 
4174 		/* Oops? */
4175 		its = NULL;
4176 	}
4177 
4178 	return its;
4179 }
4180 
4181 static void its_vpe_4_1_send_inv(struct irq_data *d)
4182 {
4183 	struct its_vpe *vpe = irq_data_get_irq_chip_data(d);
4184 	struct its_node *its;
4185 
4186 	/*
4187 	 * GICv4.1 wants doorbells to be invalidated using the
4188 	 * INVDB command in order to be broadcast to all RDs. Send
4189 	 * it to the first valid ITS, and let the HW do its magic.
4190 	 */
4191 	its = find_4_1_its();
4192 	if (its)
4193 		its_send_invdb(its, vpe);
4194 }
4195 
4196 static void its_vpe_4_1_mask_irq(struct irq_data *d)
4197 {
4198 	lpi_write_config(d->parent_data, LPI_PROP_ENABLED, 0);
4199 	its_vpe_4_1_send_inv(d);
4200 }
4201 
4202 static void its_vpe_4_1_unmask_irq(struct irq_data *d)
4203 {
4204 	lpi_write_config(d->parent_data, 0, LPI_PROP_ENABLED);
4205 	its_vpe_4_1_send_inv(d);
4206 }
4207 
4208 static void its_vpe_4_1_schedule(struct its_vpe *vpe,
4209 				 struct its_cmd_info *info)
4210 {
4211 	void __iomem *vlpi_base = gic_data_rdist_vlpi_base();
4212 	u64 val = 0;
4213 
4214 	/* Schedule the VPE */
4215 	val |= GICR_VPENDBASER_Valid;
4216 	val |= info->g0en ? GICR_VPENDBASER_4_1_VGRP0EN : 0;
4217 	val |= info->g1en ? GICR_VPENDBASER_4_1_VGRP1EN : 0;
4218 	val |= FIELD_PREP(GICR_VPENDBASER_4_1_VPEID, vpe->vpe_id);
4219 
4220 	gicr_write_vpendbaser(val, vlpi_base + GICR_VPENDBASER);
4221 }
4222 
4223 static void its_vpe_4_1_deschedule(struct its_vpe *vpe,
4224 				   struct its_cmd_info *info)
4225 {
4226 	void __iomem *vlpi_base = gic_data_rdist_vlpi_base();
4227 	u64 val;
4228 
4229 	if (info->req_db) {
4230 		unsigned long flags;
4231 
4232 		/*
4233 		 * vPE is going to block: make the vPE non-resident with
4234 		 * PendingLast clear and DB set. The GIC guarantees that if
4235 		 * we read-back PendingLast clear, then a doorbell will be
4236 		 * delivered when an interrupt comes.
4237 		 *
4238 		 * Note the locking to deal with the concurrent update of
4239 		 * pending_last from the doorbell interrupt handler that can
4240 		 * run concurrently.
4241 		 */
4242 		raw_spin_lock_irqsave(&vpe->vpe_lock, flags);
4243 		val = its_clear_vpend_valid(vlpi_base,
4244 					    GICR_VPENDBASER_PendingLast,
4245 					    GICR_VPENDBASER_4_1_DB);
4246 		vpe->pending_last = !!(val & GICR_VPENDBASER_PendingLast);
4247 		raw_spin_unlock_irqrestore(&vpe->vpe_lock, flags);
4248 	} else {
4249 		/*
4250 		 * We're not blocking, so just make the vPE non-resident
4251 		 * with PendingLast set, indicating that we'll be back.
4252 		 */
4253 		val = its_clear_vpend_valid(vlpi_base,
4254 					    0,
4255 					    GICR_VPENDBASER_PendingLast);
4256 		vpe->pending_last = true;
4257 	}
4258 }
4259 
4260 static void its_vpe_4_1_invall(struct its_vpe *vpe)
4261 {
4262 	void __iomem *rdbase;
4263 	unsigned long flags;
4264 	u64 val;
4265 	int cpu;
4266 
4267 	val  = GICR_INVALLR_V;
4268 	val |= FIELD_PREP(GICR_INVALLR_VPEID, vpe->vpe_id);
4269 
4270 	/* Target the redistributor this vPE is currently known on */
4271 	cpu = vpe_to_cpuid_lock(vpe, &flags);
4272 	raw_spin_lock(&gic_data_rdist_cpu(cpu)->rd_lock);
4273 	rdbase = per_cpu_ptr(gic_rdists->rdist, cpu)->rd_base;
4274 	gic_write_lpir(val, rdbase + GICR_INVALLR);
4275 
4276 	wait_for_syncr(rdbase);
4277 	raw_spin_unlock(&gic_data_rdist_cpu(cpu)->rd_lock);
4278 	vpe_to_cpuid_unlock(vpe, flags);
4279 }
4280 
4281 static int its_vpe_4_1_set_vcpu_affinity(struct irq_data *d, void *vcpu_info)
4282 {
4283 	struct its_vpe *vpe = irq_data_get_irq_chip_data(d);
4284 	struct its_cmd_info *info = vcpu_info;
4285 
4286 	switch (info->cmd_type) {
4287 	case SCHEDULE_VPE:
4288 		its_vpe_4_1_schedule(vpe, info);
4289 		return 0;
4290 
4291 	case DESCHEDULE_VPE:
4292 		its_vpe_4_1_deschedule(vpe, info);
4293 		return 0;
4294 
4295 	case COMMIT_VPE:
4296 		its_wait_vpt_parse_complete();
4297 		return 0;
4298 
4299 	case INVALL_VPE:
4300 		its_vpe_4_1_invall(vpe);
4301 		return 0;
4302 
4303 	default:
4304 		return -EINVAL;
4305 	}
4306 }
4307 
4308 static struct irq_chip its_vpe_4_1_irq_chip = {
4309 	.name			= "GICv4.1-vpe",
4310 	.irq_mask		= its_vpe_4_1_mask_irq,
4311 	.irq_unmask		= its_vpe_4_1_unmask_irq,
4312 	.irq_eoi		= irq_chip_eoi_parent,
4313 	.irq_set_affinity	= its_vpe_set_affinity,
4314 	.irq_set_vcpu_affinity	= its_vpe_4_1_set_vcpu_affinity,
4315 };
4316 
4317 static void its_configure_sgi(struct irq_data *d, bool clear)
4318 {
4319 	struct its_vpe *vpe = irq_data_get_irq_chip_data(d);
4320 	struct its_cmd_desc desc;
4321 
4322 	desc.its_vsgi_cmd.vpe = vpe;
4323 	desc.its_vsgi_cmd.sgi = d->hwirq;
4324 	desc.its_vsgi_cmd.priority = vpe->sgi_config[d->hwirq].priority;
4325 	desc.its_vsgi_cmd.enable = vpe->sgi_config[d->hwirq].enabled;
4326 	desc.its_vsgi_cmd.group = vpe->sgi_config[d->hwirq].group;
4327 	desc.its_vsgi_cmd.clear = clear;
4328 
4329 	/*
4330 	 * GICv4.1 allows us to send VSGI commands to any ITS as long as the
4331 	 * destination VPE is mapped there. Since we map them eagerly at
4332 	 * activation time, we're pretty sure the first GICv4.1 ITS will do.
4333 	 */
4334 	its_send_single_vcommand(find_4_1_its(), its_build_vsgi_cmd, &desc);
4335 }
4336 
4337 static void its_sgi_mask_irq(struct irq_data *d)
4338 {
4339 	struct its_vpe *vpe = irq_data_get_irq_chip_data(d);
4340 
4341 	vpe->sgi_config[d->hwirq].enabled = false;
4342 	its_configure_sgi(d, false);
4343 }
4344 
4345 static void its_sgi_unmask_irq(struct irq_data *d)
4346 {
4347 	struct its_vpe *vpe = irq_data_get_irq_chip_data(d);
4348 
4349 	vpe->sgi_config[d->hwirq].enabled = true;
4350 	its_configure_sgi(d, false);
4351 }
4352 
4353 static int its_sgi_set_affinity(struct irq_data *d,
4354 				const struct cpumask *mask_val,
4355 				bool force)
4356 {
4357 	/*
4358 	 * There is no notion of affinity for virtual SGIs, at least
4359 	 * not on the host (since they can only be targeting a vPE).
4360 	 * Tell the kernel we've done whatever it asked for.
4361 	 */
4362 	irq_data_update_effective_affinity(d, mask_val);
4363 	return IRQ_SET_MASK_OK;
4364 }
4365 
4366 static int its_sgi_set_irqchip_state(struct irq_data *d,
4367 				     enum irqchip_irq_state which,
4368 				     bool state)
4369 {
4370 	if (which != IRQCHIP_STATE_PENDING)
4371 		return -EINVAL;
4372 
4373 	if (state) {
4374 		struct its_vpe *vpe = irq_data_get_irq_chip_data(d);
4375 		struct its_node *its = find_4_1_its();
4376 		u64 val;
4377 
4378 		val  = FIELD_PREP(GITS_SGIR_VPEID, vpe->vpe_id);
4379 		val |= FIELD_PREP(GITS_SGIR_VINTID, d->hwirq);
4380 		writeq_relaxed(val, its->sgir_base + GITS_SGIR - SZ_128K);
4381 	} else {
4382 		its_configure_sgi(d, true);
4383 	}
4384 
4385 	return 0;
4386 }
4387 
4388 static int its_sgi_get_irqchip_state(struct irq_data *d,
4389 				     enum irqchip_irq_state which, bool *val)
4390 {
4391 	struct its_vpe *vpe = irq_data_get_irq_chip_data(d);
4392 	void __iomem *base;
4393 	unsigned long flags;
4394 	u32 count = 1000000;	/* 1s! */
4395 	u32 status;
4396 	int cpu;
4397 
4398 	if (which != IRQCHIP_STATE_PENDING)
4399 		return -EINVAL;
4400 
4401 	/*
4402 	 * Locking galore! We can race against two different events:
4403 	 *
4404 	 * - Concurrent vPE affinity change: we must make sure it cannot
4405 	 *   happen, or we'll talk to the wrong redistributor. This is
4406 	 *   identical to what happens with vLPIs.
4407 	 *
4408 	 * - Concurrent VSGIPENDR access: As it involves accessing two
4409 	 *   MMIO registers, this must be made atomic one way or another.
4410 	 */
4411 	cpu = vpe_to_cpuid_lock(vpe, &flags);
4412 	raw_spin_lock(&gic_data_rdist_cpu(cpu)->rd_lock);
4413 	base = gic_data_rdist_cpu(cpu)->rd_base + SZ_128K;
4414 	writel_relaxed(vpe->vpe_id, base + GICR_VSGIR);
4415 	do {
4416 		status = readl_relaxed(base + GICR_VSGIPENDR);
4417 		if (!(status & GICR_VSGIPENDR_BUSY))
4418 			goto out;
4419 
4420 		count--;
4421 		if (!count) {
4422 			pr_err_ratelimited("Unable to get SGI status\n");
4423 			goto out;
4424 		}
4425 		cpu_relax();
4426 		udelay(1);
4427 	} while (count);
4428 
4429 out:
4430 	raw_spin_unlock(&gic_data_rdist_cpu(cpu)->rd_lock);
4431 	vpe_to_cpuid_unlock(vpe, flags);
4432 
4433 	if (!count)
4434 		return -ENXIO;
4435 
4436 	*val = !!(status & (1 << d->hwirq));
4437 
4438 	return 0;
4439 }
4440 
4441 static int its_sgi_set_vcpu_affinity(struct irq_data *d, void *vcpu_info)
4442 {
4443 	struct its_vpe *vpe = irq_data_get_irq_chip_data(d);
4444 	struct its_cmd_info *info = vcpu_info;
4445 
4446 	switch (info->cmd_type) {
4447 	case PROP_UPDATE_VSGI:
4448 		vpe->sgi_config[d->hwirq].priority = info->priority;
4449 		vpe->sgi_config[d->hwirq].group = info->group;
4450 		its_configure_sgi(d, false);
4451 		return 0;
4452 
4453 	default:
4454 		return -EINVAL;
4455 	}
4456 }
4457 
4458 static struct irq_chip its_sgi_irq_chip = {
4459 	.name			= "GICv4.1-sgi",
4460 	.irq_mask		= its_sgi_mask_irq,
4461 	.irq_unmask		= its_sgi_unmask_irq,
4462 	.irq_set_affinity	= its_sgi_set_affinity,
4463 	.irq_set_irqchip_state	= its_sgi_set_irqchip_state,
4464 	.irq_get_irqchip_state	= its_sgi_get_irqchip_state,
4465 	.irq_set_vcpu_affinity	= its_sgi_set_vcpu_affinity,
4466 };
4467 
4468 static int its_sgi_irq_domain_alloc(struct irq_domain *domain,
4469 				    unsigned int virq, unsigned int nr_irqs,
4470 				    void *args)
4471 {
4472 	struct its_vpe *vpe = args;
4473 	int i;
4474 
4475 	/* Yes, we do want 16 SGIs */
4476 	WARN_ON(nr_irqs != 16);
4477 
4478 	for (i = 0; i < 16; i++) {
4479 		vpe->sgi_config[i].priority = 0;
4480 		vpe->sgi_config[i].enabled = false;
4481 		vpe->sgi_config[i].group = false;
4482 
4483 		irq_domain_set_hwirq_and_chip(domain, virq + i, i,
4484 					      &its_sgi_irq_chip, vpe);
4485 		irq_set_status_flags(virq + i, IRQ_DISABLE_UNLAZY);
4486 	}
4487 
4488 	return 0;
4489 }
4490 
4491 static void its_sgi_irq_domain_free(struct irq_domain *domain,
4492 				    unsigned int virq,
4493 				    unsigned int nr_irqs)
4494 {
4495 	/* Nothing to do */
4496 }
4497 
4498 static int its_sgi_irq_domain_activate(struct irq_domain *domain,
4499 				       struct irq_data *d, bool reserve)
4500 {
4501 	/* Write out the initial SGI configuration */
4502 	its_configure_sgi(d, false);
4503 	return 0;
4504 }
4505 
4506 static void its_sgi_irq_domain_deactivate(struct irq_domain *domain,
4507 					  struct irq_data *d)
4508 {
4509 	struct its_vpe *vpe = irq_data_get_irq_chip_data(d);
4510 
4511 	/*
4512 	 * The VSGI command is awkward:
4513 	 *
4514 	 * - To change the configuration, CLEAR must be set to false,
4515 	 *   leaving the pending bit unchanged.
4516 	 * - To clear the pending bit, CLEAR must be set to true, leaving
4517 	 *   the configuration unchanged.
4518 	 *
4519 	 * You just can't do both at once, hence the two commands below.
4520 	 */
4521 	vpe->sgi_config[d->hwirq].enabled = false;
4522 	its_configure_sgi(d, false);
4523 	its_configure_sgi(d, true);
4524 }
4525 
4526 static const struct irq_domain_ops its_sgi_domain_ops = {
4527 	.alloc		= its_sgi_irq_domain_alloc,
4528 	.free		= its_sgi_irq_domain_free,
4529 	.activate	= its_sgi_irq_domain_activate,
4530 	.deactivate	= its_sgi_irq_domain_deactivate,
4531 };
4532 
4533 static int its_vpe_id_alloc(void)
4534 {
4535 	return ida_alloc_max(&its_vpeid_ida, ITS_MAX_VPEID - 1, GFP_KERNEL);
4536 }
4537 
4538 static void its_vpe_id_free(u16 id)
4539 {
4540 	ida_free(&its_vpeid_ida, id);
4541 }
4542 
4543 static int its_vpe_init(struct its_vpe *vpe)
4544 {
4545 	struct page *vpt_page;
4546 	int vpe_id;
4547 
4548 	/* Allocate vpe_id */
4549 	vpe_id = its_vpe_id_alloc();
4550 	if (vpe_id < 0)
4551 		return vpe_id;
4552 
4553 	/* Allocate VPT */
4554 	vpt_page = its_allocate_pending_table(GFP_KERNEL);
4555 	if (!vpt_page) {
4556 		its_vpe_id_free(vpe_id);
4557 		return -ENOMEM;
4558 	}
4559 
4560 	if (!its_alloc_vpe_table(vpe_id)) {
4561 		its_vpe_id_free(vpe_id);
4562 		its_free_pending_table(vpt_page);
4563 		return -ENOMEM;
4564 	}
4565 
4566 	raw_spin_lock_init(&vpe->vpe_lock);
4567 	vpe->vpe_id = vpe_id;
4568 	vpe->vpt_page = vpt_page;
4569 	atomic_set(&vpe->vmapp_count, 0);
4570 	if (!gic_rdists->has_rvpeid)
4571 		vpe->vpe_proxy_event = -1;
4572 
4573 	return 0;
4574 }
4575 
4576 static void its_vpe_teardown(struct its_vpe *vpe)
4577 {
4578 	its_vpe_db_proxy_unmap(vpe);
4579 	its_vpe_id_free(vpe->vpe_id);
4580 	its_free_pending_table(vpe->vpt_page);
4581 }
4582 
4583 static void its_vpe_irq_domain_free(struct irq_domain *domain,
4584 				    unsigned int virq,
4585 				    unsigned int nr_irqs)
4586 {
4587 	struct its_vm *vm = domain->host_data;
4588 	int i;
4589 
4590 	irq_domain_free_irqs_parent(domain, virq, nr_irqs);
4591 
4592 	for (i = 0; i < nr_irqs; i++) {
4593 		struct irq_data *data = irq_domain_get_irq_data(domain,
4594 								virq + i);
4595 		struct its_vpe *vpe = irq_data_get_irq_chip_data(data);
4596 
4597 		BUG_ON(vm != vpe->its_vm);
4598 
4599 		clear_bit(data->hwirq, vm->db_bitmap);
4600 		its_vpe_teardown(vpe);
4601 		irq_domain_reset_irq_data(data);
4602 	}
4603 
4604 	if (bitmap_empty(vm->db_bitmap, vm->nr_db_lpis)) {
4605 		its_lpi_free(vm->db_bitmap, vm->db_lpi_base, vm->nr_db_lpis);
4606 		its_free_prop_table(vm->vprop_page);
4607 	}
4608 }
4609 
4610 static int its_vpe_irq_domain_alloc(struct irq_domain *domain, unsigned int virq,
4611 				    unsigned int nr_irqs, void *args)
4612 {
4613 	struct irq_chip *irqchip = &its_vpe_irq_chip;
4614 	struct its_vm *vm = args;
4615 	unsigned long *bitmap;
4616 	struct page *vprop_page;
4617 	int base, nr_ids, i, err = 0;
4618 
4619 	bitmap = its_lpi_alloc(roundup_pow_of_two(nr_irqs), &base, &nr_ids);
4620 	if (!bitmap)
4621 		return -ENOMEM;
4622 
4623 	if (nr_ids < nr_irqs) {
4624 		its_lpi_free(bitmap, base, nr_ids);
4625 		return -ENOMEM;
4626 	}
4627 
4628 	vprop_page = its_allocate_prop_table(GFP_KERNEL);
4629 	if (!vprop_page) {
4630 		its_lpi_free(bitmap, base, nr_ids);
4631 		return -ENOMEM;
4632 	}
4633 
4634 	vm->db_bitmap = bitmap;
4635 	vm->db_lpi_base = base;
4636 	vm->nr_db_lpis = nr_ids;
4637 	vm->vprop_page = vprop_page;
4638 	raw_spin_lock_init(&vm->vmapp_lock);
4639 
4640 	if (gic_rdists->has_rvpeid)
4641 		irqchip = &its_vpe_4_1_irq_chip;
4642 
4643 	for (i = 0; i < nr_irqs; i++) {
4644 		vm->vpes[i]->vpe_db_lpi = base + i;
4645 		err = its_vpe_init(vm->vpes[i]);
4646 		if (err)
4647 			break;
4648 		err = its_irq_gic_domain_alloc(domain, virq + i,
4649 					       vm->vpes[i]->vpe_db_lpi);
4650 		if (err)
4651 			break;
4652 		irq_domain_set_hwirq_and_chip(domain, virq + i, i,
4653 					      irqchip, vm->vpes[i]);
4654 		set_bit(i, bitmap);
4655 		irqd_set_resend_when_in_progress(irq_get_irq_data(virq + i));
4656 	}
4657 
4658 	if (err)
4659 		its_vpe_irq_domain_free(domain, virq, i);
4660 
4661 	return err;
4662 }
4663 
4664 static int its_vpe_irq_domain_activate(struct irq_domain *domain,
4665 				       struct irq_data *d, bool reserve)
4666 {
4667 	struct its_vpe *vpe = irq_data_get_irq_chip_data(d);
4668 	struct its_node *its;
4669 
4670 	/* Map the VPE to the first possible CPU */
4671 	vpe->col_idx = cpumask_first(cpu_online_mask);
4672 	irq_data_update_effective_affinity(d, cpumask_of(vpe->col_idx));
4673 
4674 	/*
4675 	 * If we use the list map, we issue VMAPP on demand... Unless
4676 	 * we're on a GICv4.1 and we eagerly map the VPE on all ITSs
4677 	 * so that VSGIs can work.
4678 	 */
4679 	if (!gic_requires_eager_mapping())
4680 		return 0;
4681 
4682 	list_for_each_entry(its, &its_nodes, entry) {
4683 		if (!is_v4(its))
4684 			continue;
4685 
4686 		its_send_vmapp(its, vpe, true);
4687 		its_send_vinvall(its, vpe);
4688 	}
4689 
4690 	return 0;
4691 }
4692 
4693 static void its_vpe_irq_domain_deactivate(struct irq_domain *domain,
4694 					  struct irq_data *d)
4695 {
4696 	struct its_vpe *vpe = irq_data_get_irq_chip_data(d);
4697 	struct its_node *its;
4698 
4699 	/*
4700 	 * If we use the list map on GICv4.0, we unmap the VPE once no
4701 	 * VLPIs are associated with the VM.
4702 	 */
4703 	if (!gic_requires_eager_mapping())
4704 		return;
4705 
4706 	list_for_each_entry(its, &its_nodes, entry) {
4707 		if (!is_v4(its))
4708 			continue;
4709 
4710 		its_send_vmapp(its, vpe, false);
4711 	}
4712 
4713 	/*
4714 	 * There may be a direct read to the VPT after unmapping the
4715 	 * vPE, to guarantee the validity of this, we make the VPT
4716 	 * memory coherent with the CPU caches here.
4717 	 */
4718 	if (find_4_1_its() && !atomic_read(&vpe->vmapp_count))
4719 		gic_flush_dcache_to_poc(page_address(vpe->vpt_page),
4720 					LPI_PENDBASE_SZ);
4721 }
4722 
4723 static const struct irq_domain_ops its_vpe_domain_ops = {
4724 	.alloc			= its_vpe_irq_domain_alloc,
4725 	.free			= its_vpe_irq_domain_free,
4726 	.activate		= its_vpe_irq_domain_activate,
4727 	.deactivate		= its_vpe_irq_domain_deactivate,
4728 };
4729 
4730 static int its_force_quiescent(void __iomem *base)
4731 {
4732 	u32 count = 1000000;	/* 1s */
4733 	u32 val;
4734 
4735 	val = readl_relaxed(base + GITS_CTLR);
4736 	/*
4737 	 * GIC architecture specification requires the ITS to be both
4738 	 * disabled and quiescent for writes to GITS_BASER<n> or
4739 	 * GITS_CBASER to not have UNPREDICTABLE results.
4740 	 */
4741 	if ((val & GITS_CTLR_QUIESCENT) && !(val & GITS_CTLR_ENABLE))
4742 		return 0;
4743 
4744 	/* Disable the generation of all interrupts to this ITS */
4745 	val &= ~(GITS_CTLR_ENABLE | GITS_CTLR_ImDe);
4746 	writel_relaxed(val, base + GITS_CTLR);
4747 
4748 	/* Poll GITS_CTLR and wait until ITS becomes quiescent */
4749 	while (1) {
4750 		val = readl_relaxed(base + GITS_CTLR);
4751 		if (val & GITS_CTLR_QUIESCENT)
4752 			return 0;
4753 
4754 		count--;
4755 		if (!count)
4756 			return -EBUSY;
4757 
4758 		cpu_relax();
4759 		udelay(1);
4760 	}
4761 }
4762 
4763 static bool __maybe_unused its_enable_quirk_cavium_22375(void *data)
4764 {
4765 	struct its_node *its = data;
4766 
4767 	/* erratum 22375: only alloc 8MB table size (20 bits) */
4768 	its->typer &= ~GITS_TYPER_DEVBITS;
4769 	its->typer |= FIELD_PREP(GITS_TYPER_DEVBITS, 20 - 1);
4770 	its->flags |= ITS_FLAGS_WORKAROUND_CAVIUM_22375;
4771 
4772 	return true;
4773 }
4774 
4775 static bool __maybe_unused its_enable_quirk_cavium_23144(void *data)
4776 {
4777 	struct its_node *its = data;
4778 
4779 	its->flags |= ITS_FLAGS_WORKAROUND_CAVIUM_23144;
4780 
4781 	return true;
4782 }
4783 
4784 static bool __maybe_unused its_enable_quirk_qdf2400_e0065(void *data)
4785 {
4786 	struct its_node *its = data;
4787 
4788 	/* On QDF2400, the size of the ITE is 16Bytes */
4789 	its->typer &= ~GITS_TYPER_ITT_ENTRY_SIZE;
4790 	its->typer |= FIELD_PREP(GITS_TYPER_ITT_ENTRY_SIZE, 16 - 1);
4791 
4792 	return true;
4793 }
4794 
4795 static u64 its_irq_get_msi_base_pre_its(struct its_device *its_dev)
4796 {
4797 	struct its_node *its = its_dev->its;
4798 
4799 	/*
4800 	 * The Socionext Synquacer SoC has a so-called 'pre-ITS',
4801 	 * which maps 32-bit writes targeted at a separate window of
4802 	 * size '4 << device_id_bits' onto writes to GITS_TRANSLATER
4803 	 * with device ID taken from bits [device_id_bits + 1:2] of
4804 	 * the window offset.
4805 	 */
4806 	return its->pre_its_base + (its_dev->device_id << 2);
4807 }
4808 
4809 static bool __maybe_unused its_enable_quirk_socionext_synquacer(void *data)
4810 {
4811 	struct its_node *its = data;
4812 	u32 pre_its_window[2];
4813 	u32 ids;
4814 
4815 	if (!fwnode_property_read_u32_array(its->fwnode_handle,
4816 					   "socionext,synquacer-pre-its",
4817 					   pre_its_window,
4818 					   ARRAY_SIZE(pre_its_window))) {
4819 
4820 		its->pre_its_base = pre_its_window[0];
4821 		its->get_msi_base = its_irq_get_msi_base_pre_its;
4822 
4823 		ids = ilog2(pre_its_window[1]) - 2;
4824 		if (device_ids(its) > ids) {
4825 			its->typer &= ~GITS_TYPER_DEVBITS;
4826 			its->typer |= FIELD_PREP(GITS_TYPER_DEVBITS, ids - 1);
4827 		}
4828 
4829 		/* the pre-ITS breaks isolation, so disable MSI remapping */
4830 		its->msi_domain_flags &= ~IRQ_DOMAIN_FLAG_ISOLATED_MSI;
4831 		return true;
4832 	}
4833 	return false;
4834 }
4835 
4836 static bool __maybe_unused its_enable_quirk_hip07_161600802(void *data)
4837 {
4838 	struct its_node *its = data;
4839 
4840 	/*
4841 	 * Hip07 insists on using the wrong address for the VLPI
4842 	 * page. Trick it into doing the right thing...
4843 	 */
4844 	its->vlpi_redist_offset = SZ_128K;
4845 	return true;
4846 }
4847 
4848 static bool __maybe_unused its_enable_rk3588001(void *data)
4849 {
4850 	struct its_node *its = data;
4851 
4852 	if (!of_machine_is_compatible("rockchip,rk3588") &&
4853 	    !of_machine_is_compatible("rockchip,rk3588s"))
4854 		return false;
4855 
4856 	its->flags |= ITS_FLAGS_FORCE_NON_SHAREABLE;
4857 	gic_rdists->flags |= RDIST_FLAGS_FORCE_NON_SHAREABLE;
4858 
4859 	return true;
4860 }
4861 
4862 static bool its_set_non_coherent(void *data)
4863 {
4864 	struct its_node *its = data;
4865 
4866 	its->flags |= ITS_FLAGS_FORCE_NON_SHAREABLE;
4867 	return true;
4868 }
4869 
4870 static const struct gic_quirk its_quirks[] = {
4871 #ifdef CONFIG_CAVIUM_ERRATUM_22375
4872 	{
4873 		.desc	= "ITS: Cavium errata 22375, 24313",
4874 		.iidr	= 0xa100034c,	/* ThunderX pass 1.x */
4875 		.mask	= 0xffff0fff,
4876 		.init	= its_enable_quirk_cavium_22375,
4877 	},
4878 #endif
4879 #ifdef CONFIG_CAVIUM_ERRATUM_23144
4880 	{
4881 		.desc	= "ITS: Cavium erratum 23144",
4882 		.iidr	= 0xa100034c,	/* ThunderX pass 1.x */
4883 		.mask	= 0xffff0fff,
4884 		.init	= its_enable_quirk_cavium_23144,
4885 	},
4886 #endif
4887 #ifdef CONFIG_QCOM_QDF2400_ERRATUM_0065
4888 	{
4889 		.desc	= "ITS: QDF2400 erratum 0065",
4890 		.iidr	= 0x00001070, /* QDF2400 ITS rev 1.x */
4891 		.mask	= 0xffffffff,
4892 		.init	= its_enable_quirk_qdf2400_e0065,
4893 	},
4894 #endif
4895 #ifdef CONFIG_SOCIONEXT_SYNQUACER_PREITS
4896 	{
4897 		/*
4898 		 * The Socionext Synquacer SoC incorporates ARM's own GIC-500
4899 		 * implementation, but with a 'pre-ITS' added that requires
4900 		 * special handling in software.
4901 		 */
4902 		.desc	= "ITS: Socionext Synquacer pre-ITS",
4903 		.iidr	= 0x0001143b,
4904 		.mask	= 0xffffffff,
4905 		.init	= its_enable_quirk_socionext_synquacer,
4906 	},
4907 #endif
4908 #ifdef CONFIG_HISILICON_ERRATUM_161600802
4909 	{
4910 		.desc	= "ITS: Hip07 erratum 161600802",
4911 		.iidr	= 0x00000004,
4912 		.mask	= 0xffffffff,
4913 		.init	= its_enable_quirk_hip07_161600802,
4914 	},
4915 #endif
4916 #ifdef CONFIG_ROCKCHIP_ERRATUM_3588001
4917 	{
4918 		.desc   = "ITS: Rockchip erratum RK3588001",
4919 		.iidr   = 0x0201743b,
4920 		.mask   = 0xffffffff,
4921 		.init   = its_enable_rk3588001,
4922 	},
4923 #endif
4924 	{
4925 		.desc   = "ITS: non-coherent attribute",
4926 		.property = "dma-noncoherent",
4927 		.init   = its_set_non_coherent,
4928 	},
4929 	{
4930 	}
4931 };
4932 
4933 static void its_enable_quirks(struct its_node *its)
4934 {
4935 	u32 iidr = readl_relaxed(its->base + GITS_IIDR);
4936 
4937 	gic_enable_quirks(iidr, its_quirks, its);
4938 
4939 	if (is_of_node(its->fwnode_handle))
4940 		gic_enable_of_quirks(to_of_node(its->fwnode_handle),
4941 				     its_quirks, its);
4942 }
4943 
4944 static int its_save_disable(void)
4945 {
4946 	struct its_node *its;
4947 	int err = 0;
4948 
4949 	raw_spin_lock(&its_lock);
4950 	list_for_each_entry(its, &its_nodes, entry) {
4951 		void __iomem *base;
4952 
4953 		base = its->base;
4954 		its->ctlr_save = readl_relaxed(base + GITS_CTLR);
4955 		err = its_force_quiescent(base);
4956 		if (err) {
4957 			pr_err("ITS@%pa: failed to quiesce: %d\n",
4958 			       &its->phys_base, err);
4959 			writel_relaxed(its->ctlr_save, base + GITS_CTLR);
4960 			goto err;
4961 		}
4962 
4963 		its->cbaser_save = gits_read_cbaser(base + GITS_CBASER);
4964 	}
4965 
4966 err:
4967 	if (err) {
4968 		list_for_each_entry_continue_reverse(its, &its_nodes, entry) {
4969 			void __iomem *base;
4970 
4971 			base = its->base;
4972 			writel_relaxed(its->ctlr_save, base + GITS_CTLR);
4973 		}
4974 	}
4975 	raw_spin_unlock(&its_lock);
4976 
4977 	return err;
4978 }
4979 
4980 static void its_restore_enable(void)
4981 {
4982 	struct its_node *its;
4983 	int ret;
4984 
4985 	raw_spin_lock(&its_lock);
4986 	list_for_each_entry(its, &its_nodes, entry) {
4987 		void __iomem *base;
4988 		int i;
4989 
4990 		base = its->base;
4991 
4992 		/*
4993 		 * Make sure that the ITS is disabled. If it fails to quiesce,
4994 		 * don't restore it since writing to CBASER or BASER<n>
4995 		 * registers is undefined according to the GIC v3 ITS
4996 		 * Specification.
4997 		 *
4998 		 * Firmware resuming with the ITS enabled is terminally broken.
4999 		 */
5000 		WARN_ON(readl_relaxed(base + GITS_CTLR) & GITS_CTLR_ENABLE);
5001 		ret = its_force_quiescent(base);
5002 		if (ret) {
5003 			pr_err("ITS@%pa: failed to quiesce on resume: %d\n",
5004 			       &its->phys_base, ret);
5005 			continue;
5006 		}
5007 
5008 		gits_write_cbaser(its->cbaser_save, base + GITS_CBASER);
5009 
5010 		/*
5011 		 * Writing CBASER resets CREADR to 0, so make CWRITER and
5012 		 * cmd_write line up with it.
5013 		 */
5014 		its->cmd_write = its->cmd_base;
5015 		gits_write_cwriter(0, base + GITS_CWRITER);
5016 
5017 		/* Restore GITS_BASER from the value cache. */
5018 		for (i = 0; i < GITS_BASER_NR_REGS; i++) {
5019 			struct its_baser *baser = &its->tables[i];
5020 
5021 			if (!(baser->val & GITS_BASER_VALID))
5022 				continue;
5023 
5024 			its_write_baser(its, baser, baser->val);
5025 		}
5026 		writel_relaxed(its->ctlr_save, base + GITS_CTLR);
5027 
5028 		/*
5029 		 * Reinit the collection if it's stored in the ITS. This is
5030 		 * indicated by the col_id being less than the HCC field.
5031 		 * CID < HCC as specified in the GIC v3 Documentation.
5032 		 */
5033 		if (its->collections[smp_processor_id()].col_id <
5034 		    GITS_TYPER_HCC(gic_read_typer(base + GITS_TYPER)))
5035 			its_cpu_init_collection(its);
5036 	}
5037 	raw_spin_unlock(&its_lock);
5038 }
5039 
5040 static struct syscore_ops its_syscore_ops = {
5041 	.suspend = its_save_disable,
5042 	.resume = its_restore_enable,
5043 };
5044 
5045 static void __init __iomem *its_map_one(struct resource *res, int *err)
5046 {
5047 	void __iomem *its_base;
5048 	u32 val;
5049 
5050 	its_base = ioremap(res->start, SZ_64K);
5051 	if (!its_base) {
5052 		pr_warn("ITS@%pa: Unable to map ITS registers\n", &res->start);
5053 		*err = -ENOMEM;
5054 		return NULL;
5055 	}
5056 
5057 	val = readl_relaxed(its_base + GITS_PIDR2) & GIC_PIDR2_ARCH_MASK;
5058 	if (val != 0x30 && val != 0x40) {
5059 		pr_warn("ITS@%pa: No ITS detected, giving up\n", &res->start);
5060 		*err = -ENODEV;
5061 		goto out_unmap;
5062 	}
5063 
5064 	*err = its_force_quiescent(its_base);
5065 	if (*err) {
5066 		pr_warn("ITS@%pa: Failed to quiesce, giving up\n", &res->start);
5067 		goto out_unmap;
5068 	}
5069 
5070 	return its_base;
5071 
5072 out_unmap:
5073 	iounmap(its_base);
5074 	return NULL;
5075 }
5076 
5077 static int its_init_domain(struct its_node *its)
5078 {
5079 	struct irq_domain *inner_domain;
5080 	struct msi_domain_info *info;
5081 
5082 	info = kzalloc(sizeof(*info), GFP_KERNEL);
5083 	if (!info)
5084 		return -ENOMEM;
5085 
5086 	info->ops = &its_msi_domain_ops;
5087 	info->data = its;
5088 
5089 	inner_domain = irq_domain_create_hierarchy(its_parent,
5090 						   its->msi_domain_flags, 0,
5091 						   its->fwnode_handle, &its_domain_ops,
5092 						   info);
5093 	if (!inner_domain) {
5094 		kfree(info);
5095 		return -ENOMEM;
5096 	}
5097 
5098 	irq_domain_update_bus_token(inner_domain, DOMAIN_BUS_NEXUS);
5099 
5100 	inner_domain->msi_parent_ops = &gic_v3_its_msi_parent_ops;
5101 	inner_domain->flags |= IRQ_DOMAIN_FLAG_MSI_PARENT;
5102 
5103 	return 0;
5104 }
5105 
5106 static int its_init_vpe_domain(void)
5107 {
5108 	struct its_node *its;
5109 	u32 devid;
5110 	int entries;
5111 
5112 	if (gic_rdists->has_direct_lpi) {
5113 		pr_info("ITS: Using DirectLPI for VPE invalidation\n");
5114 		return 0;
5115 	}
5116 
5117 	/* Any ITS will do, even if not v4 */
5118 	its = list_first_entry(&its_nodes, struct its_node, entry);
5119 
5120 	entries = roundup_pow_of_two(nr_cpu_ids);
5121 	vpe_proxy.vpes = kcalloc(entries, sizeof(*vpe_proxy.vpes),
5122 				 GFP_KERNEL);
5123 	if (!vpe_proxy.vpes)
5124 		return -ENOMEM;
5125 
5126 	/* Use the last possible DevID */
5127 	devid = GENMASK(device_ids(its) - 1, 0);
5128 	vpe_proxy.dev = its_create_device(its, devid, entries, false);
5129 	if (!vpe_proxy.dev) {
5130 		kfree(vpe_proxy.vpes);
5131 		pr_err("ITS: Can't allocate GICv4 proxy device\n");
5132 		return -ENOMEM;
5133 	}
5134 
5135 	BUG_ON(entries > vpe_proxy.dev->nr_ites);
5136 
5137 	raw_spin_lock_init(&vpe_proxy.lock);
5138 	vpe_proxy.next_victim = 0;
5139 	pr_info("ITS: Allocated DevID %x as GICv4 proxy device (%d slots)\n",
5140 		devid, vpe_proxy.dev->nr_ites);
5141 
5142 	return 0;
5143 }
5144 
5145 static int __init its_compute_its_list_map(struct its_node *its)
5146 {
5147 	int its_number;
5148 	u32 ctlr;
5149 
5150 	/*
5151 	 * This is assumed to be done early enough that we're
5152 	 * guaranteed to be single-threaded, hence no
5153 	 * locking. Should this change, we should address
5154 	 * this.
5155 	 */
5156 	its_number = find_first_zero_bit(&its_list_map, GICv4_ITS_LIST_MAX);
5157 	if (its_number >= GICv4_ITS_LIST_MAX) {
5158 		pr_err("ITS@%pa: No ITSList entry available!\n",
5159 		       &its->phys_base);
5160 		return -EINVAL;
5161 	}
5162 
5163 	ctlr = readl_relaxed(its->base + GITS_CTLR);
5164 	ctlr &= ~GITS_CTLR_ITS_NUMBER;
5165 	ctlr |= its_number << GITS_CTLR_ITS_NUMBER_SHIFT;
5166 	writel_relaxed(ctlr, its->base + GITS_CTLR);
5167 	ctlr = readl_relaxed(its->base + GITS_CTLR);
5168 	if ((ctlr & GITS_CTLR_ITS_NUMBER) != (its_number << GITS_CTLR_ITS_NUMBER_SHIFT)) {
5169 		its_number = ctlr & GITS_CTLR_ITS_NUMBER;
5170 		its_number >>= GITS_CTLR_ITS_NUMBER_SHIFT;
5171 	}
5172 
5173 	if (test_and_set_bit(its_number, &its_list_map)) {
5174 		pr_err("ITS@%pa: Duplicate ITSList entry %d\n",
5175 		       &its->phys_base, its_number);
5176 		return -EINVAL;
5177 	}
5178 
5179 	return its_number;
5180 }
5181 
5182 static int __init its_probe_one(struct its_node *its)
5183 {
5184 	u64 baser, tmp;
5185 	struct page *page;
5186 	u32 ctlr;
5187 	int err;
5188 
5189 	its_enable_quirks(its);
5190 
5191 	if (is_v4(its)) {
5192 		if (!(its->typer & GITS_TYPER_VMOVP)) {
5193 			err = its_compute_its_list_map(its);
5194 			if (err < 0)
5195 				goto out;
5196 
5197 			its->list_nr = err;
5198 
5199 			pr_info("ITS@%pa: Using ITS number %d\n",
5200 				&its->phys_base, err);
5201 		} else {
5202 			pr_info("ITS@%pa: Single VMOVP capable\n", &its->phys_base);
5203 		}
5204 
5205 		if (is_v4_1(its)) {
5206 			u32 svpet = FIELD_GET(GITS_TYPER_SVPET, its->typer);
5207 
5208 			its->sgir_base = ioremap(its->phys_base + SZ_128K, SZ_64K);
5209 			if (!its->sgir_base) {
5210 				err = -ENOMEM;
5211 				goto out;
5212 			}
5213 
5214 			its->mpidr = readl_relaxed(its->base + GITS_MPIDR);
5215 
5216 			pr_info("ITS@%pa: Using GICv4.1 mode %08x %08x\n",
5217 				&its->phys_base, its->mpidr, svpet);
5218 		}
5219 	}
5220 
5221 	page = its_alloc_pages_node(its->numa_node,
5222 				    GFP_KERNEL | __GFP_ZERO,
5223 				    get_order(ITS_CMD_QUEUE_SZ));
5224 	if (!page) {
5225 		err = -ENOMEM;
5226 		goto out_unmap_sgir;
5227 	}
5228 	its->cmd_base = (void *)page_address(page);
5229 	its->cmd_write = its->cmd_base;
5230 
5231 	err = its_alloc_tables(its);
5232 	if (err)
5233 		goto out_free_cmd;
5234 
5235 	err = its_alloc_collections(its);
5236 	if (err)
5237 		goto out_free_tables;
5238 
5239 	baser = (virt_to_phys(its->cmd_base)	|
5240 		 GITS_CBASER_RaWaWb		|
5241 		 GITS_CBASER_InnerShareable	|
5242 		 (ITS_CMD_QUEUE_SZ / SZ_4K - 1)	|
5243 		 GITS_CBASER_VALID);
5244 
5245 	gits_write_cbaser(baser, its->base + GITS_CBASER);
5246 	tmp = gits_read_cbaser(its->base + GITS_CBASER);
5247 
5248 	if (its->flags & ITS_FLAGS_FORCE_NON_SHAREABLE)
5249 		tmp &= ~GITS_CBASER_SHAREABILITY_MASK;
5250 
5251 	if ((tmp ^ baser) & GITS_CBASER_SHAREABILITY_MASK) {
5252 		if (!(tmp & GITS_CBASER_SHAREABILITY_MASK)) {
5253 			/*
5254 			 * The HW reports non-shareable, we must
5255 			 * remove the cacheability attributes as
5256 			 * well.
5257 			 */
5258 			baser &= ~(GITS_CBASER_SHAREABILITY_MASK |
5259 				   GITS_CBASER_CACHEABILITY_MASK);
5260 			baser |= GITS_CBASER_nC;
5261 			gits_write_cbaser(baser, its->base + GITS_CBASER);
5262 		}
5263 		pr_info("ITS: using cache flushing for cmd queue\n");
5264 		its->flags |= ITS_FLAGS_CMDQ_NEEDS_FLUSHING;
5265 	}
5266 
5267 	gits_write_cwriter(0, its->base + GITS_CWRITER);
5268 	ctlr = readl_relaxed(its->base + GITS_CTLR);
5269 	ctlr |= GITS_CTLR_ENABLE;
5270 	if (is_v4(its))
5271 		ctlr |= GITS_CTLR_ImDe;
5272 	writel_relaxed(ctlr, its->base + GITS_CTLR);
5273 
5274 	err = its_init_domain(its);
5275 	if (err)
5276 		goto out_free_tables;
5277 
5278 	raw_spin_lock(&its_lock);
5279 	list_add(&its->entry, &its_nodes);
5280 	raw_spin_unlock(&its_lock);
5281 
5282 	return 0;
5283 
5284 out_free_tables:
5285 	its_free_tables(its);
5286 out_free_cmd:
5287 	its_free_pages(its->cmd_base, get_order(ITS_CMD_QUEUE_SZ));
5288 out_unmap_sgir:
5289 	if (its->sgir_base)
5290 		iounmap(its->sgir_base);
5291 out:
5292 	pr_err("ITS@%pa: failed probing (%d)\n", &its->phys_base, err);
5293 	return err;
5294 }
5295 
5296 static bool gic_rdists_supports_plpis(void)
5297 {
5298 	return !!(gic_read_typer(gic_data_rdist_rd_base() + GICR_TYPER) & GICR_TYPER_PLPIS);
5299 }
5300 
5301 static int redist_disable_lpis(void)
5302 {
5303 	void __iomem *rbase = gic_data_rdist_rd_base();
5304 	u64 timeout = USEC_PER_SEC;
5305 	u64 val;
5306 
5307 	if (!gic_rdists_supports_plpis()) {
5308 		pr_info("CPU%d: LPIs not supported\n", smp_processor_id());
5309 		return -ENXIO;
5310 	}
5311 
5312 	val = readl_relaxed(rbase + GICR_CTLR);
5313 	if (!(val & GICR_CTLR_ENABLE_LPIS))
5314 		return 0;
5315 
5316 	/*
5317 	 * If coming via a CPU hotplug event, we don't need to disable
5318 	 * LPIs before trying to re-enable them. They are already
5319 	 * configured and all is well in the world.
5320 	 *
5321 	 * If running with preallocated tables, there is nothing to do.
5322 	 */
5323 	if ((gic_data_rdist()->flags & RD_LOCAL_LPI_ENABLED) ||
5324 	    (gic_rdists->flags & RDIST_FLAGS_RD_TABLES_PREALLOCATED))
5325 		return 0;
5326 
5327 	/*
5328 	 * From that point on, we only try to do some damage control.
5329 	 */
5330 	pr_warn("GICv3: CPU%d: Booted with LPIs enabled, memory probably corrupted\n",
5331 		smp_processor_id());
5332 	add_taint(TAINT_CRAP, LOCKDEP_STILL_OK);
5333 
5334 	/* Disable LPIs */
5335 	val &= ~GICR_CTLR_ENABLE_LPIS;
5336 	writel_relaxed(val, rbase + GICR_CTLR);
5337 
5338 	/* Make sure any change to GICR_CTLR is observable by the GIC */
5339 	dsb(sy);
5340 
5341 	/*
5342 	 * Software must observe RWP==0 after clearing GICR_CTLR.EnableLPIs
5343 	 * from 1 to 0 before programming GICR_PEND{PROP}BASER registers.
5344 	 * Error out if we time out waiting for RWP to clear.
5345 	 */
5346 	while (readl_relaxed(rbase + GICR_CTLR) & GICR_CTLR_RWP) {
5347 		if (!timeout) {
5348 			pr_err("CPU%d: Timeout while disabling LPIs\n",
5349 			       smp_processor_id());
5350 			return -ETIMEDOUT;
5351 		}
5352 		udelay(1);
5353 		timeout--;
5354 	}
5355 
5356 	/*
5357 	 * After it has been written to 1, it is IMPLEMENTATION
5358 	 * DEFINED whether GICR_CTLR.EnableLPI becomes RES1 or can be
5359 	 * cleared to 0. Error out if clearing the bit failed.
5360 	 */
5361 	if (readl_relaxed(rbase + GICR_CTLR) & GICR_CTLR_ENABLE_LPIS) {
5362 		pr_err("CPU%d: Failed to disable LPIs\n", smp_processor_id());
5363 		return -EBUSY;
5364 	}
5365 
5366 	return 0;
5367 }
5368 
5369 int its_cpu_init(void)
5370 {
5371 	if (!list_empty(&its_nodes)) {
5372 		int ret;
5373 
5374 		ret = redist_disable_lpis();
5375 		if (ret)
5376 			return ret;
5377 
5378 		its_cpu_init_lpis();
5379 		its_cpu_init_collections();
5380 	}
5381 
5382 	return 0;
5383 }
5384 
5385 static void rdist_memreserve_cpuhp_cleanup_workfn(struct work_struct *work)
5386 {
5387 	cpuhp_remove_state_nocalls(gic_rdists->cpuhp_memreserve_state);
5388 	gic_rdists->cpuhp_memreserve_state = CPUHP_INVALID;
5389 }
5390 
5391 static DECLARE_WORK(rdist_memreserve_cpuhp_cleanup_work,
5392 		    rdist_memreserve_cpuhp_cleanup_workfn);
5393 
5394 static int its_cpu_memreserve_lpi(unsigned int cpu)
5395 {
5396 	struct page *pend_page;
5397 	int ret = 0;
5398 
5399 	/* This gets to run exactly once per CPU */
5400 	if (gic_data_rdist()->flags & RD_LOCAL_MEMRESERVE_DONE)
5401 		return 0;
5402 
5403 	pend_page = gic_data_rdist()->pend_page;
5404 	if (WARN_ON(!pend_page)) {
5405 		ret = -ENOMEM;
5406 		goto out;
5407 	}
5408 	/*
5409 	 * If the pending table was pre-programmed, free the memory we
5410 	 * preemptively allocated. Otherwise, reserve that memory for
5411 	 * later kexecs.
5412 	 */
5413 	if (gic_data_rdist()->flags & RD_LOCAL_PENDTABLE_PREALLOCATED) {
5414 		its_free_pending_table(pend_page);
5415 		gic_data_rdist()->pend_page = NULL;
5416 	} else {
5417 		phys_addr_t paddr = page_to_phys(pend_page);
5418 		WARN_ON(gic_reserve_range(paddr, LPI_PENDBASE_SZ));
5419 	}
5420 
5421 out:
5422 	/* Last CPU being brought up gets to issue the cleanup */
5423 	if (!IS_ENABLED(CONFIG_SMP) ||
5424 	    cpumask_equal(&cpus_booted_once_mask, cpu_possible_mask))
5425 		schedule_work(&rdist_memreserve_cpuhp_cleanup_work);
5426 
5427 	gic_data_rdist()->flags |= RD_LOCAL_MEMRESERVE_DONE;
5428 	return ret;
5429 }
5430 
5431 /* Mark all the BASER registers as invalid before they get reprogrammed */
5432 static int __init its_reset_one(struct resource *res)
5433 {
5434 	void __iomem *its_base;
5435 	int err, i;
5436 
5437 	its_base = its_map_one(res, &err);
5438 	if (!its_base)
5439 		return err;
5440 
5441 	for (i = 0; i < GITS_BASER_NR_REGS; i++)
5442 		gits_write_baser(0, its_base + GITS_BASER + (i << 3));
5443 
5444 	iounmap(its_base);
5445 	return 0;
5446 }
5447 
5448 static const struct of_device_id its_device_id[] = {
5449 	{	.compatible	= "arm,gic-v3-its",	},
5450 	{},
5451 };
5452 
5453 static struct its_node __init *its_node_init(struct resource *res,
5454 					     struct fwnode_handle *handle, int numa_node)
5455 {
5456 	void __iomem *its_base;
5457 	struct its_node *its;
5458 	int err;
5459 
5460 	its_base = its_map_one(res, &err);
5461 	if (!its_base)
5462 		return NULL;
5463 
5464 	pr_info("ITS %pR\n", res);
5465 
5466 	its = kzalloc(sizeof(*its), GFP_KERNEL);
5467 	if (!its)
5468 		goto out_unmap;
5469 
5470 	raw_spin_lock_init(&its->lock);
5471 	mutex_init(&its->dev_alloc_lock);
5472 	INIT_LIST_HEAD(&its->entry);
5473 	INIT_LIST_HEAD(&its->its_device_list);
5474 
5475 	its->typer = gic_read_typer(its_base + GITS_TYPER);
5476 	its->base = its_base;
5477 	its->phys_base = res->start;
5478 	its->get_msi_base = its_irq_get_msi_base;
5479 	its->msi_domain_flags = IRQ_DOMAIN_FLAG_ISOLATED_MSI;
5480 
5481 	its->numa_node = numa_node;
5482 	its->fwnode_handle = handle;
5483 
5484 	return its;
5485 
5486 out_unmap:
5487 	iounmap(its_base);
5488 	return NULL;
5489 }
5490 
5491 static void its_node_destroy(struct its_node *its)
5492 {
5493 	iounmap(its->base);
5494 	kfree(its);
5495 }
5496 
5497 static int __init its_of_probe(struct device_node *node)
5498 {
5499 	struct device_node *np;
5500 	struct resource res;
5501 	int err;
5502 
5503 	/*
5504 	 * Make sure *all* the ITS are reset before we probe any, as
5505 	 * they may be sharing memory. If any of the ITS fails to
5506 	 * reset, don't even try to go any further, as this could
5507 	 * result in something even worse.
5508 	 */
5509 	for (np = of_find_matching_node(node, its_device_id); np;
5510 	     np = of_find_matching_node(np, its_device_id)) {
5511 		if (!of_device_is_available(np) ||
5512 		    !of_property_read_bool(np, "msi-controller") ||
5513 		    of_address_to_resource(np, 0, &res))
5514 			continue;
5515 
5516 		err = its_reset_one(&res);
5517 		if (err)
5518 			return err;
5519 	}
5520 
5521 	for (np = of_find_matching_node(node, its_device_id); np;
5522 	     np = of_find_matching_node(np, its_device_id)) {
5523 		struct its_node *its;
5524 
5525 		if (!of_device_is_available(np))
5526 			continue;
5527 		if (!of_property_read_bool(np, "msi-controller")) {
5528 			pr_warn("%pOF: no msi-controller property, ITS ignored\n",
5529 				np);
5530 			continue;
5531 		}
5532 
5533 		if (of_address_to_resource(np, 0, &res)) {
5534 			pr_warn("%pOF: no regs?\n", np);
5535 			continue;
5536 		}
5537 
5538 
5539 		its = its_node_init(&res, &np->fwnode, of_node_to_nid(np));
5540 		if (!its)
5541 			return -ENOMEM;
5542 
5543 		err = its_probe_one(its);
5544 		if (err)  {
5545 			its_node_destroy(its);
5546 			return err;
5547 		}
5548 	}
5549 	return 0;
5550 }
5551 
5552 #ifdef CONFIG_ACPI
5553 
5554 #define ACPI_GICV3_ITS_MEM_SIZE (SZ_128K)
5555 
5556 #ifdef CONFIG_ACPI_NUMA
5557 struct its_srat_map {
5558 	/* numa node id */
5559 	u32	numa_node;
5560 	/* GIC ITS ID */
5561 	u32	its_id;
5562 };
5563 
5564 static struct its_srat_map *its_srat_maps __initdata;
5565 static int its_in_srat __initdata;
5566 
5567 static int __init acpi_get_its_numa_node(u32 its_id)
5568 {
5569 	int i;
5570 
5571 	for (i = 0; i < its_in_srat; i++) {
5572 		if (its_id == its_srat_maps[i].its_id)
5573 			return its_srat_maps[i].numa_node;
5574 	}
5575 	return NUMA_NO_NODE;
5576 }
5577 
5578 static int __init gic_acpi_match_srat_its(union acpi_subtable_headers *header,
5579 					  const unsigned long end)
5580 {
5581 	return 0;
5582 }
5583 
5584 static int __init gic_acpi_parse_srat_its(union acpi_subtable_headers *header,
5585 			 const unsigned long end)
5586 {
5587 	int node;
5588 	struct acpi_srat_gic_its_affinity *its_affinity;
5589 
5590 	its_affinity = (struct acpi_srat_gic_its_affinity *)header;
5591 	if (!its_affinity)
5592 		return -EINVAL;
5593 
5594 	if (its_affinity->header.length < sizeof(*its_affinity)) {
5595 		pr_err("SRAT: Invalid header length %d in ITS affinity\n",
5596 			its_affinity->header.length);
5597 		return -EINVAL;
5598 	}
5599 
5600 	/*
5601 	 * Note that in theory a new proximity node could be created by this
5602 	 * entry as it is an SRAT resource allocation structure.
5603 	 * We do not currently support doing so.
5604 	 */
5605 	node = pxm_to_node(its_affinity->proximity_domain);
5606 
5607 	if (node == NUMA_NO_NODE || node >= MAX_NUMNODES) {
5608 		pr_err("SRAT: Invalid NUMA node %d in ITS affinity\n", node);
5609 		return 0;
5610 	}
5611 
5612 	its_srat_maps[its_in_srat].numa_node = node;
5613 	its_srat_maps[its_in_srat].its_id = its_affinity->its_id;
5614 	its_in_srat++;
5615 	pr_info("SRAT: PXM %d -> ITS %d -> Node %d\n",
5616 		its_affinity->proximity_domain, its_affinity->its_id, node);
5617 
5618 	return 0;
5619 }
5620 
5621 static void __init acpi_table_parse_srat_its(void)
5622 {
5623 	int count;
5624 
5625 	count = acpi_table_parse_entries(ACPI_SIG_SRAT,
5626 			sizeof(struct acpi_table_srat),
5627 			ACPI_SRAT_TYPE_GIC_ITS_AFFINITY,
5628 			gic_acpi_match_srat_its, 0);
5629 	if (count <= 0)
5630 		return;
5631 
5632 	its_srat_maps = kmalloc_array(count, sizeof(struct its_srat_map),
5633 				      GFP_KERNEL);
5634 	if (!its_srat_maps)
5635 		return;
5636 
5637 	acpi_table_parse_entries(ACPI_SIG_SRAT,
5638 			sizeof(struct acpi_table_srat),
5639 			ACPI_SRAT_TYPE_GIC_ITS_AFFINITY,
5640 			gic_acpi_parse_srat_its, 0);
5641 }
5642 
5643 /* free the its_srat_maps after ITS probing */
5644 static void __init acpi_its_srat_maps_free(void)
5645 {
5646 	kfree(its_srat_maps);
5647 }
5648 #else
5649 static void __init acpi_table_parse_srat_its(void)	{ }
5650 static int __init acpi_get_its_numa_node(u32 its_id) { return NUMA_NO_NODE; }
5651 static void __init acpi_its_srat_maps_free(void) { }
5652 #endif
5653 
5654 static int __init gic_acpi_parse_madt_its(union acpi_subtable_headers *header,
5655 					  const unsigned long end)
5656 {
5657 	struct acpi_madt_generic_translator *its_entry;
5658 	struct fwnode_handle *dom_handle;
5659 	struct its_node *its;
5660 	struct resource res;
5661 	int err;
5662 
5663 	its_entry = (struct acpi_madt_generic_translator *)header;
5664 	memset(&res, 0, sizeof(res));
5665 	res.start = its_entry->base_address;
5666 	res.end = its_entry->base_address + ACPI_GICV3_ITS_MEM_SIZE - 1;
5667 	res.flags = IORESOURCE_MEM;
5668 
5669 	dom_handle = irq_domain_alloc_fwnode(&res.start);
5670 	if (!dom_handle) {
5671 		pr_err("ITS@%pa: Unable to allocate GICv3 ITS domain token\n",
5672 		       &res.start);
5673 		return -ENOMEM;
5674 	}
5675 
5676 	err = iort_register_domain_token(its_entry->translation_id, res.start,
5677 					 dom_handle);
5678 	if (err) {
5679 		pr_err("ITS@%pa: Unable to register GICv3 ITS domain token (ITS ID %d) to IORT\n",
5680 		       &res.start, its_entry->translation_id);
5681 		goto dom_err;
5682 	}
5683 
5684 	its = its_node_init(&res, dom_handle,
5685 			    acpi_get_its_numa_node(its_entry->translation_id));
5686 	if (!its) {
5687 		err = -ENOMEM;
5688 		goto node_err;
5689 	}
5690 
5691 	if (acpi_get_madt_revision() >= 7 &&
5692 	    (its_entry->flags & ACPI_MADT_ITS_NON_COHERENT))
5693 		its->flags |= ITS_FLAGS_FORCE_NON_SHAREABLE;
5694 
5695 	err = its_probe_one(its);
5696 	if (!err)
5697 		return 0;
5698 
5699 node_err:
5700 	iort_deregister_domain_token(its_entry->translation_id);
5701 dom_err:
5702 	irq_domain_free_fwnode(dom_handle);
5703 	return err;
5704 }
5705 
5706 static int __init its_acpi_reset(union acpi_subtable_headers *header,
5707 				 const unsigned long end)
5708 {
5709 	struct acpi_madt_generic_translator *its_entry;
5710 	struct resource res;
5711 
5712 	its_entry = (struct acpi_madt_generic_translator *)header;
5713 	res = (struct resource) {
5714 		.start	= its_entry->base_address,
5715 		.end	= its_entry->base_address + ACPI_GICV3_ITS_MEM_SIZE - 1,
5716 		.flags	= IORESOURCE_MEM,
5717 	};
5718 
5719 	return its_reset_one(&res);
5720 }
5721 
5722 static void __init its_acpi_probe(void)
5723 {
5724 	acpi_table_parse_srat_its();
5725 	/*
5726 	 * Make sure *all* the ITS are reset before we probe any, as
5727 	 * they may be sharing memory. If any of the ITS fails to
5728 	 * reset, don't even try to go any further, as this could
5729 	 * result in something even worse.
5730 	 */
5731 	if (acpi_table_parse_madt(ACPI_MADT_TYPE_GENERIC_TRANSLATOR,
5732 				  its_acpi_reset, 0) > 0)
5733 		acpi_table_parse_madt(ACPI_MADT_TYPE_GENERIC_TRANSLATOR,
5734 				      gic_acpi_parse_madt_its, 0);
5735 	acpi_its_srat_maps_free();
5736 }
5737 #else
5738 static void __init its_acpi_probe(void) { }
5739 #endif
5740 
5741 int __init its_lpi_memreserve_init(void)
5742 {
5743 	int state;
5744 
5745 	if (!efi_enabled(EFI_CONFIG_TABLES))
5746 		return 0;
5747 
5748 	if (list_empty(&its_nodes))
5749 		return 0;
5750 
5751 	gic_rdists->cpuhp_memreserve_state = CPUHP_INVALID;
5752 	state = cpuhp_setup_state(CPUHP_AP_ONLINE_DYN,
5753 				  "irqchip/arm/gicv3/memreserve:online",
5754 				  its_cpu_memreserve_lpi,
5755 				  NULL);
5756 	if (state < 0)
5757 		return state;
5758 
5759 	gic_rdists->cpuhp_memreserve_state = state;
5760 
5761 	return 0;
5762 }
5763 
5764 int __init its_init(struct fwnode_handle *handle, struct rdists *rdists,
5765 		    struct irq_domain *parent_domain, u8 irq_prio)
5766 {
5767 	struct device_node *of_node;
5768 	struct its_node *its;
5769 	bool has_v4 = false;
5770 	bool has_v4_1 = false;
5771 	int err;
5772 
5773 	itt_pool = gen_pool_create(get_order(ITS_ITT_ALIGN), -1);
5774 	if (!itt_pool)
5775 		return -ENOMEM;
5776 
5777 	gic_rdists = rdists;
5778 
5779 	lpi_prop_prio = irq_prio;
5780 	its_parent = parent_domain;
5781 	of_node = to_of_node(handle);
5782 	if (of_node)
5783 		its_of_probe(of_node);
5784 	else
5785 		its_acpi_probe();
5786 
5787 	if (list_empty(&its_nodes)) {
5788 		pr_warn("ITS: No ITS available, not enabling LPIs\n");
5789 		return -ENXIO;
5790 	}
5791 
5792 	err = allocate_lpi_tables();
5793 	if (err)
5794 		return err;
5795 
5796 	list_for_each_entry(its, &its_nodes, entry) {
5797 		has_v4 |= is_v4(its);
5798 		has_v4_1 |= is_v4_1(its);
5799 	}
5800 
5801 	/* Don't bother with inconsistent systems */
5802 	if (WARN_ON(!has_v4_1 && rdists->has_rvpeid))
5803 		rdists->has_rvpeid = false;
5804 
5805 	if (has_v4 & rdists->has_vlpis) {
5806 		const struct irq_domain_ops *sgi_ops;
5807 
5808 		if (has_v4_1)
5809 			sgi_ops = &its_sgi_domain_ops;
5810 		else
5811 			sgi_ops = NULL;
5812 
5813 		if (its_init_vpe_domain() ||
5814 		    its_init_v4(parent_domain, &its_vpe_domain_ops, sgi_ops)) {
5815 			rdists->has_vlpis = false;
5816 			pr_err("ITS: Disabling GICv4 support\n");
5817 		}
5818 	}
5819 
5820 	register_syscore_ops(&its_syscore_ops);
5821 
5822 	return 0;
5823 }
5824