1 /*
2  * Copyright (C) 2013, 2014 ARM Limited, All Rights Reserved.
3  * Author: Marc Zyngier <marc.zyngier@arm.com>
4  *
5  * This program is free software; you can redistribute it and/or modify
6  * it under the terms of the GNU General Public License version 2 as
7  * published by the Free Software Foundation.
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
16  */
17 
18 #include <linux/acpi.h>
19 #include <linux/bitmap.h>
20 #include <linux/cpu.h>
21 #include <linux/delay.h>
22 #include <linux/dma-iommu.h>
23 #include <linux/interrupt.h>
24 #include <linux/irqdomain.h>
25 #include <linux/acpi_iort.h>
26 #include <linux/log2.h>
27 #include <linux/mm.h>
28 #include <linux/msi.h>
29 #include <linux/of.h>
30 #include <linux/of_address.h>
31 #include <linux/of_irq.h>
32 #include <linux/of_pci.h>
33 #include <linux/of_platform.h>
34 #include <linux/percpu.h>
35 #include <linux/slab.h>
36 
37 #include <linux/irqchip.h>
38 #include <linux/irqchip/arm-gic-v3.h>
39 
40 #include <asm/cacheflush.h>
41 #include <asm/cputype.h>
42 #include <asm/exception.h>
43 
44 #include "irq-gic-common.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 
50 #define RDIST_FLAGS_PROPBASE_NEEDS_FLUSHING	(1 << 0)
51 
52 /*
53  * Collection structure - just an ID, and a redistributor address to
54  * ping. We use one per CPU as a bag of interrupts assigned to this
55  * CPU.
56  */
57 struct its_collection {
58 	u64			target_address;
59 	u16			col_id;
60 };
61 
62 /*
63  * The ITS_BASER structure - contains memory information, cached
64  * value of BASER register configuration and ITS page size.
65  */
66 struct its_baser {
67 	void		*base;
68 	u64		val;
69 	u32		order;
70 	u32		psz;
71 };
72 
73 /*
74  * The ITS structure - contains most of the infrastructure, with the
75  * top-level MSI domain, the command queue, the collections, and the
76  * list of devices writing to it.
77  */
78 struct its_node {
79 	raw_spinlock_t		lock;
80 	struct list_head	entry;
81 	void __iomem		*base;
82 	phys_addr_t		phys_base;
83 	struct its_cmd_block	*cmd_base;
84 	struct its_cmd_block	*cmd_write;
85 	struct its_baser	tables[GITS_BASER_NR_REGS];
86 	struct its_collection	*collections;
87 	struct list_head	its_device_list;
88 	u64			flags;
89 	u32			ite_size;
90 	u32			device_ids;
91 	int			numa_node;
92 };
93 
94 #define ITS_ITT_ALIGN		SZ_256
95 
96 /* Convert page order to size in bytes */
97 #define PAGE_ORDER_TO_SIZE(o)	(PAGE_SIZE << (o))
98 
99 struct event_lpi_map {
100 	unsigned long		*lpi_map;
101 	u16			*col_map;
102 	irq_hw_number_t		lpi_base;
103 	int			nr_lpis;
104 };
105 
106 /*
107  * The ITS view of a device - belongs to an ITS, a collection, owns an
108  * interrupt translation table, and a list of interrupts.
109  */
110 struct its_device {
111 	struct list_head	entry;
112 	struct its_node		*its;
113 	struct event_lpi_map	event_map;
114 	void			*itt;
115 	u32			nr_ites;
116 	u32			device_id;
117 };
118 
119 static LIST_HEAD(its_nodes);
120 static DEFINE_SPINLOCK(its_lock);
121 static struct rdists *gic_rdists;
122 static struct irq_domain *its_parent;
123 
124 #define gic_data_rdist()		(raw_cpu_ptr(gic_rdists->rdist))
125 #define gic_data_rdist_rd_base()	(gic_data_rdist()->rd_base)
126 
127 static struct its_collection *dev_event_to_col(struct its_device *its_dev,
128 					       u32 event)
129 {
130 	struct its_node *its = its_dev->its;
131 
132 	return its->collections + its_dev->event_map.col_map[event];
133 }
134 
135 /*
136  * ITS command descriptors - parameters to be encoded in a command
137  * block.
138  */
139 struct its_cmd_desc {
140 	union {
141 		struct {
142 			struct its_device *dev;
143 			u32 event_id;
144 		} its_inv_cmd;
145 
146 		struct {
147 			struct its_device *dev;
148 			u32 event_id;
149 		} its_int_cmd;
150 
151 		struct {
152 			struct its_device *dev;
153 			int valid;
154 		} its_mapd_cmd;
155 
156 		struct {
157 			struct its_collection *col;
158 			int valid;
159 		} its_mapc_cmd;
160 
161 		struct {
162 			struct its_device *dev;
163 			u32 phys_id;
164 			u32 event_id;
165 		} its_mapvi_cmd;
166 
167 		struct {
168 			struct its_device *dev;
169 			struct its_collection *col;
170 			u32 event_id;
171 		} its_movi_cmd;
172 
173 		struct {
174 			struct its_device *dev;
175 			u32 event_id;
176 		} its_discard_cmd;
177 
178 		struct {
179 			struct its_collection *col;
180 		} its_invall_cmd;
181 	};
182 };
183 
184 /*
185  * The ITS command block, which is what the ITS actually parses.
186  */
187 struct its_cmd_block {
188 	u64	raw_cmd[4];
189 };
190 
191 #define ITS_CMD_QUEUE_SZ		SZ_64K
192 #define ITS_CMD_QUEUE_NR_ENTRIES	(ITS_CMD_QUEUE_SZ / sizeof(struct its_cmd_block))
193 
194 typedef struct its_collection *(*its_cmd_builder_t)(struct its_cmd_block *,
195 						    struct its_cmd_desc *);
196 
197 static void its_encode_cmd(struct its_cmd_block *cmd, u8 cmd_nr)
198 {
199 	cmd->raw_cmd[0] &= ~0xffUL;
200 	cmd->raw_cmd[0] |= cmd_nr;
201 }
202 
203 static void its_encode_devid(struct its_cmd_block *cmd, u32 devid)
204 {
205 	cmd->raw_cmd[0] &= BIT_ULL(32) - 1;
206 	cmd->raw_cmd[0] |= ((u64)devid) << 32;
207 }
208 
209 static void its_encode_event_id(struct its_cmd_block *cmd, u32 id)
210 {
211 	cmd->raw_cmd[1] &= ~0xffffffffUL;
212 	cmd->raw_cmd[1] |= id;
213 }
214 
215 static void its_encode_phys_id(struct its_cmd_block *cmd, u32 phys_id)
216 {
217 	cmd->raw_cmd[1] &= 0xffffffffUL;
218 	cmd->raw_cmd[1] |= ((u64)phys_id) << 32;
219 }
220 
221 static void its_encode_size(struct its_cmd_block *cmd, u8 size)
222 {
223 	cmd->raw_cmd[1] &= ~0x1fUL;
224 	cmd->raw_cmd[1] |= size & 0x1f;
225 }
226 
227 static void its_encode_itt(struct its_cmd_block *cmd, u64 itt_addr)
228 {
229 	cmd->raw_cmd[2] &= ~0xffffffffffffUL;
230 	cmd->raw_cmd[2] |= itt_addr & 0xffffffffff00UL;
231 }
232 
233 static void its_encode_valid(struct its_cmd_block *cmd, int valid)
234 {
235 	cmd->raw_cmd[2] &= ~(1UL << 63);
236 	cmd->raw_cmd[2] |= ((u64)!!valid) << 63;
237 }
238 
239 static void its_encode_target(struct its_cmd_block *cmd, u64 target_addr)
240 {
241 	cmd->raw_cmd[2] &= ~(0xffffffffUL << 16);
242 	cmd->raw_cmd[2] |= (target_addr & (0xffffffffUL << 16));
243 }
244 
245 static void its_encode_collection(struct its_cmd_block *cmd, u16 col)
246 {
247 	cmd->raw_cmd[2] &= ~0xffffUL;
248 	cmd->raw_cmd[2] |= col;
249 }
250 
251 static inline void its_fixup_cmd(struct its_cmd_block *cmd)
252 {
253 	/* Let's fixup BE commands */
254 	cmd->raw_cmd[0] = cpu_to_le64(cmd->raw_cmd[0]);
255 	cmd->raw_cmd[1] = cpu_to_le64(cmd->raw_cmd[1]);
256 	cmd->raw_cmd[2] = cpu_to_le64(cmd->raw_cmd[2]);
257 	cmd->raw_cmd[3] = cpu_to_le64(cmd->raw_cmd[3]);
258 }
259 
260 static struct its_collection *its_build_mapd_cmd(struct its_cmd_block *cmd,
261 						 struct its_cmd_desc *desc)
262 {
263 	unsigned long itt_addr;
264 	u8 size = ilog2(desc->its_mapd_cmd.dev->nr_ites);
265 
266 	itt_addr = virt_to_phys(desc->its_mapd_cmd.dev->itt);
267 	itt_addr = ALIGN(itt_addr, ITS_ITT_ALIGN);
268 
269 	its_encode_cmd(cmd, GITS_CMD_MAPD);
270 	its_encode_devid(cmd, desc->its_mapd_cmd.dev->device_id);
271 	its_encode_size(cmd, size - 1);
272 	its_encode_itt(cmd, itt_addr);
273 	its_encode_valid(cmd, desc->its_mapd_cmd.valid);
274 
275 	its_fixup_cmd(cmd);
276 
277 	return NULL;
278 }
279 
280 static struct its_collection *its_build_mapc_cmd(struct its_cmd_block *cmd,
281 						 struct its_cmd_desc *desc)
282 {
283 	its_encode_cmd(cmd, GITS_CMD_MAPC);
284 	its_encode_collection(cmd, desc->its_mapc_cmd.col->col_id);
285 	its_encode_target(cmd, desc->its_mapc_cmd.col->target_address);
286 	its_encode_valid(cmd, desc->its_mapc_cmd.valid);
287 
288 	its_fixup_cmd(cmd);
289 
290 	return desc->its_mapc_cmd.col;
291 }
292 
293 static struct its_collection *its_build_mapvi_cmd(struct its_cmd_block *cmd,
294 						  struct its_cmd_desc *desc)
295 {
296 	struct its_collection *col;
297 
298 	col = dev_event_to_col(desc->its_mapvi_cmd.dev,
299 			       desc->its_mapvi_cmd.event_id);
300 
301 	its_encode_cmd(cmd, GITS_CMD_MAPVI);
302 	its_encode_devid(cmd, desc->its_mapvi_cmd.dev->device_id);
303 	its_encode_event_id(cmd, desc->its_mapvi_cmd.event_id);
304 	its_encode_phys_id(cmd, desc->its_mapvi_cmd.phys_id);
305 	its_encode_collection(cmd, col->col_id);
306 
307 	its_fixup_cmd(cmd);
308 
309 	return col;
310 }
311 
312 static struct its_collection *its_build_movi_cmd(struct its_cmd_block *cmd,
313 						 struct its_cmd_desc *desc)
314 {
315 	struct its_collection *col;
316 
317 	col = dev_event_to_col(desc->its_movi_cmd.dev,
318 			       desc->its_movi_cmd.event_id);
319 
320 	its_encode_cmd(cmd, GITS_CMD_MOVI);
321 	its_encode_devid(cmd, desc->its_movi_cmd.dev->device_id);
322 	its_encode_event_id(cmd, desc->its_movi_cmd.event_id);
323 	its_encode_collection(cmd, desc->its_movi_cmd.col->col_id);
324 
325 	its_fixup_cmd(cmd);
326 
327 	return col;
328 }
329 
330 static struct its_collection *its_build_discard_cmd(struct its_cmd_block *cmd,
331 						    struct its_cmd_desc *desc)
332 {
333 	struct its_collection *col;
334 
335 	col = dev_event_to_col(desc->its_discard_cmd.dev,
336 			       desc->its_discard_cmd.event_id);
337 
338 	its_encode_cmd(cmd, GITS_CMD_DISCARD);
339 	its_encode_devid(cmd, desc->its_discard_cmd.dev->device_id);
340 	its_encode_event_id(cmd, desc->its_discard_cmd.event_id);
341 
342 	its_fixup_cmd(cmd);
343 
344 	return col;
345 }
346 
347 static struct its_collection *its_build_inv_cmd(struct its_cmd_block *cmd,
348 						struct its_cmd_desc *desc)
349 {
350 	struct its_collection *col;
351 
352 	col = dev_event_to_col(desc->its_inv_cmd.dev,
353 			       desc->its_inv_cmd.event_id);
354 
355 	its_encode_cmd(cmd, GITS_CMD_INV);
356 	its_encode_devid(cmd, desc->its_inv_cmd.dev->device_id);
357 	its_encode_event_id(cmd, desc->its_inv_cmd.event_id);
358 
359 	its_fixup_cmd(cmd);
360 
361 	return col;
362 }
363 
364 static struct its_collection *its_build_invall_cmd(struct its_cmd_block *cmd,
365 						   struct its_cmd_desc *desc)
366 {
367 	its_encode_cmd(cmd, GITS_CMD_INVALL);
368 	its_encode_collection(cmd, desc->its_mapc_cmd.col->col_id);
369 
370 	its_fixup_cmd(cmd);
371 
372 	return NULL;
373 }
374 
375 static u64 its_cmd_ptr_to_offset(struct its_node *its,
376 				 struct its_cmd_block *ptr)
377 {
378 	return (ptr - its->cmd_base) * sizeof(*ptr);
379 }
380 
381 static int its_queue_full(struct its_node *its)
382 {
383 	int widx;
384 	int ridx;
385 
386 	widx = its->cmd_write - its->cmd_base;
387 	ridx = readl_relaxed(its->base + GITS_CREADR) / sizeof(struct its_cmd_block);
388 
389 	/* This is incredibly unlikely to happen, unless the ITS locks up. */
390 	if (((widx + 1) % ITS_CMD_QUEUE_NR_ENTRIES) == ridx)
391 		return 1;
392 
393 	return 0;
394 }
395 
396 static struct its_cmd_block *its_allocate_entry(struct its_node *its)
397 {
398 	struct its_cmd_block *cmd;
399 	u32 count = 1000000;	/* 1s! */
400 
401 	while (its_queue_full(its)) {
402 		count--;
403 		if (!count) {
404 			pr_err_ratelimited("ITS queue not draining\n");
405 			return NULL;
406 		}
407 		cpu_relax();
408 		udelay(1);
409 	}
410 
411 	cmd = its->cmd_write++;
412 
413 	/* Handle queue wrapping */
414 	if (its->cmd_write == (its->cmd_base + ITS_CMD_QUEUE_NR_ENTRIES))
415 		its->cmd_write = its->cmd_base;
416 
417 	return cmd;
418 }
419 
420 static struct its_cmd_block *its_post_commands(struct its_node *its)
421 {
422 	u64 wr = its_cmd_ptr_to_offset(its, its->cmd_write);
423 
424 	writel_relaxed(wr, its->base + GITS_CWRITER);
425 
426 	return its->cmd_write;
427 }
428 
429 static void its_flush_cmd(struct its_node *its, struct its_cmd_block *cmd)
430 {
431 	/*
432 	 * Make sure the commands written to memory are observable by
433 	 * the ITS.
434 	 */
435 	if (its->flags & ITS_FLAGS_CMDQ_NEEDS_FLUSHING)
436 		__flush_dcache_area(cmd, sizeof(*cmd));
437 	else
438 		dsb(ishst);
439 }
440 
441 static void its_wait_for_range_completion(struct its_node *its,
442 					  struct its_cmd_block *from,
443 					  struct its_cmd_block *to)
444 {
445 	u64 rd_idx, from_idx, to_idx;
446 	u32 count = 1000000;	/* 1s! */
447 
448 	from_idx = its_cmd_ptr_to_offset(its, from);
449 	to_idx = its_cmd_ptr_to_offset(its, to);
450 
451 	while (1) {
452 		rd_idx = readl_relaxed(its->base + GITS_CREADR);
453 		if (rd_idx >= to_idx || rd_idx < from_idx)
454 			break;
455 
456 		count--;
457 		if (!count) {
458 			pr_err_ratelimited("ITS queue timeout\n");
459 			return;
460 		}
461 		cpu_relax();
462 		udelay(1);
463 	}
464 }
465 
466 static void its_send_single_command(struct its_node *its,
467 				    its_cmd_builder_t builder,
468 				    struct its_cmd_desc *desc)
469 {
470 	struct its_cmd_block *cmd, *sync_cmd, *next_cmd;
471 	struct its_collection *sync_col;
472 	unsigned long flags;
473 
474 	raw_spin_lock_irqsave(&its->lock, flags);
475 
476 	cmd = its_allocate_entry(its);
477 	if (!cmd) {		/* We're soooooo screewed... */
478 		pr_err_ratelimited("ITS can't allocate, dropping command\n");
479 		raw_spin_unlock_irqrestore(&its->lock, flags);
480 		return;
481 	}
482 	sync_col = builder(cmd, desc);
483 	its_flush_cmd(its, cmd);
484 
485 	if (sync_col) {
486 		sync_cmd = its_allocate_entry(its);
487 		if (!sync_cmd) {
488 			pr_err_ratelimited("ITS can't SYNC, skipping\n");
489 			goto post;
490 		}
491 		its_encode_cmd(sync_cmd, GITS_CMD_SYNC);
492 		its_encode_target(sync_cmd, sync_col->target_address);
493 		its_fixup_cmd(sync_cmd);
494 		its_flush_cmd(its, sync_cmd);
495 	}
496 
497 post:
498 	next_cmd = its_post_commands(its);
499 	raw_spin_unlock_irqrestore(&its->lock, flags);
500 
501 	its_wait_for_range_completion(its, cmd, next_cmd);
502 }
503 
504 static void its_send_inv(struct its_device *dev, u32 event_id)
505 {
506 	struct its_cmd_desc desc;
507 
508 	desc.its_inv_cmd.dev = dev;
509 	desc.its_inv_cmd.event_id = event_id;
510 
511 	its_send_single_command(dev->its, its_build_inv_cmd, &desc);
512 }
513 
514 static void its_send_mapd(struct its_device *dev, int valid)
515 {
516 	struct its_cmd_desc desc;
517 
518 	desc.its_mapd_cmd.dev = dev;
519 	desc.its_mapd_cmd.valid = !!valid;
520 
521 	its_send_single_command(dev->its, its_build_mapd_cmd, &desc);
522 }
523 
524 static void its_send_mapc(struct its_node *its, struct its_collection *col,
525 			  int valid)
526 {
527 	struct its_cmd_desc desc;
528 
529 	desc.its_mapc_cmd.col = col;
530 	desc.its_mapc_cmd.valid = !!valid;
531 
532 	its_send_single_command(its, its_build_mapc_cmd, &desc);
533 }
534 
535 static void its_send_mapvi(struct its_device *dev, u32 irq_id, u32 id)
536 {
537 	struct its_cmd_desc desc;
538 
539 	desc.its_mapvi_cmd.dev = dev;
540 	desc.its_mapvi_cmd.phys_id = irq_id;
541 	desc.its_mapvi_cmd.event_id = id;
542 
543 	its_send_single_command(dev->its, its_build_mapvi_cmd, &desc);
544 }
545 
546 static void its_send_movi(struct its_device *dev,
547 			  struct its_collection *col, u32 id)
548 {
549 	struct its_cmd_desc desc;
550 
551 	desc.its_movi_cmd.dev = dev;
552 	desc.its_movi_cmd.col = col;
553 	desc.its_movi_cmd.event_id = id;
554 
555 	its_send_single_command(dev->its, its_build_movi_cmd, &desc);
556 }
557 
558 static void its_send_discard(struct its_device *dev, u32 id)
559 {
560 	struct its_cmd_desc desc;
561 
562 	desc.its_discard_cmd.dev = dev;
563 	desc.its_discard_cmd.event_id = id;
564 
565 	its_send_single_command(dev->its, its_build_discard_cmd, &desc);
566 }
567 
568 static void its_send_invall(struct its_node *its, struct its_collection *col)
569 {
570 	struct its_cmd_desc desc;
571 
572 	desc.its_invall_cmd.col = col;
573 
574 	its_send_single_command(its, its_build_invall_cmd, &desc);
575 }
576 
577 /*
578  * irqchip functions - assumes MSI, mostly.
579  */
580 
581 static inline u32 its_get_event_id(struct irq_data *d)
582 {
583 	struct its_device *its_dev = irq_data_get_irq_chip_data(d);
584 	return d->hwirq - its_dev->event_map.lpi_base;
585 }
586 
587 static void lpi_set_config(struct irq_data *d, bool enable)
588 {
589 	struct its_device *its_dev = irq_data_get_irq_chip_data(d);
590 	irq_hw_number_t hwirq = d->hwirq;
591 	u32 id = its_get_event_id(d);
592 	u8 *cfg = page_address(gic_rdists->prop_page) + hwirq - 8192;
593 
594 	if (enable)
595 		*cfg |= LPI_PROP_ENABLED;
596 	else
597 		*cfg &= ~LPI_PROP_ENABLED;
598 
599 	/*
600 	 * Make the above write visible to the redistributors.
601 	 * And yes, we're flushing exactly: One. Single. Byte.
602 	 * Humpf...
603 	 */
604 	if (gic_rdists->flags & RDIST_FLAGS_PROPBASE_NEEDS_FLUSHING)
605 		__flush_dcache_area(cfg, sizeof(*cfg));
606 	else
607 		dsb(ishst);
608 	its_send_inv(its_dev, id);
609 }
610 
611 static void its_mask_irq(struct irq_data *d)
612 {
613 	lpi_set_config(d, false);
614 }
615 
616 static void its_unmask_irq(struct irq_data *d)
617 {
618 	lpi_set_config(d, true);
619 }
620 
621 static int its_set_affinity(struct irq_data *d, const struct cpumask *mask_val,
622 			    bool force)
623 {
624 	unsigned int cpu;
625 	const struct cpumask *cpu_mask = cpu_online_mask;
626 	struct its_device *its_dev = irq_data_get_irq_chip_data(d);
627 	struct its_collection *target_col;
628 	u32 id = its_get_event_id(d);
629 
630        /* lpi cannot be routed to a redistributor that is on a foreign node */
631 	if (its_dev->its->flags & ITS_FLAGS_WORKAROUND_CAVIUM_23144) {
632 		if (its_dev->its->numa_node >= 0) {
633 			cpu_mask = cpumask_of_node(its_dev->its->numa_node);
634 			if (!cpumask_intersects(mask_val, cpu_mask))
635 				return -EINVAL;
636 		}
637 	}
638 
639 	cpu = cpumask_any_and(mask_val, cpu_mask);
640 
641 	if (cpu >= nr_cpu_ids)
642 		return -EINVAL;
643 
644 	target_col = &its_dev->its->collections[cpu];
645 	its_send_movi(its_dev, target_col, id);
646 	its_dev->event_map.col_map[id] = cpu;
647 
648 	return IRQ_SET_MASK_OK_DONE;
649 }
650 
651 static void its_irq_compose_msi_msg(struct irq_data *d, struct msi_msg *msg)
652 {
653 	struct its_device *its_dev = irq_data_get_irq_chip_data(d);
654 	struct its_node *its;
655 	u64 addr;
656 
657 	its = its_dev->its;
658 	addr = its->phys_base + GITS_TRANSLATER;
659 
660 	msg->address_lo		= addr & ((1UL << 32) - 1);
661 	msg->address_hi		= addr >> 32;
662 	msg->data		= its_get_event_id(d);
663 
664 	iommu_dma_map_msi_msg(d->irq, msg);
665 }
666 
667 static struct irq_chip its_irq_chip = {
668 	.name			= "ITS",
669 	.irq_mask		= its_mask_irq,
670 	.irq_unmask		= its_unmask_irq,
671 	.irq_eoi		= irq_chip_eoi_parent,
672 	.irq_set_affinity	= its_set_affinity,
673 	.irq_compose_msi_msg	= its_irq_compose_msi_msg,
674 };
675 
676 /*
677  * How we allocate LPIs:
678  *
679  * The GIC has id_bits bits for interrupt identifiers. From there, we
680  * must subtract 8192 which are reserved for SGIs/PPIs/SPIs. Then, as
681  * we allocate LPIs by chunks of 32, we can shift the whole thing by 5
682  * bits to the right.
683  *
684  * This gives us (((1UL << id_bits) - 8192) >> 5) possible allocations.
685  */
686 #define IRQS_PER_CHUNK_SHIFT	5
687 #define IRQS_PER_CHUNK		(1 << IRQS_PER_CHUNK_SHIFT)
688 
689 static unsigned long *lpi_bitmap;
690 static u32 lpi_chunks;
691 static DEFINE_SPINLOCK(lpi_lock);
692 
693 static int its_lpi_to_chunk(int lpi)
694 {
695 	return (lpi - 8192) >> IRQS_PER_CHUNK_SHIFT;
696 }
697 
698 static int its_chunk_to_lpi(int chunk)
699 {
700 	return (chunk << IRQS_PER_CHUNK_SHIFT) + 8192;
701 }
702 
703 static int __init its_lpi_init(u32 id_bits)
704 {
705 	lpi_chunks = its_lpi_to_chunk(1UL << id_bits);
706 
707 	lpi_bitmap = kzalloc(BITS_TO_LONGS(lpi_chunks) * sizeof(long),
708 			     GFP_KERNEL);
709 	if (!lpi_bitmap) {
710 		lpi_chunks = 0;
711 		return -ENOMEM;
712 	}
713 
714 	pr_info("ITS: Allocated %d chunks for LPIs\n", (int)lpi_chunks);
715 	return 0;
716 }
717 
718 static unsigned long *its_lpi_alloc_chunks(int nr_irqs, int *base, int *nr_ids)
719 {
720 	unsigned long *bitmap = NULL;
721 	int chunk_id;
722 	int nr_chunks;
723 	int i;
724 
725 	nr_chunks = DIV_ROUND_UP(nr_irqs, IRQS_PER_CHUNK);
726 
727 	spin_lock(&lpi_lock);
728 
729 	do {
730 		chunk_id = bitmap_find_next_zero_area(lpi_bitmap, lpi_chunks,
731 						      0, nr_chunks, 0);
732 		if (chunk_id < lpi_chunks)
733 			break;
734 
735 		nr_chunks--;
736 	} while (nr_chunks > 0);
737 
738 	if (!nr_chunks)
739 		goto out;
740 
741 	bitmap = kzalloc(BITS_TO_LONGS(nr_chunks * IRQS_PER_CHUNK) * sizeof (long),
742 			 GFP_ATOMIC);
743 	if (!bitmap)
744 		goto out;
745 
746 	for (i = 0; i < nr_chunks; i++)
747 		set_bit(chunk_id + i, lpi_bitmap);
748 
749 	*base = its_chunk_to_lpi(chunk_id);
750 	*nr_ids = nr_chunks * IRQS_PER_CHUNK;
751 
752 out:
753 	spin_unlock(&lpi_lock);
754 
755 	if (!bitmap)
756 		*base = *nr_ids = 0;
757 
758 	return bitmap;
759 }
760 
761 static void its_lpi_free(struct event_lpi_map *map)
762 {
763 	int base = map->lpi_base;
764 	int nr_ids = map->nr_lpis;
765 	int lpi;
766 
767 	spin_lock(&lpi_lock);
768 
769 	for (lpi = base; lpi < (base + nr_ids); lpi += IRQS_PER_CHUNK) {
770 		int chunk = its_lpi_to_chunk(lpi);
771 		BUG_ON(chunk > lpi_chunks);
772 		if (test_bit(chunk, lpi_bitmap)) {
773 			clear_bit(chunk, lpi_bitmap);
774 		} else {
775 			pr_err("Bad LPI chunk %d\n", chunk);
776 		}
777 	}
778 
779 	spin_unlock(&lpi_lock);
780 
781 	kfree(map->lpi_map);
782 	kfree(map->col_map);
783 }
784 
785 /*
786  * We allocate 64kB for PROPBASE. That gives us at most 64K LPIs to
787  * deal with (one configuration byte per interrupt). PENDBASE has to
788  * be 64kB aligned (one bit per LPI, plus 8192 bits for SPI/PPI/SGI).
789  */
790 #define LPI_PROPBASE_SZ		SZ_64K
791 #define LPI_PENDBASE_SZ		(LPI_PROPBASE_SZ / 8 + SZ_1K)
792 
793 /*
794  * This is how many bits of ID we need, including the useless ones.
795  */
796 #define LPI_NRBITS		ilog2(LPI_PROPBASE_SZ + SZ_8K)
797 
798 #define LPI_PROP_DEFAULT_PRIO	0xa0
799 
800 static int __init its_alloc_lpi_tables(void)
801 {
802 	phys_addr_t paddr;
803 
804 	gic_rdists->prop_page = alloc_pages(GFP_NOWAIT,
805 					   get_order(LPI_PROPBASE_SZ));
806 	if (!gic_rdists->prop_page) {
807 		pr_err("Failed to allocate PROPBASE\n");
808 		return -ENOMEM;
809 	}
810 
811 	paddr = page_to_phys(gic_rdists->prop_page);
812 	pr_info("GIC: using LPI property table @%pa\n", &paddr);
813 
814 	/* Priority 0xa0, Group-1, disabled */
815 	memset(page_address(gic_rdists->prop_page),
816 	       LPI_PROP_DEFAULT_PRIO | LPI_PROP_GROUP1,
817 	       LPI_PROPBASE_SZ);
818 
819 	/* Make sure the GIC will observe the written configuration */
820 	__flush_dcache_area(page_address(gic_rdists->prop_page), LPI_PROPBASE_SZ);
821 
822 	return 0;
823 }
824 
825 static const char *its_base_type_string[] = {
826 	[GITS_BASER_TYPE_DEVICE]	= "Devices",
827 	[GITS_BASER_TYPE_VCPU]		= "Virtual CPUs",
828 	[GITS_BASER_TYPE_CPU]		= "Physical CPUs",
829 	[GITS_BASER_TYPE_COLLECTION]	= "Interrupt Collections",
830 	[GITS_BASER_TYPE_RESERVED5] 	= "Reserved (5)",
831 	[GITS_BASER_TYPE_RESERVED6] 	= "Reserved (6)",
832 	[GITS_BASER_TYPE_RESERVED7] 	= "Reserved (7)",
833 };
834 
835 static u64 its_read_baser(struct its_node *its, struct its_baser *baser)
836 {
837 	u32 idx = baser - its->tables;
838 
839 	return readq_relaxed(its->base + GITS_BASER + (idx << 3));
840 }
841 
842 static void its_write_baser(struct its_node *its, struct its_baser *baser,
843 			    u64 val)
844 {
845 	u32 idx = baser - its->tables;
846 
847 	writeq_relaxed(val, its->base + GITS_BASER + (idx << 3));
848 	baser->val = its_read_baser(its, baser);
849 }
850 
851 static int its_setup_baser(struct its_node *its, struct its_baser *baser,
852 			   u64 cache, u64 shr, u32 psz, u32 order,
853 			   bool indirect)
854 {
855 	u64 val = its_read_baser(its, baser);
856 	u64 esz = GITS_BASER_ENTRY_SIZE(val);
857 	u64 type = GITS_BASER_TYPE(val);
858 	u32 alloc_pages;
859 	void *base;
860 	u64 tmp;
861 
862 retry_alloc_baser:
863 	alloc_pages = (PAGE_ORDER_TO_SIZE(order) / psz);
864 	if (alloc_pages > GITS_BASER_PAGES_MAX) {
865 		pr_warn("ITS@%pa: %s too large, reduce ITS pages %u->%u\n",
866 			&its->phys_base, its_base_type_string[type],
867 			alloc_pages, GITS_BASER_PAGES_MAX);
868 		alloc_pages = GITS_BASER_PAGES_MAX;
869 		order = get_order(GITS_BASER_PAGES_MAX * psz);
870 	}
871 
872 	base = (void *)__get_free_pages(GFP_KERNEL | __GFP_ZERO, order);
873 	if (!base)
874 		return -ENOMEM;
875 
876 retry_baser:
877 	val = (virt_to_phys(base)				 |
878 		(type << GITS_BASER_TYPE_SHIFT)			 |
879 		((esz - 1) << GITS_BASER_ENTRY_SIZE_SHIFT)	 |
880 		((alloc_pages - 1) << GITS_BASER_PAGES_SHIFT)	 |
881 		cache						 |
882 		shr						 |
883 		GITS_BASER_VALID);
884 
885 	val |=	indirect ? GITS_BASER_INDIRECT : 0x0;
886 
887 	switch (psz) {
888 	case SZ_4K:
889 		val |= GITS_BASER_PAGE_SIZE_4K;
890 		break;
891 	case SZ_16K:
892 		val |= GITS_BASER_PAGE_SIZE_16K;
893 		break;
894 	case SZ_64K:
895 		val |= GITS_BASER_PAGE_SIZE_64K;
896 		break;
897 	}
898 
899 	its_write_baser(its, baser, val);
900 	tmp = baser->val;
901 
902 	if ((val ^ tmp) & GITS_BASER_SHAREABILITY_MASK) {
903 		/*
904 		 * Shareability didn't stick. Just use
905 		 * whatever the read reported, which is likely
906 		 * to be the only thing this redistributor
907 		 * supports. If that's zero, make it
908 		 * non-cacheable as well.
909 		 */
910 		shr = tmp & GITS_BASER_SHAREABILITY_MASK;
911 		if (!shr) {
912 			cache = GITS_BASER_nC;
913 			__flush_dcache_area(base, PAGE_ORDER_TO_SIZE(order));
914 		}
915 		goto retry_baser;
916 	}
917 
918 	if ((val ^ tmp) & GITS_BASER_PAGE_SIZE_MASK) {
919 		/*
920 		 * Page size didn't stick. Let's try a smaller
921 		 * size and retry. If we reach 4K, then
922 		 * something is horribly wrong...
923 		 */
924 		free_pages((unsigned long)base, order);
925 		baser->base = NULL;
926 
927 		switch (psz) {
928 		case SZ_16K:
929 			psz = SZ_4K;
930 			goto retry_alloc_baser;
931 		case SZ_64K:
932 			psz = SZ_16K;
933 			goto retry_alloc_baser;
934 		}
935 	}
936 
937 	if (val != tmp) {
938 		pr_err("ITS@%pa: %s doesn't stick: %lx %lx\n",
939 		       &its->phys_base, its_base_type_string[type],
940 		       (unsigned long) val, (unsigned long) tmp);
941 		free_pages((unsigned long)base, order);
942 		return -ENXIO;
943 	}
944 
945 	baser->order = order;
946 	baser->base = base;
947 	baser->psz = psz;
948 	tmp = indirect ? GITS_LVL1_ENTRY_SIZE : esz;
949 
950 	pr_info("ITS@%pa: allocated %d %s @%lx (%s, esz %d, psz %dK, shr %d)\n",
951 		&its->phys_base, (int)(PAGE_ORDER_TO_SIZE(order) / tmp),
952 		its_base_type_string[type],
953 		(unsigned long)virt_to_phys(base),
954 		indirect ? "indirect" : "flat", (int)esz,
955 		psz / SZ_1K, (int)shr >> GITS_BASER_SHAREABILITY_SHIFT);
956 
957 	return 0;
958 }
959 
960 static bool its_parse_baser_device(struct its_node *its, struct its_baser *baser,
961 				   u32 psz, u32 *order)
962 {
963 	u64 esz = GITS_BASER_ENTRY_SIZE(its_read_baser(its, baser));
964 	u64 val = GITS_BASER_InnerShareable | GITS_BASER_WaWb;
965 	u32 ids = its->device_ids;
966 	u32 new_order = *order;
967 	bool indirect = false;
968 
969 	/* No need to enable Indirection if memory requirement < (psz*2)bytes */
970 	if ((esz << ids) > (psz * 2)) {
971 		/*
972 		 * Find out whether hw supports a single or two-level table by
973 		 * table by reading bit at offset '62' after writing '1' to it.
974 		 */
975 		its_write_baser(its, baser, val | GITS_BASER_INDIRECT);
976 		indirect = !!(baser->val & GITS_BASER_INDIRECT);
977 
978 		if (indirect) {
979 			/*
980 			 * The size of the lvl2 table is equal to ITS page size
981 			 * which is 'psz'. For computing lvl1 table size,
982 			 * subtract ID bits that sparse lvl2 table from 'ids'
983 			 * which is reported by ITS hardware times lvl1 table
984 			 * entry size.
985 			 */
986 			ids -= ilog2(psz / esz);
987 			esz = GITS_LVL1_ENTRY_SIZE;
988 		}
989 	}
990 
991 	/*
992 	 * Allocate as many entries as required to fit the
993 	 * range of device IDs that the ITS can grok... The ID
994 	 * space being incredibly sparse, this results in a
995 	 * massive waste of memory if two-level device table
996 	 * feature is not supported by hardware.
997 	 */
998 	new_order = max_t(u32, get_order(esz << ids), new_order);
999 	if (new_order >= MAX_ORDER) {
1000 		new_order = MAX_ORDER - 1;
1001 		ids = ilog2(PAGE_ORDER_TO_SIZE(new_order) / esz);
1002 		pr_warn("ITS@%pa: Device Table too large, reduce ids %u->%u\n",
1003 			&its->phys_base, its->device_ids, ids);
1004 	}
1005 
1006 	*order = new_order;
1007 
1008 	return indirect;
1009 }
1010 
1011 static void its_free_tables(struct its_node *its)
1012 {
1013 	int i;
1014 
1015 	for (i = 0; i < GITS_BASER_NR_REGS; i++) {
1016 		if (its->tables[i].base) {
1017 			free_pages((unsigned long)its->tables[i].base,
1018 				   its->tables[i].order);
1019 			its->tables[i].base = NULL;
1020 		}
1021 	}
1022 }
1023 
1024 static int its_alloc_tables(struct its_node *its)
1025 {
1026 	u64 typer = gic_read_typer(its->base + GITS_TYPER);
1027 	u32 ids = GITS_TYPER_DEVBITS(typer);
1028 	u64 shr = GITS_BASER_InnerShareable;
1029 	u64 cache = GITS_BASER_WaWb;
1030 	u32 psz = SZ_64K;
1031 	int err, i;
1032 
1033 	if (its->flags & ITS_FLAGS_WORKAROUND_CAVIUM_22375) {
1034 		/*
1035 		* erratum 22375: only alloc 8MB table size
1036 		* erratum 24313: ignore memory access type
1037 		*/
1038 		cache   = GITS_BASER_nCnB;
1039 		ids     = 0x14;                 /* 20 bits, 8MB */
1040 	}
1041 
1042 	its->device_ids = ids;
1043 
1044 	for (i = 0; i < GITS_BASER_NR_REGS; i++) {
1045 		struct its_baser *baser = its->tables + i;
1046 		u64 val = its_read_baser(its, baser);
1047 		u64 type = GITS_BASER_TYPE(val);
1048 		u32 order = get_order(psz);
1049 		bool indirect = false;
1050 
1051 		if (type == GITS_BASER_TYPE_NONE)
1052 			continue;
1053 
1054 		if (type == GITS_BASER_TYPE_DEVICE)
1055 			indirect = its_parse_baser_device(its, baser, psz, &order);
1056 
1057 		err = its_setup_baser(its, baser, cache, shr, psz, order, indirect);
1058 		if (err < 0) {
1059 			its_free_tables(its);
1060 			return err;
1061 		}
1062 
1063 		/* Update settings which will be used for next BASERn */
1064 		psz = baser->psz;
1065 		cache = baser->val & GITS_BASER_CACHEABILITY_MASK;
1066 		shr = baser->val & GITS_BASER_SHAREABILITY_MASK;
1067 	}
1068 
1069 	return 0;
1070 }
1071 
1072 static int its_alloc_collections(struct its_node *its)
1073 {
1074 	its->collections = kzalloc(nr_cpu_ids * sizeof(*its->collections),
1075 				   GFP_KERNEL);
1076 	if (!its->collections)
1077 		return -ENOMEM;
1078 
1079 	return 0;
1080 }
1081 
1082 static void its_cpu_init_lpis(void)
1083 {
1084 	void __iomem *rbase = gic_data_rdist_rd_base();
1085 	struct page *pend_page;
1086 	u64 val, tmp;
1087 
1088 	/* If we didn't allocate the pending table yet, do it now */
1089 	pend_page = gic_data_rdist()->pend_page;
1090 	if (!pend_page) {
1091 		phys_addr_t paddr;
1092 		/*
1093 		 * The pending pages have to be at least 64kB aligned,
1094 		 * hence the 'max(LPI_PENDBASE_SZ, SZ_64K)' below.
1095 		 */
1096 		pend_page = alloc_pages(GFP_NOWAIT | __GFP_ZERO,
1097 					get_order(max(LPI_PENDBASE_SZ, SZ_64K)));
1098 		if (!pend_page) {
1099 			pr_err("Failed to allocate PENDBASE for CPU%d\n",
1100 			       smp_processor_id());
1101 			return;
1102 		}
1103 
1104 		/* Make sure the GIC will observe the zero-ed page */
1105 		__flush_dcache_area(page_address(pend_page), LPI_PENDBASE_SZ);
1106 
1107 		paddr = page_to_phys(pend_page);
1108 		pr_info("CPU%d: using LPI pending table @%pa\n",
1109 			smp_processor_id(), &paddr);
1110 		gic_data_rdist()->pend_page = pend_page;
1111 	}
1112 
1113 	/* Disable LPIs */
1114 	val = readl_relaxed(rbase + GICR_CTLR);
1115 	val &= ~GICR_CTLR_ENABLE_LPIS;
1116 	writel_relaxed(val, rbase + GICR_CTLR);
1117 
1118 	/*
1119 	 * Make sure any change to the table is observable by the GIC.
1120 	 */
1121 	dsb(sy);
1122 
1123 	/* set PROPBASE */
1124 	val = (page_to_phys(gic_rdists->prop_page) |
1125 	       GICR_PROPBASER_InnerShareable |
1126 	       GICR_PROPBASER_WaWb |
1127 	       ((LPI_NRBITS - 1) & GICR_PROPBASER_IDBITS_MASK));
1128 
1129 	writeq_relaxed(val, rbase + GICR_PROPBASER);
1130 	tmp = readq_relaxed(rbase + GICR_PROPBASER);
1131 
1132 	if ((tmp ^ val) & GICR_PROPBASER_SHAREABILITY_MASK) {
1133 		if (!(tmp & GICR_PROPBASER_SHAREABILITY_MASK)) {
1134 			/*
1135 			 * The HW reports non-shareable, we must
1136 			 * remove the cacheability attributes as
1137 			 * well.
1138 			 */
1139 			val &= ~(GICR_PROPBASER_SHAREABILITY_MASK |
1140 				 GICR_PROPBASER_CACHEABILITY_MASK);
1141 			val |= GICR_PROPBASER_nC;
1142 			writeq_relaxed(val, rbase + GICR_PROPBASER);
1143 		}
1144 		pr_info_once("GIC: using cache flushing for LPI property table\n");
1145 		gic_rdists->flags |= RDIST_FLAGS_PROPBASE_NEEDS_FLUSHING;
1146 	}
1147 
1148 	/* set PENDBASE */
1149 	val = (page_to_phys(pend_page) |
1150 	       GICR_PENDBASER_InnerShareable |
1151 	       GICR_PENDBASER_WaWb);
1152 
1153 	writeq_relaxed(val, rbase + GICR_PENDBASER);
1154 	tmp = readq_relaxed(rbase + GICR_PENDBASER);
1155 
1156 	if (!(tmp & GICR_PENDBASER_SHAREABILITY_MASK)) {
1157 		/*
1158 		 * The HW reports non-shareable, we must remove the
1159 		 * cacheability attributes as well.
1160 		 */
1161 		val &= ~(GICR_PENDBASER_SHAREABILITY_MASK |
1162 			 GICR_PENDBASER_CACHEABILITY_MASK);
1163 		val |= GICR_PENDBASER_nC;
1164 		writeq_relaxed(val, rbase + GICR_PENDBASER);
1165 	}
1166 
1167 	/* Enable LPIs */
1168 	val = readl_relaxed(rbase + GICR_CTLR);
1169 	val |= GICR_CTLR_ENABLE_LPIS;
1170 	writel_relaxed(val, rbase + GICR_CTLR);
1171 
1172 	/* Make sure the GIC has seen the above */
1173 	dsb(sy);
1174 }
1175 
1176 static void its_cpu_init_collection(void)
1177 {
1178 	struct its_node *its;
1179 	int cpu;
1180 
1181 	spin_lock(&its_lock);
1182 	cpu = smp_processor_id();
1183 
1184 	list_for_each_entry(its, &its_nodes, entry) {
1185 		u64 target;
1186 
1187 		/* avoid cross node collections and its mapping */
1188 		if (its->flags & ITS_FLAGS_WORKAROUND_CAVIUM_23144) {
1189 			struct device_node *cpu_node;
1190 
1191 			cpu_node = of_get_cpu_node(cpu, NULL);
1192 			if (its->numa_node != NUMA_NO_NODE &&
1193 				its->numa_node != of_node_to_nid(cpu_node))
1194 				continue;
1195 		}
1196 
1197 		/*
1198 		 * We now have to bind each collection to its target
1199 		 * redistributor.
1200 		 */
1201 		if (gic_read_typer(its->base + GITS_TYPER) & GITS_TYPER_PTA) {
1202 			/*
1203 			 * This ITS wants the physical address of the
1204 			 * redistributor.
1205 			 */
1206 			target = gic_data_rdist()->phys_base;
1207 		} else {
1208 			/*
1209 			 * This ITS wants a linear CPU number.
1210 			 */
1211 			target = gic_read_typer(gic_data_rdist_rd_base() + GICR_TYPER);
1212 			target = GICR_TYPER_CPU_NUMBER(target) << 16;
1213 		}
1214 
1215 		/* Perform collection mapping */
1216 		its->collections[cpu].target_address = target;
1217 		its->collections[cpu].col_id = cpu;
1218 
1219 		its_send_mapc(its, &its->collections[cpu], 1);
1220 		its_send_invall(its, &its->collections[cpu]);
1221 	}
1222 
1223 	spin_unlock(&its_lock);
1224 }
1225 
1226 static struct its_device *its_find_device(struct its_node *its, u32 dev_id)
1227 {
1228 	struct its_device *its_dev = NULL, *tmp;
1229 	unsigned long flags;
1230 
1231 	raw_spin_lock_irqsave(&its->lock, flags);
1232 
1233 	list_for_each_entry(tmp, &its->its_device_list, entry) {
1234 		if (tmp->device_id == dev_id) {
1235 			its_dev = tmp;
1236 			break;
1237 		}
1238 	}
1239 
1240 	raw_spin_unlock_irqrestore(&its->lock, flags);
1241 
1242 	return its_dev;
1243 }
1244 
1245 static struct its_baser *its_get_baser(struct its_node *its, u32 type)
1246 {
1247 	int i;
1248 
1249 	for (i = 0; i < GITS_BASER_NR_REGS; i++) {
1250 		if (GITS_BASER_TYPE(its->tables[i].val) == type)
1251 			return &its->tables[i];
1252 	}
1253 
1254 	return NULL;
1255 }
1256 
1257 static bool its_alloc_device_table(struct its_node *its, u32 dev_id)
1258 {
1259 	struct its_baser *baser;
1260 	struct page *page;
1261 	u32 esz, idx;
1262 	__le64 *table;
1263 
1264 	baser = its_get_baser(its, GITS_BASER_TYPE_DEVICE);
1265 
1266 	/* Don't allow device id that exceeds ITS hardware limit */
1267 	if (!baser)
1268 		return (ilog2(dev_id) < its->device_ids);
1269 
1270 	/* Don't allow device id that exceeds single, flat table limit */
1271 	esz = GITS_BASER_ENTRY_SIZE(baser->val);
1272 	if (!(baser->val & GITS_BASER_INDIRECT))
1273 		return (dev_id < (PAGE_ORDER_TO_SIZE(baser->order) / esz));
1274 
1275 	/* Compute 1st level table index & check if that exceeds table limit */
1276 	idx = dev_id >> ilog2(baser->psz / esz);
1277 	if (idx >= (PAGE_ORDER_TO_SIZE(baser->order) / GITS_LVL1_ENTRY_SIZE))
1278 		return false;
1279 
1280 	table = baser->base;
1281 
1282 	/* Allocate memory for 2nd level table */
1283 	if (!table[idx]) {
1284 		page = alloc_pages(GFP_KERNEL | __GFP_ZERO, get_order(baser->psz));
1285 		if (!page)
1286 			return false;
1287 
1288 		/* Flush Lvl2 table to PoC if hw doesn't support coherency */
1289 		if (!(baser->val & GITS_BASER_SHAREABILITY_MASK))
1290 			__flush_dcache_area(page_address(page), baser->psz);
1291 
1292 		table[idx] = cpu_to_le64(page_to_phys(page) | GITS_BASER_VALID);
1293 
1294 		/* Flush Lvl1 entry to PoC if hw doesn't support coherency */
1295 		if (!(baser->val & GITS_BASER_SHAREABILITY_MASK))
1296 			__flush_dcache_area(table + idx, GITS_LVL1_ENTRY_SIZE);
1297 
1298 		/* Ensure updated table contents are visible to ITS hardware */
1299 		dsb(sy);
1300 	}
1301 
1302 	return true;
1303 }
1304 
1305 static struct its_device *its_create_device(struct its_node *its, u32 dev_id,
1306 					    int nvecs)
1307 {
1308 	struct its_device *dev;
1309 	unsigned long *lpi_map;
1310 	unsigned long flags;
1311 	u16 *col_map = NULL;
1312 	void *itt;
1313 	int lpi_base;
1314 	int nr_lpis;
1315 	int nr_ites;
1316 	int sz;
1317 
1318 	if (!its_alloc_device_table(its, dev_id))
1319 		return NULL;
1320 
1321 	dev = kzalloc(sizeof(*dev), GFP_KERNEL);
1322 	/*
1323 	 * At least one bit of EventID is being used, hence a minimum
1324 	 * of two entries. No, the architecture doesn't let you
1325 	 * express an ITT with a single entry.
1326 	 */
1327 	nr_ites = max(2UL, roundup_pow_of_two(nvecs));
1328 	sz = nr_ites * its->ite_size;
1329 	sz = max(sz, ITS_ITT_ALIGN) + ITS_ITT_ALIGN - 1;
1330 	itt = kzalloc(sz, GFP_KERNEL);
1331 	lpi_map = its_lpi_alloc_chunks(nvecs, &lpi_base, &nr_lpis);
1332 	if (lpi_map)
1333 		col_map = kzalloc(sizeof(*col_map) * nr_lpis, GFP_KERNEL);
1334 
1335 	if (!dev || !itt || !lpi_map || !col_map) {
1336 		kfree(dev);
1337 		kfree(itt);
1338 		kfree(lpi_map);
1339 		kfree(col_map);
1340 		return NULL;
1341 	}
1342 
1343 	__flush_dcache_area(itt, sz);
1344 
1345 	dev->its = its;
1346 	dev->itt = itt;
1347 	dev->nr_ites = nr_ites;
1348 	dev->event_map.lpi_map = lpi_map;
1349 	dev->event_map.col_map = col_map;
1350 	dev->event_map.lpi_base = lpi_base;
1351 	dev->event_map.nr_lpis = nr_lpis;
1352 	dev->device_id = dev_id;
1353 	INIT_LIST_HEAD(&dev->entry);
1354 
1355 	raw_spin_lock_irqsave(&its->lock, flags);
1356 	list_add(&dev->entry, &its->its_device_list);
1357 	raw_spin_unlock_irqrestore(&its->lock, flags);
1358 
1359 	/* Map device to its ITT */
1360 	its_send_mapd(dev, 1);
1361 
1362 	return dev;
1363 }
1364 
1365 static void its_free_device(struct its_device *its_dev)
1366 {
1367 	unsigned long flags;
1368 
1369 	raw_spin_lock_irqsave(&its_dev->its->lock, flags);
1370 	list_del(&its_dev->entry);
1371 	raw_spin_unlock_irqrestore(&its_dev->its->lock, flags);
1372 	kfree(its_dev->itt);
1373 	kfree(its_dev);
1374 }
1375 
1376 static int its_alloc_device_irq(struct its_device *dev, irq_hw_number_t *hwirq)
1377 {
1378 	int idx;
1379 
1380 	idx = find_first_zero_bit(dev->event_map.lpi_map,
1381 				  dev->event_map.nr_lpis);
1382 	if (idx == dev->event_map.nr_lpis)
1383 		return -ENOSPC;
1384 
1385 	*hwirq = dev->event_map.lpi_base + idx;
1386 	set_bit(idx, dev->event_map.lpi_map);
1387 
1388 	return 0;
1389 }
1390 
1391 static int its_msi_prepare(struct irq_domain *domain, struct device *dev,
1392 			   int nvec, msi_alloc_info_t *info)
1393 {
1394 	struct its_node *its;
1395 	struct its_device *its_dev;
1396 	struct msi_domain_info *msi_info;
1397 	u32 dev_id;
1398 
1399 	/*
1400 	 * We ignore "dev" entierely, and rely on the dev_id that has
1401 	 * been passed via the scratchpad. This limits this domain's
1402 	 * usefulness to upper layers that definitely know that they
1403 	 * are built on top of the ITS.
1404 	 */
1405 	dev_id = info->scratchpad[0].ul;
1406 
1407 	msi_info = msi_get_domain_info(domain);
1408 	its = msi_info->data;
1409 
1410 	its_dev = its_find_device(its, dev_id);
1411 	if (its_dev) {
1412 		/*
1413 		 * We already have seen this ID, probably through
1414 		 * another alias (PCI bridge of some sort). No need to
1415 		 * create the device.
1416 		 */
1417 		pr_debug("Reusing ITT for devID %x\n", dev_id);
1418 		goto out;
1419 	}
1420 
1421 	its_dev = its_create_device(its, dev_id, nvec);
1422 	if (!its_dev)
1423 		return -ENOMEM;
1424 
1425 	pr_debug("ITT %d entries, %d bits\n", nvec, ilog2(nvec));
1426 out:
1427 	info->scratchpad[0].ptr = its_dev;
1428 	return 0;
1429 }
1430 
1431 static struct msi_domain_ops its_msi_domain_ops = {
1432 	.msi_prepare	= its_msi_prepare,
1433 };
1434 
1435 static int its_irq_gic_domain_alloc(struct irq_domain *domain,
1436 				    unsigned int virq,
1437 				    irq_hw_number_t hwirq)
1438 {
1439 	struct irq_fwspec fwspec;
1440 
1441 	if (irq_domain_get_of_node(domain->parent)) {
1442 		fwspec.fwnode = domain->parent->fwnode;
1443 		fwspec.param_count = 3;
1444 		fwspec.param[0] = GIC_IRQ_TYPE_LPI;
1445 		fwspec.param[1] = hwirq;
1446 		fwspec.param[2] = IRQ_TYPE_EDGE_RISING;
1447 	} else if (is_fwnode_irqchip(domain->parent->fwnode)) {
1448 		fwspec.fwnode = domain->parent->fwnode;
1449 		fwspec.param_count = 2;
1450 		fwspec.param[0] = hwirq;
1451 		fwspec.param[1] = IRQ_TYPE_EDGE_RISING;
1452 	} else {
1453 		return -EINVAL;
1454 	}
1455 
1456 	return irq_domain_alloc_irqs_parent(domain, virq, 1, &fwspec);
1457 }
1458 
1459 static int its_irq_domain_alloc(struct irq_domain *domain, unsigned int virq,
1460 				unsigned int nr_irqs, void *args)
1461 {
1462 	msi_alloc_info_t *info = args;
1463 	struct its_device *its_dev = info->scratchpad[0].ptr;
1464 	irq_hw_number_t hwirq;
1465 	int err;
1466 	int i;
1467 
1468 	for (i = 0; i < nr_irqs; i++) {
1469 		err = its_alloc_device_irq(its_dev, &hwirq);
1470 		if (err)
1471 			return err;
1472 
1473 		err = its_irq_gic_domain_alloc(domain, virq + i, hwirq);
1474 		if (err)
1475 			return err;
1476 
1477 		irq_domain_set_hwirq_and_chip(domain, virq + i,
1478 					      hwirq, &its_irq_chip, its_dev);
1479 		pr_debug("ID:%d pID:%d vID:%d\n",
1480 			 (int)(hwirq - its_dev->event_map.lpi_base),
1481 			 (int) hwirq, virq + i);
1482 	}
1483 
1484 	return 0;
1485 }
1486 
1487 static void its_irq_domain_activate(struct irq_domain *domain,
1488 				    struct irq_data *d)
1489 {
1490 	struct its_device *its_dev = irq_data_get_irq_chip_data(d);
1491 	u32 event = its_get_event_id(d);
1492 	const struct cpumask *cpu_mask = cpu_online_mask;
1493 
1494 	/* get the cpu_mask of local node */
1495 	if (its_dev->its->numa_node >= 0)
1496 		cpu_mask = cpumask_of_node(its_dev->its->numa_node);
1497 
1498 	/* Bind the LPI to the first possible CPU */
1499 	its_dev->event_map.col_map[event] = cpumask_first(cpu_mask);
1500 
1501 	/* Map the GIC IRQ and event to the device */
1502 	its_send_mapvi(its_dev, d->hwirq, event);
1503 }
1504 
1505 static void its_irq_domain_deactivate(struct irq_domain *domain,
1506 				      struct irq_data *d)
1507 {
1508 	struct its_device *its_dev = irq_data_get_irq_chip_data(d);
1509 	u32 event = its_get_event_id(d);
1510 
1511 	/* Stop the delivery of interrupts */
1512 	its_send_discard(its_dev, event);
1513 }
1514 
1515 static void its_irq_domain_free(struct irq_domain *domain, unsigned int virq,
1516 				unsigned int nr_irqs)
1517 {
1518 	struct irq_data *d = irq_domain_get_irq_data(domain, virq);
1519 	struct its_device *its_dev = irq_data_get_irq_chip_data(d);
1520 	int i;
1521 
1522 	for (i = 0; i < nr_irqs; i++) {
1523 		struct irq_data *data = irq_domain_get_irq_data(domain,
1524 								virq + i);
1525 		u32 event = its_get_event_id(data);
1526 
1527 		/* Mark interrupt index as unused */
1528 		clear_bit(event, its_dev->event_map.lpi_map);
1529 
1530 		/* Nuke the entry in the domain */
1531 		irq_domain_reset_irq_data(data);
1532 	}
1533 
1534 	/* If all interrupts have been freed, start mopping the floor */
1535 	if (bitmap_empty(its_dev->event_map.lpi_map,
1536 			 its_dev->event_map.nr_lpis)) {
1537 		its_lpi_free(&its_dev->event_map);
1538 
1539 		/* Unmap device/itt */
1540 		its_send_mapd(its_dev, 0);
1541 		its_free_device(its_dev);
1542 	}
1543 
1544 	irq_domain_free_irqs_parent(domain, virq, nr_irqs);
1545 }
1546 
1547 static const struct irq_domain_ops its_domain_ops = {
1548 	.alloc			= its_irq_domain_alloc,
1549 	.free			= its_irq_domain_free,
1550 	.activate		= its_irq_domain_activate,
1551 	.deactivate		= its_irq_domain_deactivate,
1552 };
1553 
1554 static int its_force_quiescent(void __iomem *base)
1555 {
1556 	u32 count = 1000000;	/* 1s */
1557 	u32 val;
1558 
1559 	val = readl_relaxed(base + GITS_CTLR);
1560 	/*
1561 	 * GIC architecture specification requires the ITS to be both
1562 	 * disabled and quiescent for writes to GITS_BASER<n> or
1563 	 * GITS_CBASER to not have UNPREDICTABLE results.
1564 	 */
1565 	if ((val & GITS_CTLR_QUIESCENT) && !(val & GITS_CTLR_ENABLE))
1566 		return 0;
1567 
1568 	/* Disable the generation of all interrupts to this ITS */
1569 	val &= ~GITS_CTLR_ENABLE;
1570 	writel_relaxed(val, base + GITS_CTLR);
1571 
1572 	/* Poll GITS_CTLR and wait until ITS becomes quiescent */
1573 	while (1) {
1574 		val = readl_relaxed(base + GITS_CTLR);
1575 		if (val & GITS_CTLR_QUIESCENT)
1576 			return 0;
1577 
1578 		count--;
1579 		if (!count)
1580 			return -EBUSY;
1581 
1582 		cpu_relax();
1583 		udelay(1);
1584 	}
1585 }
1586 
1587 static void __maybe_unused its_enable_quirk_cavium_22375(void *data)
1588 {
1589 	struct its_node *its = data;
1590 
1591 	its->flags |= ITS_FLAGS_WORKAROUND_CAVIUM_22375;
1592 }
1593 
1594 static void __maybe_unused its_enable_quirk_cavium_23144(void *data)
1595 {
1596 	struct its_node *its = data;
1597 
1598 	its->flags |= ITS_FLAGS_WORKAROUND_CAVIUM_23144;
1599 }
1600 
1601 static const struct gic_quirk its_quirks[] = {
1602 #ifdef CONFIG_CAVIUM_ERRATUM_22375
1603 	{
1604 		.desc	= "ITS: Cavium errata 22375, 24313",
1605 		.iidr	= 0xa100034c,	/* ThunderX pass 1.x */
1606 		.mask	= 0xffff0fff,
1607 		.init	= its_enable_quirk_cavium_22375,
1608 	},
1609 #endif
1610 #ifdef CONFIG_CAVIUM_ERRATUM_23144
1611 	{
1612 		.desc	= "ITS: Cavium erratum 23144",
1613 		.iidr	= 0xa100034c,	/* ThunderX pass 1.x */
1614 		.mask	= 0xffff0fff,
1615 		.init	= its_enable_quirk_cavium_23144,
1616 	},
1617 #endif
1618 	{
1619 	}
1620 };
1621 
1622 static void its_enable_quirks(struct its_node *its)
1623 {
1624 	u32 iidr = readl_relaxed(its->base + GITS_IIDR);
1625 
1626 	gic_enable_quirks(iidr, its_quirks, its);
1627 }
1628 
1629 static int its_init_domain(struct fwnode_handle *handle, struct its_node *its)
1630 {
1631 	struct irq_domain *inner_domain;
1632 	struct msi_domain_info *info;
1633 
1634 	info = kzalloc(sizeof(*info), GFP_KERNEL);
1635 	if (!info)
1636 		return -ENOMEM;
1637 
1638 	inner_domain = irq_domain_create_tree(handle, &its_domain_ops, its);
1639 	if (!inner_domain) {
1640 		kfree(info);
1641 		return -ENOMEM;
1642 	}
1643 
1644 	inner_domain->parent = its_parent;
1645 	inner_domain->bus_token = DOMAIN_BUS_NEXUS;
1646 	info->ops = &its_msi_domain_ops;
1647 	info->data = its;
1648 	inner_domain->host_data = info;
1649 
1650 	return 0;
1651 }
1652 
1653 static int __init its_probe_one(struct resource *res,
1654 				struct fwnode_handle *handle, int numa_node)
1655 {
1656 	struct its_node *its;
1657 	void __iomem *its_base;
1658 	u32 val;
1659 	u64 baser, tmp;
1660 	int err;
1661 
1662 	its_base = ioremap(res->start, resource_size(res));
1663 	if (!its_base) {
1664 		pr_warn("ITS@%pa: Unable to map ITS registers\n", &res->start);
1665 		return -ENOMEM;
1666 	}
1667 
1668 	val = readl_relaxed(its_base + GITS_PIDR2) & GIC_PIDR2_ARCH_MASK;
1669 	if (val != 0x30 && val != 0x40) {
1670 		pr_warn("ITS@%pa: No ITS detected, giving up\n", &res->start);
1671 		err = -ENODEV;
1672 		goto out_unmap;
1673 	}
1674 
1675 	err = its_force_quiescent(its_base);
1676 	if (err) {
1677 		pr_warn("ITS@%pa: Failed to quiesce, giving up\n", &res->start);
1678 		goto out_unmap;
1679 	}
1680 
1681 	pr_info("ITS %pR\n", res);
1682 
1683 	its = kzalloc(sizeof(*its), GFP_KERNEL);
1684 	if (!its) {
1685 		err = -ENOMEM;
1686 		goto out_unmap;
1687 	}
1688 
1689 	raw_spin_lock_init(&its->lock);
1690 	INIT_LIST_HEAD(&its->entry);
1691 	INIT_LIST_HEAD(&its->its_device_list);
1692 	its->base = its_base;
1693 	its->phys_base = res->start;
1694 	its->ite_size = ((gic_read_typer(its_base + GITS_TYPER) >> 4) & 0xf) + 1;
1695 	its->numa_node = numa_node;
1696 
1697 	its->cmd_base = kzalloc(ITS_CMD_QUEUE_SZ, GFP_KERNEL);
1698 	if (!its->cmd_base) {
1699 		err = -ENOMEM;
1700 		goto out_free_its;
1701 	}
1702 	its->cmd_write = its->cmd_base;
1703 
1704 	its_enable_quirks(its);
1705 
1706 	err = its_alloc_tables(its);
1707 	if (err)
1708 		goto out_free_cmd;
1709 
1710 	err = its_alloc_collections(its);
1711 	if (err)
1712 		goto out_free_tables;
1713 
1714 	baser = (virt_to_phys(its->cmd_base)	|
1715 		 GITS_CBASER_WaWb		|
1716 		 GITS_CBASER_InnerShareable	|
1717 		 (ITS_CMD_QUEUE_SZ / SZ_4K - 1)	|
1718 		 GITS_CBASER_VALID);
1719 
1720 	writeq_relaxed(baser, its->base + GITS_CBASER);
1721 	tmp = readq_relaxed(its->base + GITS_CBASER);
1722 
1723 	if ((tmp ^ baser) & GITS_CBASER_SHAREABILITY_MASK) {
1724 		if (!(tmp & GITS_CBASER_SHAREABILITY_MASK)) {
1725 			/*
1726 			 * The HW reports non-shareable, we must
1727 			 * remove the cacheability attributes as
1728 			 * well.
1729 			 */
1730 			baser &= ~(GITS_CBASER_SHAREABILITY_MASK |
1731 				   GITS_CBASER_CACHEABILITY_MASK);
1732 			baser |= GITS_CBASER_nC;
1733 			writeq_relaxed(baser, its->base + GITS_CBASER);
1734 		}
1735 		pr_info("ITS: using cache flushing for cmd queue\n");
1736 		its->flags |= ITS_FLAGS_CMDQ_NEEDS_FLUSHING;
1737 	}
1738 
1739 	writeq_relaxed(0, its->base + GITS_CWRITER);
1740 	writel_relaxed(GITS_CTLR_ENABLE, its->base + GITS_CTLR);
1741 
1742 	err = its_init_domain(handle, its);
1743 	if (err)
1744 		goto out_free_tables;
1745 
1746 	spin_lock(&its_lock);
1747 	list_add(&its->entry, &its_nodes);
1748 	spin_unlock(&its_lock);
1749 
1750 	return 0;
1751 
1752 out_free_tables:
1753 	its_free_tables(its);
1754 out_free_cmd:
1755 	kfree(its->cmd_base);
1756 out_free_its:
1757 	kfree(its);
1758 out_unmap:
1759 	iounmap(its_base);
1760 	pr_err("ITS@%pa: failed probing (%d)\n", &res->start, err);
1761 	return err;
1762 }
1763 
1764 static bool gic_rdists_supports_plpis(void)
1765 {
1766 	return !!(gic_read_typer(gic_data_rdist_rd_base() + GICR_TYPER) & GICR_TYPER_PLPIS);
1767 }
1768 
1769 int its_cpu_init(void)
1770 {
1771 	if (!list_empty(&its_nodes)) {
1772 		if (!gic_rdists_supports_plpis()) {
1773 			pr_info("CPU%d: LPIs not supported\n", smp_processor_id());
1774 			return -ENXIO;
1775 		}
1776 		its_cpu_init_lpis();
1777 		its_cpu_init_collection();
1778 	}
1779 
1780 	return 0;
1781 }
1782 
1783 static struct of_device_id its_device_id[] = {
1784 	{	.compatible	= "arm,gic-v3-its",	},
1785 	{},
1786 };
1787 
1788 static int __init its_of_probe(struct device_node *node)
1789 {
1790 	struct device_node *np;
1791 	struct resource res;
1792 
1793 	for (np = of_find_matching_node(node, its_device_id); np;
1794 	     np = of_find_matching_node(np, its_device_id)) {
1795 		if (!of_property_read_bool(np, "msi-controller")) {
1796 			pr_warn("%s: no msi-controller property, ITS ignored\n",
1797 				np->full_name);
1798 			continue;
1799 		}
1800 
1801 		if (of_address_to_resource(np, 0, &res)) {
1802 			pr_warn("%s: no regs?\n", np->full_name);
1803 			continue;
1804 		}
1805 
1806 		its_probe_one(&res, &np->fwnode, of_node_to_nid(np));
1807 	}
1808 	return 0;
1809 }
1810 
1811 #ifdef CONFIG_ACPI
1812 
1813 #define ACPI_GICV3_ITS_MEM_SIZE (SZ_128K)
1814 
1815 static int __init gic_acpi_parse_madt_its(struct acpi_subtable_header *header,
1816 					  const unsigned long end)
1817 {
1818 	struct acpi_madt_generic_translator *its_entry;
1819 	struct fwnode_handle *dom_handle;
1820 	struct resource res;
1821 	int err;
1822 
1823 	its_entry = (struct acpi_madt_generic_translator *)header;
1824 	memset(&res, 0, sizeof(res));
1825 	res.start = its_entry->base_address;
1826 	res.end = its_entry->base_address + ACPI_GICV3_ITS_MEM_SIZE - 1;
1827 	res.flags = IORESOURCE_MEM;
1828 
1829 	dom_handle = irq_domain_alloc_fwnode((void *)its_entry->base_address);
1830 	if (!dom_handle) {
1831 		pr_err("ITS@%pa: Unable to allocate GICv3 ITS domain token\n",
1832 		       &res.start);
1833 		return -ENOMEM;
1834 	}
1835 
1836 	err = iort_register_domain_token(its_entry->translation_id, dom_handle);
1837 	if (err) {
1838 		pr_err("ITS@%pa: Unable to register GICv3 ITS domain token (ITS ID %d) to IORT\n",
1839 		       &res.start, its_entry->translation_id);
1840 		goto dom_err;
1841 	}
1842 
1843 	err = its_probe_one(&res, dom_handle, NUMA_NO_NODE);
1844 	if (!err)
1845 		return 0;
1846 
1847 	iort_deregister_domain_token(its_entry->translation_id);
1848 dom_err:
1849 	irq_domain_free_fwnode(dom_handle);
1850 	return err;
1851 }
1852 
1853 static void __init its_acpi_probe(void)
1854 {
1855 	acpi_table_parse_madt(ACPI_MADT_TYPE_GENERIC_TRANSLATOR,
1856 			      gic_acpi_parse_madt_its, 0);
1857 }
1858 #else
1859 static void __init its_acpi_probe(void) { }
1860 #endif
1861 
1862 int __init its_init(struct fwnode_handle *handle, struct rdists *rdists,
1863 		    struct irq_domain *parent_domain)
1864 {
1865 	struct device_node *of_node;
1866 
1867 	its_parent = parent_domain;
1868 	of_node = to_of_node(handle);
1869 	if (of_node)
1870 		its_of_probe(of_node);
1871 	else
1872 		its_acpi_probe();
1873 
1874 	if (list_empty(&its_nodes)) {
1875 		pr_warn("ITS: No ITS available, not enabling LPIs\n");
1876 		return -ENXIO;
1877 	}
1878 
1879 	gic_rdists = rdists;
1880 	its_alloc_lpi_tables();
1881 	its_lpi_init(rdists->id_bits);
1882 
1883 	return 0;
1884 }
1885