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