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