irqchip/gic-v3-its: Move allocation outside mutex
[sfrench/cifs-2.6.git] / drivers / irqchip / irq-gic-v3-its.c
1 /*
2  * Copyright (C) 2013-2017 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/acpi_iort.h>
20 #include <linux/bitmap.h>
21 #include <linux/cpu.h>
22 #include <linux/crash_dump.h>
23 #include <linux/delay.h>
24 #include <linux/dma-iommu.h>
25 #include <linux/efi.h>
26 #include <linux/interrupt.h>
27 #include <linux/irqdomain.h>
28 #include <linux/list.h>
29 #include <linux/list_sort.h>
30 #include <linux/log2.h>
31 #include <linux/memblock.h>
32 #include <linux/mm.h>
33 #include <linux/msi.h>
34 #include <linux/of.h>
35 #include <linux/of_address.h>
36 #include <linux/of_irq.h>
37 #include <linux/of_pci.h>
38 #include <linux/of_platform.h>
39 #include <linux/percpu.h>
40 #include <linux/slab.h>
41 #include <linux/syscore_ops.h>
42
43 #include <linux/irqchip.h>
44 #include <linux/irqchip/arm-gic-v3.h>
45 #include <linux/irqchip/arm-gic-v4.h>
46
47 #include <asm/cputype.h>
48 #include <asm/exception.h>
49
50 #include "irq-gic-common.h"
51
52 #define ITS_FLAGS_CMDQ_NEEDS_FLUSHING           (1ULL << 0)
53 #define ITS_FLAGS_WORKAROUND_CAVIUM_22375       (1ULL << 1)
54 #define ITS_FLAGS_WORKAROUND_CAVIUM_23144       (1ULL << 2)
55 #define ITS_FLAGS_SAVE_SUSPEND_STATE            (1ULL << 3)
56
57 #define RDIST_FLAGS_PROPBASE_NEEDS_FLUSHING     (1 << 0)
58 #define RDIST_FLAGS_RD_TABLES_PREALLOCATED      (1 << 1)
59
60 static u32 lpi_id_bits;
61
62 /*
63  * We allocate memory for PROPBASE to cover 2 ^ lpi_id_bits LPIs to
64  * deal with (one configuration byte per interrupt). PENDBASE has to
65  * be 64kB aligned (one bit per LPI, plus 8192 bits for SPI/PPI/SGI).
66  */
67 #define LPI_NRBITS              lpi_id_bits
68 #define LPI_PROPBASE_SZ         ALIGN(BIT(LPI_NRBITS), SZ_64K)
69 #define LPI_PENDBASE_SZ         ALIGN(BIT(LPI_NRBITS) / 8, SZ_64K)
70
71 #define LPI_PROP_DEFAULT_PRIO   GICD_INT_DEF_PRI
72
73 /*
74  * Collection structure - just an ID, and a redistributor address to
75  * ping. We use one per CPU as a bag of interrupts assigned to this
76  * CPU.
77  */
78 struct its_collection {
79         u64                     target_address;
80         u16                     col_id;
81 };
82
83 /*
84  * The ITS_BASER structure - contains memory information, cached
85  * value of BASER register configuration and ITS page size.
86  */
87 struct its_baser {
88         void            *base;
89         u64             val;
90         u32             order;
91         u32             psz;
92 };
93
94 struct its_device;
95
96 /*
97  * The ITS structure - contains most of the infrastructure, with the
98  * top-level MSI domain, the command queue, the collections, and the
99  * list of devices writing to it.
100  *
101  * dev_alloc_lock has to be taken for device allocations, while the
102  * spinlock must be taken to parse data structures such as the device
103  * list.
104  */
105 struct its_node {
106         raw_spinlock_t          lock;
107         struct mutex            dev_alloc_lock;
108         struct list_head        entry;
109         void __iomem            *base;
110         phys_addr_t             phys_base;
111         struct its_cmd_block    *cmd_base;
112         struct its_cmd_block    *cmd_write;
113         struct its_baser        tables[GITS_BASER_NR_REGS];
114         struct its_collection   *collections;
115         struct fwnode_handle    *fwnode_handle;
116         u64                     (*get_msi_base)(struct its_device *its_dev);
117         u64                     cbaser_save;
118         u32                     ctlr_save;
119         struct list_head        its_device_list;
120         u64                     flags;
121         unsigned long           list_nr;
122         u32                     ite_size;
123         u32                     device_ids;
124         int                     numa_node;
125         unsigned int            msi_domain_flags;
126         u32                     pre_its_base; /* for Socionext Synquacer */
127         bool                    is_v4;
128         int                     vlpi_redist_offset;
129 };
130
131 #define ITS_ITT_ALIGN           SZ_256
132
133 /* The maximum number of VPEID bits supported by VLPI commands */
134 #define ITS_MAX_VPEID_BITS      (16)
135 #define ITS_MAX_VPEID           (1 << (ITS_MAX_VPEID_BITS))
136
137 /* Convert page order to size in bytes */
138 #define PAGE_ORDER_TO_SIZE(o)   (PAGE_SIZE << (o))
139
140 struct event_lpi_map {
141         unsigned long           *lpi_map;
142         u16                     *col_map;
143         irq_hw_number_t         lpi_base;
144         int                     nr_lpis;
145         struct mutex            vlpi_lock;
146         struct its_vm           *vm;
147         struct its_vlpi_map     *vlpi_maps;
148         int                     nr_vlpis;
149 };
150
151 /*
152  * The ITS view of a device - belongs to an ITS, owns an interrupt
153  * translation table, and a list of interrupts.  If it some of its
154  * LPIs are injected into a guest (GICv4), the event_map.vm field
155  * indicates which one.
156  */
157 struct its_device {
158         struct list_head        entry;
159         struct its_node         *its;
160         struct event_lpi_map    event_map;
161         void                    *itt;
162         u32                     nr_ites;
163         u32                     device_id;
164         bool                    shared;
165 };
166
167 static struct {
168         raw_spinlock_t          lock;
169         struct its_device       *dev;
170         struct its_vpe          **vpes;
171         int                     next_victim;
172 } vpe_proxy;
173
174 static LIST_HEAD(its_nodes);
175 static DEFINE_RAW_SPINLOCK(its_lock);
176 static struct rdists *gic_rdists;
177 static struct irq_domain *its_parent;
178
179 static unsigned long its_list_map;
180 static u16 vmovp_seq_num;
181 static DEFINE_RAW_SPINLOCK(vmovp_lock);
182
183 static DEFINE_IDA(its_vpeid_ida);
184
185 #define gic_data_rdist()                (raw_cpu_ptr(gic_rdists->rdist))
186 #define gic_data_rdist_cpu(cpu)         (per_cpu_ptr(gic_rdists->rdist, cpu))
187 #define gic_data_rdist_rd_base()        (gic_data_rdist()->rd_base)
188 #define gic_data_rdist_vlpi_base()      (gic_data_rdist_rd_base() + SZ_128K)
189
190 static struct its_collection *dev_event_to_col(struct its_device *its_dev,
191                                                u32 event)
192 {
193         struct its_node *its = its_dev->its;
194
195         return its->collections + its_dev->event_map.col_map[event];
196 }
197
198 static struct its_collection *valid_col(struct its_collection *col)
199 {
200         if (WARN_ON_ONCE(col->target_address & GENMASK_ULL(0, 15)))
201                 return NULL;
202
203         return col;
204 }
205
206 static struct its_vpe *valid_vpe(struct its_node *its, struct its_vpe *vpe)
207 {
208         if (valid_col(its->collections + vpe->col_idx))
209                 return vpe;
210
211         return NULL;
212 }
213
214 /*
215  * ITS command descriptors - parameters to be encoded in a command
216  * block.
217  */
218 struct its_cmd_desc {
219         union {
220                 struct {
221                         struct its_device *dev;
222                         u32 event_id;
223                 } its_inv_cmd;
224
225                 struct {
226                         struct its_device *dev;
227                         u32 event_id;
228                 } its_clear_cmd;
229
230                 struct {
231                         struct its_device *dev;
232                         u32 event_id;
233                 } its_int_cmd;
234
235                 struct {
236                         struct its_device *dev;
237                         int valid;
238                 } its_mapd_cmd;
239
240                 struct {
241                         struct its_collection *col;
242                         int valid;
243                 } its_mapc_cmd;
244
245                 struct {
246                         struct its_device *dev;
247                         u32 phys_id;
248                         u32 event_id;
249                 } its_mapti_cmd;
250
251                 struct {
252                         struct its_device *dev;
253                         struct its_collection *col;
254                         u32 event_id;
255                 } its_movi_cmd;
256
257                 struct {
258                         struct its_device *dev;
259                         u32 event_id;
260                 } its_discard_cmd;
261
262                 struct {
263                         struct its_collection *col;
264                 } its_invall_cmd;
265
266                 struct {
267                         struct its_vpe *vpe;
268                 } its_vinvall_cmd;
269
270                 struct {
271                         struct its_vpe *vpe;
272                         struct its_collection *col;
273                         bool valid;
274                 } its_vmapp_cmd;
275
276                 struct {
277                         struct its_vpe *vpe;
278                         struct its_device *dev;
279                         u32 virt_id;
280                         u32 event_id;
281                         bool db_enabled;
282                 } its_vmapti_cmd;
283
284                 struct {
285                         struct its_vpe *vpe;
286                         struct its_device *dev;
287                         u32 event_id;
288                         bool db_enabled;
289                 } its_vmovi_cmd;
290
291                 struct {
292                         struct its_vpe *vpe;
293                         struct its_collection *col;
294                         u16 seq_num;
295                         u16 its_list;
296                 } its_vmovp_cmd;
297         };
298 };
299
300 /*
301  * The ITS command block, which is what the ITS actually parses.
302  */
303 struct its_cmd_block {
304         u64     raw_cmd[4];
305 };
306
307 #define ITS_CMD_QUEUE_SZ                SZ_64K
308 #define ITS_CMD_QUEUE_NR_ENTRIES        (ITS_CMD_QUEUE_SZ / sizeof(struct its_cmd_block))
309
310 typedef struct its_collection *(*its_cmd_builder_t)(struct its_node *,
311                                                     struct its_cmd_block *,
312                                                     struct its_cmd_desc *);
313
314 typedef struct its_vpe *(*its_cmd_vbuilder_t)(struct its_node *,
315                                               struct its_cmd_block *,
316                                               struct its_cmd_desc *);
317
318 static void its_mask_encode(u64 *raw_cmd, u64 val, int h, int l)
319 {
320         u64 mask = GENMASK_ULL(h, l);
321         *raw_cmd &= ~mask;
322         *raw_cmd |= (val << l) & mask;
323 }
324
325 static void its_encode_cmd(struct its_cmd_block *cmd, u8 cmd_nr)
326 {
327         its_mask_encode(&cmd->raw_cmd[0], cmd_nr, 7, 0);
328 }
329
330 static void its_encode_devid(struct its_cmd_block *cmd, u32 devid)
331 {
332         its_mask_encode(&cmd->raw_cmd[0], devid, 63, 32);
333 }
334
335 static void its_encode_event_id(struct its_cmd_block *cmd, u32 id)
336 {
337         its_mask_encode(&cmd->raw_cmd[1], id, 31, 0);
338 }
339
340 static void its_encode_phys_id(struct its_cmd_block *cmd, u32 phys_id)
341 {
342         its_mask_encode(&cmd->raw_cmd[1], phys_id, 63, 32);
343 }
344
345 static void its_encode_size(struct its_cmd_block *cmd, u8 size)
346 {
347         its_mask_encode(&cmd->raw_cmd[1], size, 4, 0);
348 }
349
350 static void its_encode_itt(struct its_cmd_block *cmd, u64 itt_addr)
351 {
352         its_mask_encode(&cmd->raw_cmd[2], itt_addr >> 8, 51, 8);
353 }
354
355 static void its_encode_valid(struct its_cmd_block *cmd, int valid)
356 {
357         its_mask_encode(&cmd->raw_cmd[2], !!valid, 63, 63);
358 }
359
360 static void its_encode_target(struct its_cmd_block *cmd, u64 target_addr)
361 {
362         its_mask_encode(&cmd->raw_cmd[2], target_addr >> 16, 51, 16);
363 }
364
365 static void its_encode_collection(struct its_cmd_block *cmd, u16 col)
366 {
367         its_mask_encode(&cmd->raw_cmd[2], col, 15, 0);
368 }
369
370 static void its_encode_vpeid(struct its_cmd_block *cmd, u16 vpeid)
371 {
372         its_mask_encode(&cmd->raw_cmd[1], vpeid, 47, 32);
373 }
374
375 static void its_encode_virt_id(struct its_cmd_block *cmd, u32 virt_id)
376 {
377         its_mask_encode(&cmd->raw_cmd[2], virt_id, 31, 0);
378 }
379
380 static void its_encode_db_phys_id(struct its_cmd_block *cmd, u32 db_phys_id)
381 {
382         its_mask_encode(&cmd->raw_cmd[2], db_phys_id, 63, 32);
383 }
384
385 static void its_encode_db_valid(struct its_cmd_block *cmd, bool db_valid)
386 {
387         its_mask_encode(&cmd->raw_cmd[2], db_valid, 0, 0);
388 }
389
390 static void its_encode_seq_num(struct its_cmd_block *cmd, u16 seq_num)
391 {
392         its_mask_encode(&cmd->raw_cmd[0], seq_num, 47, 32);
393 }
394
395 static void its_encode_its_list(struct its_cmd_block *cmd, u16 its_list)
396 {
397         its_mask_encode(&cmd->raw_cmd[1], its_list, 15, 0);
398 }
399
400 static void its_encode_vpt_addr(struct its_cmd_block *cmd, u64 vpt_pa)
401 {
402         its_mask_encode(&cmd->raw_cmd[3], vpt_pa >> 16, 51, 16);
403 }
404
405 static void its_encode_vpt_size(struct its_cmd_block *cmd, u8 vpt_size)
406 {
407         its_mask_encode(&cmd->raw_cmd[3], vpt_size, 4, 0);
408 }
409
410 static inline void its_fixup_cmd(struct its_cmd_block *cmd)
411 {
412         /* Let's fixup BE commands */
413         cmd->raw_cmd[0] = cpu_to_le64(cmd->raw_cmd[0]);
414         cmd->raw_cmd[1] = cpu_to_le64(cmd->raw_cmd[1]);
415         cmd->raw_cmd[2] = cpu_to_le64(cmd->raw_cmd[2]);
416         cmd->raw_cmd[3] = cpu_to_le64(cmd->raw_cmd[3]);
417 }
418
419 static struct its_collection *its_build_mapd_cmd(struct its_node *its,
420                                                  struct its_cmd_block *cmd,
421                                                  struct its_cmd_desc *desc)
422 {
423         unsigned long itt_addr;
424         u8 size = ilog2(desc->its_mapd_cmd.dev->nr_ites);
425
426         itt_addr = virt_to_phys(desc->its_mapd_cmd.dev->itt);
427         itt_addr = ALIGN(itt_addr, ITS_ITT_ALIGN);
428
429         its_encode_cmd(cmd, GITS_CMD_MAPD);
430         its_encode_devid(cmd, desc->its_mapd_cmd.dev->device_id);
431         its_encode_size(cmd, size - 1);
432         its_encode_itt(cmd, itt_addr);
433         its_encode_valid(cmd, desc->its_mapd_cmd.valid);
434
435         its_fixup_cmd(cmd);
436
437         return NULL;
438 }
439
440 static struct its_collection *its_build_mapc_cmd(struct its_node *its,
441                                                  struct its_cmd_block *cmd,
442                                                  struct its_cmd_desc *desc)
443 {
444         its_encode_cmd(cmd, GITS_CMD_MAPC);
445         its_encode_collection(cmd, desc->its_mapc_cmd.col->col_id);
446         its_encode_target(cmd, desc->its_mapc_cmd.col->target_address);
447         its_encode_valid(cmd, desc->its_mapc_cmd.valid);
448
449         its_fixup_cmd(cmd);
450
451         return desc->its_mapc_cmd.col;
452 }
453
454 static struct its_collection *its_build_mapti_cmd(struct its_node *its,
455                                                   struct its_cmd_block *cmd,
456                                                   struct its_cmd_desc *desc)
457 {
458         struct its_collection *col;
459
460         col = dev_event_to_col(desc->its_mapti_cmd.dev,
461                                desc->its_mapti_cmd.event_id);
462
463         its_encode_cmd(cmd, GITS_CMD_MAPTI);
464         its_encode_devid(cmd, desc->its_mapti_cmd.dev->device_id);
465         its_encode_event_id(cmd, desc->its_mapti_cmd.event_id);
466         its_encode_phys_id(cmd, desc->its_mapti_cmd.phys_id);
467         its_encode_collection(cmd, col->col_id);
468
469         its_fixup_cmd(cmd);
470
471         return valid_col(col);
472 }
473
474 static struct its_collection *its_build_movi_cmd(struct its_node *its,
475                                                  struct its_cmd_block *cmd,
476                                                  struct its_cmd_desc *desc)
477 {
478         struct its_collection *col;
479
480         col = dev_event_to_col(desc->its_movi_cmd.dev,
481                                desc->its_movi_cmd.event_id);
482
483         its_encode_cmd(cmd, GITS_CMD_MOVI);
484         its_encode_devid(cmd, desc->its_movi_cmd.dev->device_id);
485         its_encode_event_id(cmd, desc->its_movi_cmd.event_id);
486         its_encode_collection(cmd, desc->its_movi_cmd.col->col_id);
487
488         its_fixup_cmd(cmd);
489
490         return valid_col(col);
491 }
492
493 static struct its_collection *its_build_discard_cmd(struct its_node *its,
494                                                     struct its_cmd_block *cmd,
495                                                     struct its_cmd_desc *desc)
496 {
497         struct its_collection *col;
498
499         col = dev_event_to_col(desc->its_discard_cmd.dev,
500                                desc->its_discard_cmd.event_id);
501
502         its_encode_cmd(cmd, GITS_CMD_DISCARD);
503         its_encode_devid(cmd, desc->its_discard_cmd.dev->device_id);
504         its_encode_event_id(cmd, desc->its_discard_cmd.event_id);
505
506         its_fixup_cmd(cmd);
507
508         return valid_col(col);
509 }
510
511 static struct its_collection *its_build_inv_cmd(struct its_node *its,
512                                                 struct its_cmd_block *cmd,
513                                                 struct its_cmd_desc *desc)
514 {
515         struct its_collection *col;
516
517         col = dev_event_to_col(desc->its_inv_cmd.dev,
518                                desc->its_inv_cmd.event_id);
519
520         its_encode_cmd(cmd, GITS_CMD_INV);
521         its_encode_devid(cmd, desc->its_inv_cmd.dev->device_id);
522         its_encode_event_id(cmd, desc->its_inv_cmd.event_id);
523
524         its_fixup_cmd(cmd);
525
526         return valid_col(col);
527 }
528
529 static struct its_collection *its_build_int_cmd(struct its_node *its,
530                                                 struct its_cmd_block *cmd,
531                                                 struct its_cmd_desc *desc)
532 {
533         struct its_collection *col;
534
535         col = dev_event_to_col(desc->its_int_cmd.dev,
536                                desc->its_int_cmd.event_id);
537
538         its_encode_cmd(cmd, GITS_CMD_INT);
539         its_encode_devid(cmd, desc->its_int_cmd.dev->device_id);
540         its_encode_event_id(cmd, desc->its_int_cmd.event_id);
541
542         its_fixup_cmd(cmd);
543
544         return valid_col(col);
545 }
546
547 static struct its_collection *its_build_clear_cmd(struct its_node *its,
548                                                   struct its_cmd_block *cmd,
549                                                   struct its_cmd_desc *desc)
550 {
551         struct its_collection *col;
552
553         col = dev_event_to_col(desc->its_clear_cmd.dev,
554                                desc->its_clear_cmd.event_id);
555
556         its_encode_cmd(cmd, GITS_CMD_CLEAR);
557         its_encode_devid(cmd, desc->its_clear_cmd.dev->device_id);
558         its_encode_event_id(cmd, desc->its_clear_cmd.event_id);
559
560         its_fixup_cmd(cmd);
561
562         return valid_col(col);
563 }
564
565 static struct its_collection *its_build_invall_cmd(struct its_node *its,
566                                                    struct its_cmd_block *cmd,
567                                                    struct its_cmd_desc *desc)
568 {
569         its_encode_cmd(cmd, GITS_CMD_INVALL);
570         its_encode_collection(cmd, desc->its_mapc_cmd.col->col_id);
571
572         its_fixup_cmd(cmd);
573
574         return NULL;
575 }
576
577 static struct its_vpe *its_build_vinvall_cmd(struct its_node *its,
578                                              struct its_cmd_block *cmd,
579                                              struct its_cmd_desc *desc)
580 {
581         its_encode_cmd(cmd, GITS_CMD_VINVALL);
582         its_encode_vpeid(cmd, desc->its_vinvall_cmd.vpe->vpe_id);
583
584         its_fixup_cmd(cmd);
585
586         return valid_vpe(its, desc->its_vinvall_cmd.vpe);
587 }
588
589 static struct its_vpe *its_build_vmapp_cmd(struct its_node *its,
590                                            struct its_cmd_block *cmd,
591                                            struct its_cmd_desc *desc)
592 {
593         unsigned long vpt_addr;
594         u64 target;
595
596         vpt_addr = virt_to_phys(page_address(desc->its_vmapp_cmd.vpe->vpt_page));
597         target = desc->its_vmapp_cmd.col->target_address + its->vlpi_redist_offset;
598
599         its_encode_cmd(cmd, GITS_CMD_VMAPP);
600         its_encode_vpeid(cmd, desc->its_vmapp_cmd.vpe->vpe_id);
601         its_encode_valid(cmd, desc->its_vmapp_cmd.valid);
602         its_encode_target(cmd, target);
603         its_encode_vpt_addr(cmd, vpt_addr);
604         its_encode_vpt_size(cmd, LPI_NRBITS - 1);
605
606         its_fixup_cmd(cmd);
607
608         return valid_vpe(its, desc->its_vmapp_cmd.vpe);
609 }
610
611 static struct its_vpe *its_build_vmapti_cmd(struct its_node *its,
612                                             struct its_cmd_block *cmd,
613                                             struct its_cmd_desc *desc)
614 {
615         u32 db;
616
617         if (desc->its_vmapti_cmd.db_enabled)
618                 db = desc->its_vmapti_cmd.vpe->vpe_db_lpi;
619         else
620                 db = 1023;
621
622         its_encode_cmd(cmd, GITS_CMD_VMAPTI);
623         its_encode_devid(cmd, desc->its_vmapti_cmd.dev->device_id);
624         its_encode_vpeid(cmd, desc->its_vmapti_cmd.vpe->vpe_id);
625         its_encode_event_id(cmd, desc->its_vmapti_cmd.event_id);
626         its_encode_db_phys_id(cmd, db);
627         its_encode_virt_id(cmd, desc->its_vmapti_cmd.virt_id);
628
629         its_fixup_cmd(cmd);
630
631         return valid_vpe(its, desc->its_vmapti_cmd.vpe);
632 }
633
634 static struct its_vpe *its_build_vmovi_cmd(struct its_node *its,
635                                            struct its_cmd_block *cmd,
636                                            struct its_cmd_desc *desc)
637 {
638         u32 db;
639
640         if (desc->its_vmovi_cmd.db_enabled)
641                 db = desc->its_vmovi_cmd.vpe->vpe_db_lpi;
642         else
643                 db = 1023;
644
645         its_encode_cmd(cmd, GITS_CMD_VMOVI);
646         its_encode_devid(cmd, desc->its_vmovi_cmd.dev->device_id);
647         its_encode_vpeid(cmd, desc->its_vmovi_cmd.vpe->vpe_id);
648         its_encode_event_id(cmd, desc->its_vmovi_cmd.event_id);
649         its_encode_db_phys_id(cmd, db);
650         its_encode_db_valid(cmd, true);
651
652         its_fixup_cmd(cmd);
653
654         return valid_vpe(its, desc->its_vmovi_cmd.vpe);
655 }
656
657 static struct its_vpe *its_build_vmovp_cmd(struct its_node *its,
658                                            struct its_cmd_block *cmd,
659                                            struct its_cmd_desc *desc)
660 {
661         u64 target;
662
663         target = desc->its_vmovp_cmd.col->target_address + its->vlpi_redist_offset;
664         its_encode_cmd(cmd, GITS_CMD_VMOVP);
665         its_encode_seq_num(cmd, desc->its_vmovp_cmd.seq_num);
666         its_encode_its_list(cmd, desc->its_vmovp_cmd.its_list);
667         its_encode_vpeid(cmd, desc->its_vmovp_cmd.vpe->vpe_id);
668         its_encode_target(cmd, target);
669
670         its_fixup_cmd(cmd);
671
672         return valid_vpe(its, desc->its_vmovp_cmd.vpe);
673 }
674
675 static u64 its_cmd_ptr_to_offset(struct its_node *its,
676                                  struct its_cmd_block *ptr)
677 {
678         return (ptr - its->cmd_base) * sizeof(*ptr);
679 }
680
681 static int its_queue_full(struct its_node *its)
682 {
683         int widx;
684         int ridx;
685
686         widx = its->cmd_write - its->cmd_base;
687         ridx = readl_relaxed(its->base + GITS_CREADR) / sizeof(struct its_cmd_block);
688
689         /* This is incredibly unlikely to happen, unless the ITS locks up. */
690         if (((widx + 1) % ITS_CMD_QUEUE_NR_ENTRIES) == ridx)
691                 return 1;
692
693         return 0;
694 }
695
696 static struct its_cmd_block *its_allocate_entry(struct its_node *its)
697 {
698         struct its_cmd_block *cmd;
699         u32 count = 1000000;    /* 1s! */
700
701         while (its_queue_full(its)) {
702                 count--;
703                 if (!count) {
704                         pr_err_ratelimited("ITS queue not draining\n");
705                         return NULL;
706                 }
707                 cpu_relax();
708                 udelay(1);
709         }
710
711         cmd = its->cmd_write++;
712
713         /* Handle queue wrapping */
714         if (its->cmd_write == (its->cmd_base + ITS_CMD_QUEUE_NR_ENTRIES))
715                 its->cmd_write = its->cmd_base;
716
717         /* Clear command  */
718         cmd->raw_cmd[0] = 0;
719         cmd->raw_cmd[1] = 0;
720         cmd->raw_cmd[2] = 0;
721         cmd->raw_cmd[3] = 0;
722
723         return cmd;
724 }
725
726 static struct its_cmd_block *its_post_commands(struct its_node *its)
727 {
728         u64 wr = its_cmd_ptr_to_offset(its, its->cmd_write);
729
730         writel_relaxed(wr, its->base + GITS_CWRITER);
731
732         return its->cmd_write;
733 }
734
735 static void its_flush_cmd(struct its_node *its, struct its_cmd_block *cmd)
736 {
737         /*
738          * Make sure the commands written to memory are observable by
739          * the ITS.
740          */
741         if (its->flags & ITS_FLAGS_CMDQ_NEEDS_FLUSHING)
742                 gic_flush_dcache_to_poc(cmd, sizeof(*cmd));
743         else
744                 dsb(ishst);
745 }
746
747 static int its_wait_for_range_completion(struct its_node *its,
748                                          struct its_cmd_block *from,
749                                          struct its_cmd_block *to)
750 {
751         u64 rd_idx, from_idx, to_idx;
752         u32 count = 1000000;    /* 1s! */
753
754         from_idx = its_cmd_ptr_to_offset(its, from);
755         to_idx = its_cmd_ptr_to_offset(its, to);
756
757         while (1) {
758                 rd_idx = readl_relaxed(its->base + GITS_CREADR);
759
760                 /* Direct case */
761                 if (from_idx < to_idx && rd_idx >= to_idx)
762                         break;
763
764                 /* Wrapped case */
765                 if (from_idx >= to_idx && rd_idx >= to_idx && rd_idx < from_idx)
766                         break;
767
768                 count--;
769                 if (!count) {
770                         pr_err_ratelimited("ITS queue timeout (%llu %llu %llu)\n",
771                                            from_idx, to_idx, rd_idx);
772                         return -1;
773                 }
774                 cpu_relax();
775                 udelay(1);
776         }
777
778         return 0;
779 }
780
781 /* Warning, macro hell follows */
782 #define BUILD_SINGLE_CMD_FUNC(name, buildtype, synctype, buildfn)       \
783 void name(struct its_node *its,                                         \
784           buildtype builder,                                            \
785           struct its_cmd_desc *desc)                                    \
786 {                                                                       \
787         struct its_cmd_block *cmd, *sync_cmd, *next_cmd;                \
788         synctype *sync_obj;                                             \
789         unsigned long flags;                                            \
790                                                                         \
791         raw_spin_lock_irqsave(&its->lock, flags);                       \
792                                                                         \
793         cmd = its_allocate_entry(its);                                  \
794         if (!cmd) {             /* We're soooooo screewed... */         \
795                 raw_spin_unlock_irqrestore(&its->lock, flags);          \
796                 return;                                                 \
797         }                                                               \
798         sync_obj = builder(its, cmd, desc);                             \
799         its_flush_cmd(its, cmd);                                        \
800                                                                         \
801         if (sync_obj) {                                                 \
802                 sync_cmd = its_allocate_entry(its);                     \
803                 if (!sync_cmd)                                          \
804                         goto post;                                      \
805                                                                         \
806                 buildfn(its, sync_cmd, sync_obj);                       \
807                 its_flush_cmd(its, sync_cmd);                           \
808         }                                                               \
809                                                                         \
810 post:                                                                   \
811         next_cmd = its_post_commands(its);                              \
812         raw_spin_unlock_irqrestore(&its->lock, flags);                  \
813                                                                         \
814         if (its_wait_for_range_completion(its, cmd, next_cmd))          \
815                 pr_err_ratelimited("ITS cmd %ps failed\n", builder);    \
816 }
817
818 static void its_build_sync_cmd(struct its_node *its,
819                                struct its_cmd_block *sync_cmd,
820                                struct its_collection *sync_col)
821 {
822         its_encode_cmd(sync_cmd, GITS_CMD_SYNC);
823         its_encode_target(sync_cmd, sync_col->target_address);
824
825         its_fixup_cmd(sync_cmd);
826 }
827
828 static BUILD_SINGLE_CMD_FUNC(its_send_single_command, its_cmd_builder_t,
829                              struct its_collection, its_build_sync_cmd)
830
831 static void its_build_vsync_cmd(struct its_node *its,
832                                 struct its_cmd_block *sync_cmd,
833                                 struct its_vpe *sync_vpe)
834 {
835         its_encode_cmd(sync_cmd, GITS_CMD_VSYNC);
836         its_encode_vpeid(sync_cmd, sync_vpe->vpe_id);
837
838         its_fixup_cmd(sync_cmd);
839 }
840
841 static BUILD_SINGLE_CMD_FUNC(its_send_single_vcommand, its_cmd_vbuilder_t,
842                              struct its_vpe, its_build_vsync_cmd)
843
844 static void its_send_int(struct its_device *dev, u32 event_id)
845 {
846         struct its_cmd_desc desc;
847
848         desc.its_int_cmd.dev = dev;
849         desc.its_int_cmd.event_id = event_id;
850
851         its_send_single_command(dev->its, its_build_int_cmd, &desc);
852 }
853
854 static void its_send_clear(struct its_device *dev, u32 event_id)
855 {
856         struct its_cmd_desc desc;
857
858         desc.its_clear_cmd.dev = dev;
859         desc.its_clear_cmd.event_id = event_id;
860
861         its_send_single_command(dev->its, its_build_clear_cmd, &desc);
862 }
863
864 static void its_send_inv(struct its_device *dev, u32 event_id)
865 {
866         struct its_cmd_desc desc;
867
868         desc.its_inv_cmd.dev = dev;
869         desc.its_inv_cmd.event_id = event_id;
870
871         its_send_single_command(dev->its, its_build_inv_cmd, &desc);
872 }
873
874 static void its_send_mapd(struct its_device *dev, int valid)
875 {
876         struct its_cmd_desc desc;
877
878         desc.its_mapd_cmd.dev = dev;
879         desc.its_mapd_cmd.valid = !!valid;
880
881         its_send_single_command(dev->its, its_build_mapd_cmd, &desc);
882 }
883
884 static void its_send_mapc(struct its_node *its, struct its_collection *col,
885                           int valid)
886 {
887         struct its_cmd_desc desc;
888
889         desc.its_mapc_cmd.col = col;
890         desc.its_mapc_cmd.valid = !!valid;
891
892         its_send_single_command(its, its_build_mapc_cmd, &desc);
893 }
894
895 static void its_send_mapti(struct its_device *dev, u32 irq_id, u32 id)
896 {
897         struct its_cmd_desc desc;
898
899         desc.its_mapti_cmd.dev = dev;
900         desc.its_mapti_cmd.phys_id = irq_id;
901         desc.its_mapti_cmd.event_id = id;
902
903         its_send_single_command(dev->its, its_build_mapti_cmd, &desc);
904 }
905
906 static void its_send_movi(struct its_device *dev,
907                           struct its_collection *col, u32 id)
908 {
909         struct its_cmd_desc desc;
910
911         desc.its_movi_cmd.dev = dev;
912         desc.its_movi_cmd.col = col;
913         desc.its_movi_cmd.event_id = id;
914
915         its_send_single_command(dev->its, its_build_movi_cmd, &desc);
916 }
917
918 static void its_send_discard(struct its_device *dev, u32 id)
919 {
920         struct its_cmd_desc desc;
921
922         desc.its_discard_cmd.dev = dev;
923         desc.its_discard_cmd.event_id = id;
924
925         its_send_single_command(dev->its, its_build_discard_cmd, &desc);
926 }
927
928 static void its_send_invall(struct its_node *its, struct its_collection *col)
929 {
930         struct its_cmd_desc desc;
931
932         desc.its_invall_cmd.col = col;
933
934         its_send_single_command(its, its_build_invall_cmd, &desc);
935 }
936
937 static void its_send_vmapti(struct its_device *dev, u32 id)
938 {
939         struct its_vlpi_map *map = &dev->event_map.vlpi_maps[id];
940         struct its_cmd_desc desc;
941
942         desc.its_vmapti_cmd.vpe = map->vpe;
943         desc.its_vmapti_cmd.dev = dev;
944         desc.its_vmapti_cmd.virt_id = map->vintid;
945         desc.its_vmapti_cmd.event_id = id;
946         desc.its_vmapti_cmd.db_enabled = map->db_enabled;
947
948         its_send_single_vcommand(dev->its, its_build_vmapti_cmd, &desc);
949 }
950
951 static void its_send_vmovi(struct its_device *dev, u32 id)
952 {
953         struct its_vlpi_map *map = &dev->event_map.vlpi_maps[id];
954         struct its_cmd_desc desc;
955
956         desc.its_vmovi_cmd.vpe = map->vpe;
957         desc.its_vmovi_cmd.dev = dev;
958         desc.its_vmovi_cmd.event_id = id;
959         desc.its_vmovi_cmd.db_enabled = map->db_enabled;
960
961         its_send_single_vcommand(dev->its, its_build_vmovi_cmd, &desc);
962 }
963
964 static void its_send_vmapp(struct its_node *its,
965                            struct its_vpe *vpe, bool valid)
966 {
967         struct its_cmd_desc desc;
968
969         desc.its_vmapp_cmd.vpe = vpe;
970         desc.its_vmapp_cmd.valid = valid;
971         desc.its_vmapp_cmd.col = &its->collections[vpe->col_idx];
972
973         its_send_single_vcommand(its, its_build_vmapp_cmd, &desc);
974 }
975
976 static void its_send_vmovp(struct its_vpe *vpe)
977 {
978         struct its_cmd_desc desc;
979         struct its_node *its;
980         unsigned long flags;
981         int col_id = vpe->col_idx;
982
983         desc.its_vmovp_cmd.vpe = vpe;
984         desc.its_vmovp_cmd.its_list = (u16)its_list_map;
985
986         if (!its_list_map) {
987                 its = list_first_entry(&its_nodes, struct its_node, entry);
988                 desc.its_vmovp_cmd.seq_num = 0;
989                 desc.its_vmovp_cmd.col = &its->collections[col_id];
990                 its_send_single_vcommand(its, its_build_vmovp_cmd, &desc);
991                 return;
992         }
993
994         /*
995          * Yet another marvel of the architecture. If using the
996          * its_list "feature", we need to make sure that all ITSs
997          * receive all VMOVP commands in the same order. The only way
998          * to guarantee this is to make vmovp a serialization point.
999          *
1000          * Wall <-- Head.
1001          */
1002         raw_spin_lock_irqsave(&vmovp_lock, flags);
1003
1004         desc.its_vmovp_cmd.seq_num = vmovp_seq_num++;
1005
1006         /* Emit VMOVPs */
1007         list_for_each_entry(its, &its_nodes, entry) {
1008                 if (!its->is_v4)
1009                         continue;
1010
1011                 if (!vpe->its_vm->vlpi_count[its->list_nr])
1012                         continue;
1013
1014                 desc.its_vmovp_cmd.col = &its->collections[col_id];
1015                 its_send_single_vcommand(its, its_build_vmovp_cmd, &desc);
1016         }
1017
1018         raw_spin_unlock_irqrestore(&vmovp_lock, flags);
1019 }
1020
1021 static void its_send_vinvall(struct its_node *its, struct its_vpe *vpe)
1022 {
1023         struct its_cmd_desc desc;
1024
1025         desc.its_vinvall_cmd.vpe = vpe;
1026         its_send_single_vcommand(its, its_build_vinvall_cmd, &desc);
1027 }
1028
1029 /*
1030  * irqchip functions - assumes MSI, mostly.
1031  */
1032
1033 static inline u32 its_get_event_id(struct irq_data *d)
1034 {
1035         struct its_device *its_dev = irq_data_get_irq_chip_data(d);
1036         return d->hwirq - its_dev->event_map.lpi_base;
1037 }
1038
1039 static void lpi_write_config(struct irq_data *d, u8 clr, u8 set)
1040 {
1041         irq_hw_number_t hwirq;
1042         void *va;
1043         u8 *cfg;
1044
1045         if (irqd_is_forwarded_to_vcpu(d)) {
1046                 struct its_device *its_dev = irq_data_get_irq_chip_data(d);
1047                 u32 event = its_get_event_id(d);
1048                 struct its_vlpi_map *map;
1049
1050                 va = page_address(its_dev->event_map.vm->vprop_page);
1051                 map = &its_dev->event_map.vlpi_maps[event];
1052                 hwirq = map->vintid;
1053
1054                 /* Remember the updated property */
1055                 map->properties &= ~clr;
1056                 map->properties |= set | LPI_PROP_GROUP1;
1057         } else {
1058                 va = gic_rdists->prop_table_va;
1059                 hwirq = d->hwirq;
1060         }
1061
1062         cfg = va + hwirq - 8192;
1063         *cfg &= ~clr;
1064         *cfg |= set | LPI_PROP_GROUP1;
1065
1066         /*
1067          * Make the above write visible to the redistributors.
1068          * And yes, we're flushing exactly: One. Single. Byte.
1069          * Humpf...
1070          */
1071         if (gic_rdists->flags & RDIST_FLAGS_PROPBASE_NEEDS_FLUSHING)
1072                 gic_flush_dcache_to_poc(cfg, sizeof(*cfg));
1073         else
1074                 dsb(ishst);
1075 }
1076
1077 static void lpi_update_config(struct irq_data *d, u8 clr, u8 set)
1078 {
1079         struct its_device *its_dev = irq_data_get_irq_chip_data(d);
1080
1081         lpi_write_config(d, clr, set);
1082         its_send_inv(its_dev, its_get_event_id(d));
1083 }
1084
1085 static void its_vlpi_set_doorbell(struct irq_data *d, bool enable)
1086 {
1087         struct its_device *its_dev = irq_data_get_irq_chip_data(d);
1088         u32 event = its_get_event_id(d);
1089
1090         if (its_dev->event_map.vlpi_maps[event].db_enabled == enable)
1091                 return;
1092
1093         its_dev->event_map.vlpi_maps[event].db_enabled = enable;
1094
1095         /*
1096          * More fun with the architecture:
1097          *
1098          * Ideally, we'd issue a VMAPTI to set the doorbell to its LPI
1099          * value or to 1023, depending on the enable bit. But that
1100          * would be issueing a mapping for an /existing/ DevID+EventID
1101          * pair, which is UNPREDICTABLE. Instead, let's issue a VMOVI
1102          * to the /same/ vPE, using this opportunity to adjust the
1103          * doorbell. Mouahahahaha. We loves it, Precious.
1104          */
1105         its_send_vmovi(its_dev, event);
1106 }
1107
1108 static void its_mask_irq(struct irq_data *d)
1109 {
1110         if (irqd_is_forwarded_to_vcpu(d))
1111                 its_vlpi_set_doorbell(d, false);
1112
1113         lpi_update_config(d, LPI_PROP_ENABLED, 0);
1114 }
1115
1116 static void its_unmask_irq(struct irq_data *d)
1117 {
1118         if (irqd_is_forwarded_to_vcpu(d))
1119                 its_vlpi_set_doorbell(d, true);
1120
1121         lpi_update_config(d, 0, LPI_PROP_ENABLED);
1122 }
1123
1124 static int its_set_affinity(struct irq_data *d, const struct cpumask *mask_val,
1125                             bool force)
1126 {
1127         unsigned int cpu;
1128         const struct cpumask *cpu_mask = cpu_online_mask;
1129         struct its_device *its_dev = irq_data_get_irq_chip_data(d);
1130         struct its_collection *target_col;
1131         u32 id = its_get_event_id(d);
1132
1133         /* A forwarded interrupt should use irq_set_vcpu_affinity */
1134         if (irqd_is_forwarded_to_vcpu(d))
1135                 return -EINVAL;
1136
1137        /* lpi cannot be routed to a redistributor that is on a foreign node */
1138         if (its_dev->its->flags & ITS_FLAGS_WORKAROUND_CAVIUM_23144) {
1139                 if (its_dev->its->numa_node >= 0) {
1140                         cpu_mask = cpumask_of_node(its_dev->its->numa_node);
1141                         if (!cpumask_intersects(mask_val, cpu_mask))
1142                                 return -EINVAL;
1143                 }
1144         }
1145
1146         cpu = cpumask_any_and(mask_val, cpu_mask);
1147
1148         if (cpu >= nr_cpu_ids)
1149                 return -EINVAL;
1150
1151         /* don't set the affinity when the target cpu is same as current one */
1152         if (cpu != its_dev->event_map.col_map[id]) {
1153                 target_col = &its_dev->its->collections[cpu];
1154                 its_send_movi(its_dev, target_col, id);
1155                 its_dev->event_map.col_map[id] = cpu;
1156                 irq_data_update_effective_affinity(d, cpumask_of(cpu));
1157         }
1158
1159         return IRQ_SET_MASK_OK_DONE;
1160 }
1161
1162 static u64 its_irq_get_msi_base(struct its_device *its_dev)
1163 {
1164         struct its_node *its = its_dev->its;
1165
1166         return its->phys_base + GITS_TRANSLATER;
1167 }
1168
1169 static void its_irq_compose_msi_msg(struct irq_data *d, struct msi_msg *msg)
1170 {
1171         struct its_device *its_dev = irq_data_get_irq_chip_data(d);
1172         struct its_node *its;
1173         u64 addr;
1174
1175         its = its_dev->its;
1176         addr = its->get_msi_base(its_dev);
1177
1178         msg->address_lo         = lower_32_bits(addr);
1179         msg->address_hi         = upper_32_bits(addr);
1180         msg->data               = its_get_event_id(d);
1181
1182         iommu_dma_map_msi_msg(d->irq, msg);
1183 }
1184
1185 static int its_irq_set_irqchip_state(struct irq_data *d,
1186                                      enum irqchip_irq_state which,
1187                                      bool state)
1188 {
1189         struct its_device *its_dev = irq_data_get_irq_chip_data(d);
1190         u32 event = its_get_event_id(d);
1191
1192         if (which != IRQCHIP_STATE_PENDING)
1193                 return -EINVAL;
1194
1195         if (state)
1196                 its_send_int(its_dev, event);
1197         else
1198                 its_send_clear(its_dev, event);
1199
1200         return 0;
1201 }
1202
1203 static void its_map_vm(struct its_node *its, struct its_vm *vm)
1204 {
1205         unsigned long flags;
1206
1207         /* Not using the ITS list? Everything is always mapped. */
1208         if (!its_list_map)
1209                 return;
1210
1211         raw_spin_lock_irqsave(&vmovp_lock, flags);
1212
1213         /*
1214          * If the VM wasn't mapped yet, iterate over the vpes and get
1215          * them mapped now.
1216          */
1217         vm->vlpi_count[its->list_nr]++;
1218
1219         if (vm->vlpi_count[its->list_nr] == 1) {
1220                 int i;
1221
1222                 for (i = 0; i < vm->nr_vpes; i++) {
1223                         struct its_vpe *vpe = vm->vpes[i];
1224                         struct irq_data *d = irq_get_irq_data(vpe->irq);
1225
1226                         /* Map the VPE to the first possible CPU */
1227                         vpe->col_idx = cpumask_first(cpu_online_mask);
1228                         its_send_vmapp(its, vpe, true);
1229                         its_send_vinvall(its, vpe);
1230                         irq_data_update_effective_affinity(d, cpumask_of(vpe->col_idx));
1231                 }
1232         }
1233
1234         raw_spin_unlock_irqrestore(&vmovp_lock, flags);
1235 }
1236
1237 static void its_unmap_vm(struct its_node *its, struct its_vm *vm)
1238 {
1239         unsigned long flags;
1240
1241         /* Not using the ITS list? Everything is always mapped. */
1242         if (!its_list_map)
1243                 return;
1244
1245         raw_spin_lock_irqsave(&vmovp_lock, flags);
1246
1247         if (!--vm->vlpi_count[its->list_nr]) {
1248                 int i;
1249
1250                 for (i = 0; i < vm->nr_vpes; i++)
1251                         its_send_vmapp(its, vm->vpes[i], false);
1252         }
1253
1254         raw_spin_unlock_irqrestore(&vmovp_lock, flags);
1255 }
1256
1257 static int its_vlpi_map(struct irq_data *d, struct its_cmd_info *info)
1258 {
1259         struct its_device *its_dev = irq_data_get_irq_chip_data(d);
1260         u32 event = its_get_event_id(d);
1261         int ret = 0;
1262
1263         if (!info->map)
1264                 return -EINVAL;
1265
1266         mutex_lock(&its_dev->event_map.vlpi_lock);
1267
1268         if (!its_dev->event_map.vm) {
1269                 struct its_vlpi_map *maps;
1270
1271                 maps = kcalloc(its_dev->event_map.nr_lpis, sizeof(*maps),
1272                                GFP_KERNEL);
1273                 if (!maps) {
1274                         ret = -ENOMEM;
1275                         goto out;
1276                 }
1277
1278                 its_dev->event_map.vm = info->map->vm;
1279                 its_dev->event_map.vlpi_maps = maps;
1280         } else if (its_dev->event_map.vm != info->map->vm) {
1281                 ret = -EINVAL;
1282                 goto out;
1283         }
1284
1285         /* Get our private copy of the mapping information */
1286         its_dev->event_map.vlpi_maps[event] = *info->map;
1287
1288         if (irqd_is_forwarded_to_vcpu(d)) {
1289                 /* Already mapped, move it around */
1290                 its_send_vmovi(its_dev, event);
1291         } else {
1292                 /* Ensure all the VPEs are mapped on this ITS */
1293                 its_map_vm(its_dev->its, info->map->vm);
1294
1295                 /*
1296                  * Flag the interrupt as forwarded so that we can
1297                  * start poking the virtual property table.
1298                  */
1299                 irqd_set_forwarded_to_vcpu(d);
1300
1301                 /* Write out the property to the prop table */
1302                 lpi_write_config(d, 0xff, info->map->properties);
1303
1304                 /* Drop the physical mapping */
1305                 its_send_discard(its_dev, event);
1306
1307                 /* and install the virtual one */
1308                 its_send_vmapti(its_dev, event);
1309
1310                 /* Increment the number of VLPIs */
1311                 its_dev->event_map.nr_vlpis++;
1312         }
1313
1314 out:
1315         mutex_unlock(&its_dev->event_map.vlpi_lock);
1316         return ret;
1317 }
1318
1319 static int its_vlpi_get(struct irq_data *d, struct its_cmd_info *info)
1320 {
1321         struct its_device *its_dev = irq_data_get_irq_chip_data(d);
1322         u32 event = its_get_event_id(d);
1323         int ret = 0;
1324
1325         mutex_lock(&its_dev->event_map.vlpi_lock);
1326
1327         if (!its_dev->event_map.vm ||
1328             !its_dev->event_map.vlpi_maps[event].vm) {
1329                 ret = -EINVAL;
1330                 goto out;
1331         }
1332
1333         /* Copy our mapping information to the incoming request */
1334         *info->map = its_dev->event_map.vlpi_maps[event];
1335
1336 out:
1337         mutex_unlock(&its_dev->event_map.vlpi_lock);
1338         return ret;
1339 }
1340
1341 static int its_vlpi_unmap(struct irq_data *d)
1342 {
1343         struct its_device *its_dev = irq_data_get_irq_chip_data(d);
1344         u32 event = its_get_event_id(d);
1345         int ret = 0;
1346
1347         mutex_lock(&its_dev->event_map.vlpi_lock);
1348
1349         if (!its_dev->event_map.vm || !irqd_is_forwarded_to_vcpu(d)) {
1350                 ret = -EINVAL;
1351                 goto out;
1352         }
1353
1354         /* Drop the virtual mapping */
1355         its_send_discard(its_dev, event);
1356
1357         /* and restore the physical one */
1358         irqd_clr_forwarded_to_vcpu(d);
1359         its_send_mapti(its_dev, d->hwirq, event);
1360         lpi_update_config(d, 0xff, (LPI_PROP_DEFAULT_PRIO |
1361                                     LPI_PROP_ENABLED |
1362                                     LPI_PROP_GROUP1));
1363
1364         /* Potentially unmap the VM from this ITS */
1365         its_unmap_vm(its_dev->its, its_dev->event_map.vm);
1366
1367         /*
1368          * Drop the refcount and make the device available again if
1369          * this was the last VLPI.
1370          */
1371         if (!--its_dev->event_map.nr_vlpis) {
1372                 its_dev->event_map.vm = NULL;
1373                 kfree(its_dev->event_map.vlpi_maps);
1374         }
1375
1376 out:
1377         mutex_unlock(&its_dev->event_map.vlpi_lock);
1378         return ret;
1379 }
1380
1381 static int its_vlpi_prop_update(struct irq_data *d, struct its_cmd_info *info)
1382 {
1383         struct its_device *its_dev = irq_data_get_irq_chip_data(d);
1384
1385         if (!its_dev->event_map.vm || !irqd_is_forwarded_to_vcpu(d))
1386                 return -EINVAL;
1387
1388         if (info->cmd_type == PROP_UPDATE_AND_INV_VLPI)
1389                 lpi_update_config(d, 0xff, info->config);
1390         else
1391                 lpi_write_config(d, 0xff, info->config);
1392         its_vlpi_set_doorbell(d, !!(info->config & LPI_PROP_ENABLED));
1393
1394         return 0;
1395 }
1396
1397 static int its_irq_set_vcpu_affinity(struct irq_data *d, void *vcpu_info)
1398 {
1399         struct its_device *its_dev = irq_data_get_irq_chip_data(d);
1400         struct its_cmd_info *info = vcpu_info;
1401
1402         /* Need a v4 ITS */
1403         if (!its_dev->its->is_v4)
1404                 return -EINVAL;
1405
1406         /* Unmap request? */
1407         if (!info)
1408                 return its_vlpi_unmap(d);
1409
1410         switch (info->cmd_type) {
1411         case MAP_VLPI:
1412                 return its_vlpi_map(d, info);
1413
1414         case GET_VLPI:
1415                 return its_vlpi_get(d, info);
1416
1417         case PROP_UPDATE_VLPI:
1418         case PROP_UPDATE_AND_INV_VLPI:
1419                 return its_vlpi_prop_update(d, info);
1420
1421         default:
1422                 return -EINVAL;
1423         }
1424 }
1425
1426 static struct irq_chip its_irq_chip = {
1427         .name                   = "ITS",
1428         .irq_mask               = its_mask_irq,
1429         .irq_unmask             = its_unmask_irq,
1430         .irq_eoi                = irq_chip_eoi_parent,
1431         .irq_set_affinity       = its_set_affinity,
1432         .irq_compose_msi_msg    = its_irq_compose_msi_msg,
1433         .irq_set_irqchip_state  = its_irq_set_irqchip_state,
1434         .irq_set_vcpu_affinity  = its_irq_set_vcpu_affinity,
1435 };
1436
1437
1438 /*
1439  * How we allocate LPIs:
1440  *
1441  * lpi_range_list contains ranges of LPIs that are to available to
1442  * allocate from. To allocate LPIs, just pick the first range that
1443  * fits the required allocation, and reduce it by the required
1444  * amount. Once empty, remove the range from the list.
1445  *
1446  * To free a range of LPIs, add a free range to the list, sort it and
1447  * merge the result if the new range happens to be adjacent to an
1448  * already free block.
1449  *
1450  * The consequence of the above is that allocation is cost is low, but
1451  * freeing is expensive. We assumes that freeing rarely occurs.
1452  */
1453 #define ITS_MAX_LPI_NRBITS      16 /* 64K LPIs */
1454
1455 static DEFINE_MUTEX(lpi_range_lock);
1456 static LIST_HEAD(lpi_range_list);
1457
1458 struct lpi_range {
1459         struct list_head        entry;
1460         u32                     base_id;
1461         u32                     span;
1462 };
1463
1464 static struct lpi_range *mk_lpi_range(u32 base, u32 span)
1465 {
1466         struct lpi_range *range;
1467
1468         range = kzalloc(sizeof(*range), GFP_KERNEL);
1469         if (range) {
1470                 INIT_LIST_HEAD(&range->entry);
1471                 range->base_id = base;
1472                 range->span = span;
1473         }
1474
1475         return range;
1476 }
1477
1478 static int lpi_range_cmp(void *priv, struct list_head *a, struct list_head *b)
1479 {
1480         struct lpi_range *ra, *rb;
1481
1482         ra = container_of(a, struct lpi_range, entry);
1483         rb = container_of(b, struct lpi_range, entry);
1484
1485         return ra->base_id - rb->base_id;
1486 }
1487
1488 static void merge_lpi_ranges(void)
1489 {
1490         struct lpi_range *range, *tmp;
1491
1492         list_for_each_entry_safe(range, tmp, &lpi_range_list, entry) {
1493                 if (!list_is_last(&range->entry, &lpi_range_list) &&
1494                     (tmp->base_id == (range->base_id + range->span))) {
1495                         tmp->base_id = range->base_id;
1496                         tmp->span += range->span;
1497                         list_del(&range->entry);
1498                         kfree(range);
1499                 }
1500         }
1501 }
1502
1503 static int alloc_lpi_range(u32 nr_lpis, u32 *base)
1504 {
1505         struct lpi_range *range, *tmp;
1506         int err = -ENOSPC;
1507
1508         mutex_lock(&lpi_range_lock);
1509
1510         list_for_each_entry_safe(range, tmp, &lpi_range_list, entry) {
1511                 if (range->span >= nr_lpis) {
1512                         *base = range->base_id;
1513                         range->base_id += nr_lpis;
1514                         range->span -= nr_lpis;
1515
1516                         if (range->span == 0) {
1517                                 list_del(&range->entry);
1518                                 kfree(range);
1519                         }
1520
1521                         err = 0;
1522                         break;
1523                 }
1524         }
1525
1526         mutex_unlock(&lpi_range_lock);
1527
1528         pr_debug("ITS: alloc %u:%u\n", *base, nr_lpis);
1529         return err;
1530 }
1531
1532 static int free_lpi_range(u32 base, u32 nr_lpis)
1533 {
1534         struct lpi_range *new;
1535
1536         new = mk_lpi_range(base, nr_lpis);
1537         if (!new)
1538                 return -ENOMEM;
1539
1540         mutex_lock(&lpi_range_lock);
1541
1542         list_add(&new->entry, &lpi_range_list);
1543         list_sort(NULL, &lpi_range_list, lpi_range_cmp);
1544         merge_lpi_ranges();
1545
1546         mutex_unlock(&lpi_range_lock);
1547         return 0;
1548 }
1549
1550 static int __init its_lpi_init(u32 id_bits)
1551 {
1552         u32 lpis = (1UL << id_bits) - 8192;
1553         u32 numlpis;
1554         int err;
1555
1556         numlpis = 1UL << GICD_TYPER_NUM_LPIS(gic_rdists->gicd_typer);
1557
1558         if (numlpis > 2 && !WARN_ON(numlpis > lpis)) {
1559                 lpis = numlpis;
1560                 pr_info("ITS: Using hypervisor restricted LPI range [%u]\n",
1561                         lpis);
1562         }
1563
1564         /*
1565          * Initializing the allocator is just the same as freeing the
1566          * full range of LPIs.
1567          */
1568         err = free_lpi_range(8192, lpis);
1569         pr_debug("ITS: Allocator initialized for %u LPIs\n", lpis);
1570         return err;
1571 }
1572
1573 static unsigned long *its_lpi_alloc(int nr_irqs, u32 *base, int *nr_ids)
1574 {
1575         unsigned long *bitmap = NULL;
1576         int err = 0;
1577
1578         do {
1579                 err = alloc_lpi_range(nr_irqs, base);
1580                 if (!err)
1581                         break;
1582
1583                 nr_irqs /= 2;
1584         } while (nr_irqs > 0);
1585
1586         if (!nr_irqs)
1587                 err = -ENOSPC;
1588
1589         if (err)
1590                 goto out;
1591
1592         bitmap = kcalloc(BITS_TO_LONGS(nr_irqs), sizeof (long), GFP_ATOMIC);
1593         if (!bitmap)
1594                 goto out;
1595
1596         *nr_ids = nr_irqs;
1597
1598 out:
1599         if (!bitmap)
1600                 *base = *nr_ids = 0;
1601
1602         return bitmap;
1603 }
1604
1605 static void its_lpi_free(unsigned long *bitmap, u32 base, u32 nr_ids)
1606 {
1607         WARN_ON(free_lpi_range(base, nr_ids));
1608         kfree(bitmap);
1609 }
1610
1611 static void gic_reset_prop_table(void *va)
1612 {
1613         /* Priority 0xa0, Group-1, disabled */
1614         memset(va, LPI_PROP_DEFAULT_PRIO | LPI_PROP_GROUP1, LPI_PROPBASE_SZ);
1615
1616         /* Make sure the GIC will observe the written configuration */
1617         gic_flush_dcache_to_poc(va, LPI_PROPBASE_SZ);
1618 }
1619
1620 static struct page *its_allocate_prop_table(gfp_t gfp_flags)
1621 {
1622         struct page *prop_page;
1623
1624         prop_page = alloc_pages(gfp_flags, get_order(LPI_PROPBASE_SZ));
1625         if (!prop_page)
1626                 return NULL;
1627
1628         gic_reset_prop_table(page_address(prop_page));
1629
1630         return prop_page;
1631 }
1632
1633 static void its_free_prop_table(struct page *prop_page)
1634 {
1635         free_pages((unsigned long)page_address(prop_page),
1636                    get_order(LPI_PROPBASE_SZ));
1637 }
1638
1639 static bool gic_check_reserved_range(phys_addr_t addr, unsigned long size)
1640 {
1641         phys_addr_t start, end, addr_end;
1642         u64 i;
1643
1644         /*
1645          * We don't bother checking for a kdump kernel as by
1646          * construction, the LPI tables are out of this kernel's
1647          * memory map.
1648          */
1649         if (is_kdump_kernel())
1650                 return true;
1651
1652         addr_end = addr + size - 1;
1653
1654         for_each_reserved_mem_region(i, &start, &end) {
1655                 if (addr >= start && addr_end <= end)
1656                         return true;
1657         }
1658
1659         /* Not found, not a good sign... */
1660         pr_warn("GICv3: Expected reserved range [%pa:%pa], not found\n",
1661                 &addr, &addr_end);
1662         add_taint(TAINT_CRAP, LOCKDEP_STILL_OK);
1663         return false;
1664 }
1665
1666 static int gic_reserve_range(phys_addr_t addr, unsigned long size)
1667 {
1668         if (efi_enabled(EFI_CONFIG_TABLES))
1669                 return efi_mem_reserve_persistent(addr, size);
1670
1671         return 0;
1672 }
1673
1674 static int __init its_setup_lpi_prop_table(void)
1675 {
1676         if (gic_rdists->flags & RDIST_FLAGS_RD_TABLES_PREALLOCATED) {
1677                 u64 val;
1678
1679                 val = gicr_read_propbaser(gic_data_rdist_rd_base() + GICR_PROPBASER);
1680                 lpi_id_bits = (val & GICR_PROPBASER_IDBITS_MASK) + 1;
1681
1682                 gic_rdists->prop_table_pa = val & GENMASK_ULL(51, 12);
1683                 gic_rdists->prop_table_va = memremap(gic_rdists->prop_table_pa,
1684                                                      LPI_PROPBASE_SZ,
1685                                                      MEMREMAP_WB);
1686                 gic_reset_prop_table(gic_rdists->prop_table_va);
1687         } else {
1688                 struct page *page;
1689
1690                 lpi_id_bits = min_t(u32,
1691                                     GICD_TYPER_ID_BITS(gic_rdists->gicd_typer),
1692                                     ITS_MAX_LPI_NRBITS);
1693                 page = its_allocate_prop_table(GFP_NOWAIT);
1694                 if (!page) {
1695                         pr_err("Failed to allocate PROPBASE\n");
1696                         return -ENOMEM;
1697                 }
1698
1699                 gic_rdists->prop_table_pa = page_to_phys(page);
1700                 gic_rdists->prop_table_va = page_address(page);
1701                 WARN_ON(gic_reserve_range(gic_rdists->prop_table_pa,
1702                                           LPI_PROPBASE_SZ));
1703         }
1704
1705         pr_info("GICv3: using LPI property table @%pa\n",
1706                 &gic_rdists->prop_table_pa);
1707
1708         return its_lpi_init(lpi_id_bits);
1709 }
1710
1711 static const char *its_base_type_string[] = {
1712         [GITS_BASER_TYPE_DEVICE]        = "Devices",
1713         [GITS_BASER_TYPE_VCPU]          = "Virtual CPUs",
1714         [GITS_BASER_TYPE_RESERVED3]     = "Reserved (3)",
1715         [GITS_BASER_TYPE_COLLECTION]    = "Interrupt Collections",
1716         [GITS_BASER_TYPE_RESERVED5]     = "Reserved (5)",
1717         [GITS_BASER_TYPE_RESERVED6]     = "Reserved (6)",
1718         [GITS_BASER_TYPE_RESERVED7]     = "Reserved (7)",
1719 };
1720
1721 static u64 its_read_baser(struct its_node *its, struct its_baser *baser)
1722 {
1723         u32 idx = baser - its->tables;
1724
1725         return gits_read_baser(its->base + GITS_BASER + (idx << 3));
1726 }
1727
1728 static void its_write_baser(struct its_node *its, struct its_baser *baser,
1729                             u64 val)
1730 {
1731         u32 idx = baser - its->tables;
1732
1733         gits_write_baser(val, its->base + GITS_BASER + (idx << 3));
1734         baser->val = its_read_baser(its, baser);
1735 }
1736
1737 static int its_setup_baser(struct its_node *its, struct its_baser *baser,
1738                            u64 cache, u64 shr, u32 psz, u32 order,
1739                            bool indirect)
1740 {
1741         u64 val = its_read_baser(its, baser);
1742         u64 esz = GITS_BASER_ENTRY_SIZE(val);
1743         u64 type = GITS_BASER_TYPE(val);
1744         u64 baser_phys, tmp;
1745         u32 alloc_pages;
1746         struct page *page;
1747         void *base;
1748
1749 retry_alloc_baser:
1750         alloc_pages = (PAGE_ORDER_TO_SIZE(order) / psz);
1751         if (alloc_pages > GITS_BASER_PAGES_MAX) {
1752                 pr_warn("ITS@%pa: %s too large, reduce ITS pages %u->%u\n",
1753                         &its->phys_base, its_base_type_string[type],
1754                         alloc_pages, GITS_BASER_PAGES_MAX);
1755                 alloc_pages = GITS_BASER_PAGES_MAX;
1756                 order = get_order(GITS_BASER_PAGES_MAX * psz);
1757         }
1758
1759         page = alloc_pages_node(its->numa_node, GFP_KERNEL | __GFP_ZERO, order);
1760         if (!page)
1761                 return -ENOMEM;
1762
1763         base = (void *)page_address(page);
1764         baser_phys = virt_to_phys(base);
1765
1766         /* Check if the physical address of the memory is above 48bits */
1767         if (IS_ENABLED(CONFIG_ARM64_64K_PAGES) && (baser_phys >> 48)) {
1768
1769                 /* 52bit PA is supported only when PageSize=64K */
1770                 if (psz != SZ_64K) {
1771                         pr_err("ITS: no 52bit PA support when psz=%d\n", psz);
1772                         free_pages((unsigned long)base, order);
1773                         return -ENXIO;
1774                 }
1775
1776                 /* Convert 52bit PA to 48bit field */
1777                 baser_phys = GITS_BASER_PHYS_52_to_48(baser_phys);
1778         }
1779
1780 retry_baser:
1781         val = (baser_phys                                        |
1782                 (type << GITS_BASER_TYPE_SHIFT)                  |
1783                 ((esz - 1) << GITS_BASER_ENTRY_SIZE_SHIFT)       |
1784                 ((alloc_pages - 1) << GITS_BASER_PAGES_SHIFT)    |
1785                 cache                                            |
1786                 shr                                              |
1787                 GITS_BASER_VALID);
1788
1789         val |=  indirect ? GITS_BASER_INDIRECT : 0x0;
1790
1791         switch (psz) {
1792         case SZ_4K:
1793                 val |= GITS_BASER_PAGE_SIZE_4K;
1794                 break;
1795         case SZ_16K:
1796                 val |= GITS_BASER_PAGE_SIZE_16K;
1797                 break;
1798         case SZ_64K:
1799                 val |= GITS_BASER_PAGE_SIZE_64K;
1800                 break;
1801         }
1802
1803         its_write_baser(its, baser, val);
1804         tmp = baser->val;
1805
1806         if ((val ^ tmp) & GITS_BASER_SHAREABILITY_MASK) {
1807                 /*
1808                  * Shareability didn't stick. Just use
1809                  * whatever the read reported, which is likely
1810                  * to be the only thing this redistributor
1811                  * supports. If that's zero, make it
1812                  * non-cacheable as well.
1813                  */
1814                 shr = tmp & GITS_BASER_SHAREABILITY_MASK;
1815                 if (!shr) {
1816                         cache = GITS_BASER_nC;
1817                         gic_flush_dcache_to_poc(base, PAGE_ORDER_TO_SIZE(order));
1818                 }
1819                 goto retry_baser;
1820         }
1821
1822         if ((val ^ tmp) & GITS_BASER_PAGE_SIZE_MASK) {
1823                 /*
1824                  * Page size didn't stick. Let's try a smaller
1825                  * size and retry. If we reach 4K, then
1826                  * something is horribly wrong...
1827                  */
1828                 free_pages((unsigned long)base, order);
1829                 baser->base = NULL;
1830
1831                 switch (psz) {
1832                 case SZ_16K:
1833                         psz = SZ_4K;
1834                         goto retry_alloc_baser;
1835                 case SZ_64K:
1836                         psz = SZ_16K;
1837                         goto retry_alloc_baser;
1838                 }
1839         }
1840
1841         if (val != tmp) {
1842                 pr_err("ITS@%pa: %s doesn't stick: %llx %llx\n",
1843                        &its->phys_base, its_base_type_string[type],
1844                        val, tmp);
1845                 free_pages((unsigned long)base, order);
1846                 return -ENXIO;
1847         }
1848
1849         baser->order = order;
1850         baser->base = base;
1851         baser->psz = psz;
1852         tmp = indirect ? GITS_LVL1_ENTRY_SIZE : esz;
1853
1854         pr_info("ITS@%pa: allocated %d %s @%lx (%s, esz %d, psz %dK, shr %d)\n",
1855                 &its->phys_base, (int)(PAGE_ORDER_TO_SIZE(order) / (int)tmp),
1856                 its_base_type_string[type],
1857                 (unsigned long)virt_to_phys(base),
1858                 indirect ? "indirect" : "flat", (int)esz,
1859                 psz / SZ_1K, (int)shr >> GITS_BASER_SHAREABILITY_SHIFT);
1860
1861         return 0;
1862 }
1863
1864 static bool its_parse_indirect_baser(struct its_node *its,
1865                                      struct its_baser *baser,
1866                                      u32 psz, u32 *order, u32 ids)
1867 {
1868         u64 tmp = its_read_baser(its, baser);
1869         u64 type = GITS_BASER_TYPE(tmp);
1870         u64 esz = GITS_BASER_ENTRY_SIZE(tmp);
1871         u64 val = GITS_BASER_InnerShareable | GITS_BASER_RaWaWb;
1872         u32 new_order = *order;
1873         bool indirect = false;
1874
1875         /* No need to enable Indirection if memory requirement < (psz*2)bytes */
1876         if ((esz << ids) > (psz * 2)) {
1877                 /*
1878                  * Find out whether hw supports a single or two-level table by
1879                  * table by reading bit at offset '62' after writing '1' to it.
1880                  */
1881                 its_write_baser(its, baser, val | GITS_BASER_INDIRECT);
1882                 indirect = !!(baser->val & GITS_BASER_INDIRECT);
1883
1884                 if (indirect) {
1885                         /*
1886                          * The size of the lvl2 table is equal to ITS page size
1887                          * which is 'psz'. For computing lvl1 table size,
1888                          * subtract ID bits that sparse lvl2 table from 'ids'
1889                          * which is reported by ITS hardware times lvl1 table
1890                          * entry size.
1891                          */
1892                         ids -= ilog2(psz / (int)esz);
1893                         esz = GITS_LVL1_ENTRY_SIZE;
1894                 }
1895         }
1896
1897         /*
1898          * Allocate as many entries as required to fit the
1899          * range of device IDs that the ITS can grok... The ID
1900          * space being incredibly sparse, this results in a
1901          * massive waste of memory if two-level device table
1902          * feature is not supported by hardware.
1903          */
1904         new_order = max_t(u32, get_order(esz << ids), new_order);
1905         if (new_order >= MAX_ORDER) {
1906                 new_order = MAX_ORDER - 1;
1907                 ids = ilog2(PAGE_ORDER_TO_SIZE(new_order) / (int)esz);
1908                 pr_warn("ITS@%pa: %s Table too large, reduce ids %u->%u\n",
1909                         &its->phys_base, its_base_type_string[type],
1910                         its->device_ids, ids);
1911         }
1912
1913         *order = new_order;
1914
1915         return indirect;
1916 }
1917
1918 static void its_free_tables(struct its_node *its)
1919 {
1920         int i;
1921
1922         for (i = 0; i < GITS_BASER_NR_REGS; i++) {
1923                 if (its->tables[i].base) {
1924                         free_pages((unsigned long)its->tables[i].base,
1925                                    its->tables[i].order);
1926                         its->tables[i].base = NULL;
1927                 }
1928         }
1929 }
1930
1931 static int its_alloc_tables(struct its_node *its)
1932 {
1933         u64 shr = GITS_BASER_InnerShareable;
1934         u64 cache = GITS_BASER_RaWaWb;
1935         u32 psz = SZ_64K;
1936         int err, i;
1937
1938         if (its->flags & ITS_FLAGS_WORKAROUND_CAVIUM_22375)
1939                 /* erratum 24313: ignore memory access type */
1940                 cache = GITS_BASER_nCnB;
1941
1942         for (i = 0; i < GITS_BASER_NR_REGS; i++) {
1943                 struct its_baser *baser = its->tables + i;
1944                 u64 val = its_read_baser(its, baser);
1945                 u64 type = GITS_BASER_TYPE(val);
1946                 u32 order = get_order(psz);
1947                 bool indirect = false;
1948
1949                 switch (type) {
1950                 case GITS_BASER_TYPE_NONE:
1951                         continue;
1952
1953                 case GITS_BASER_TYPE_DEVICE:
1954                         indirect = its_parse_indirect_baser(its, baser,
1955                                                             psz, &order,
1956                                                             its->device_ids);
1957                         break;
1958
1959                 case GITS_BASER_TYPE_VCPU:
1960                         indirect = its_parse_indirect_baser(its, baser,
1961                                                             psz, &order,
1962                                                             ITS_MAX_VPEID_BITS);
1963                         break;
1964                 }
1965
1966                 err = its_setup_baser(its, baser, cache, shr, psz, order, indirect);
1967                 if (err < 0) {
1968                         its_free_tables(its);
1969                         return err;
1970                 }
1971
1972                 /* Update settings which will be used for next BASERn */
1973                 psz = baser->psz;
1974                 cache = baser->val & GITS_BASER_CACHEABILITY_MASK;
1975                 shr = baser->val & GITS_BASER_SHAREABILITY_MASK;
1976         }
1977
1978         return 0;
1979 }
1980
1981 static int its_alloc_collections(struct its_node *its)
1982 {
1983         int i;
1984
1985         its->collections = kcalloc(nr_cpu_ids, sizeof(*its->collections),
1986                                    GFP_KERNEL);
1987         if (!its->collections)
1988                 return -ENOMEM;
1989
1990         for (i = 0; i < nr_cpu_ids; i++)
1991                 its->collections[i].target_address = ~0ULL;
1992
1993         return 0;
1994 }
1995
1996 static struct page *its_allocate_pending_table(gfp_t gfp_flags)
1997 {
1998         struct page *pend_page;
1999
2000         pend_page = alloc_pages(gfp_flags | __GFP_ZERO,
2001                                 get_order(LPI_PENDBASE_SZ));
2002         if (!pend_page)
2003                 return NULL;
2004
2005         /* Make sure the GIC will observe the zero-ed page */
2006         gic_flush_dcache_to_poc(page_address(pend_page), LPI_PENDBASE_SZ);
2007
2008         return pend_page;
2009 }
2010
2011 static void its_free_pending_table(struct page *pt)
2012 {
2013         free_pages((unsigned long)page_address(pt), get_order(LPI_PENDBASE_SZ));
2014 }
2015
2016 /*
2017  * Booting with kdump and LPIs enabled is generally fine. Any other
2018  * case is wrong in the absence of firmware/EFI support.
2019  */
2020 static bool enabled_lpis_allowed(void)
2021 {
2022         phys_addr_t addr;
2023         u64 val;
2024
2025         /* Check whether the property table is in a reserved region */
2026         val = gicr_read_propbaser(gic_data_rdist_rd_base() + GICR_PROPBASER);
2027         addr = val & GENMASK_ULL(51, 12);
2028
2029         return gic_check_reserved_range(addr, LPI_PROPBASE_SZ);
2030 }
2031
2032 static int __init allocate_lpi_tables(void)
2033 {
2034         u64 val;
2035         int err, cpu;
2036
2037         /*
2038          * If LPIs are enabled while we run this from the boot CPU,
2039          * flag the RD tables as pre-allocated if the stars do align.
2040          */
2041         val = readl_relaxed(gic_data_rdist_rd_base() + GICR_CTLR);
2042         if ((val & GICR_CTLR_ENABLE_LPIS) && enabled_lpis_allowed()) {
2043                 gic_rdists->flags |= (RDIST_FLAGS_RD_TABLES_PREALLOCATED |
2044                                       RDIST_FLAGS_PROPBASE_NEEDS_FLUSHING);
2045                 pr_info("GICv3: Using preallocated redistributor tables\n");
2046         }
2047
2048         err = its_setup_lpi_prop_table();
2049         if (err)
2050                 return err;
2051
2052         /*
2053          * We allocate all the pending tables anyway, as we may have a
2054          * mix of RDs that have had LPIs enabled, and some that
2055          * don't. We'll free the unused ones as each CPU comes online.
2056          */
2057         for_each_possible_cpu(cpu) {
2058                 struct page *pend_page;
2059
2060                 pend_page = its_allocate_pending_table(GFP_NOWAIT);
2061                 if (!pend_page) {
2062                         pr_err("Failed to allocate PENDBASE for CPU%d\n", cpu);
2063                         return -ENOMEM;
2064                 }
2065
2066                 gic_data_rdist_cpu(cpu)->pend_page = pend_page;
2067         }
2068
2069         return 0;
2070 }
2071
2072 static u64 its_clear_vpend_valid(void __iomem *vlpi_base)
2073 {
2074         u32 count = 1000000;    /* 1s! */
2075         bool clean;
2076         u64 val;
2077
2078         val = gits_read_vpendbaser(vlpi_base + GICR_VPENDBASER);
2079         val &= ~GICR_VPENDBASER_Valid;
2080         gits_write_vpendbaser(val, vlpi_base + GICR_VPENDBASER);
2081
2082         do {
2083                 val = gits_read_vpendbaser(vlpi_base + GICR_VPENDBASER);
2084                 clean = !(val & GICR_VPENDBASER_Dirty);
2085                 if (!clean) {
2086                         count--;
2087                         cpu_relax();
2088                         udelay(1);
2089                 }
2090         } while (!clean && count);
2091
2092         return val;
2093 }
2094
2095 static void its_cpu_init_lpis(void)
2096 {
2097         void __iomem *rbase = gic_data_rdist_rd_base();
2098         struct page *pend_page;
2099         phys_addr_t paddr;
2100         u64 val, tmp;
2101
2102         if (gic_data_rdist()->lpi_enabled)
2103                 return;
2104
2105         val = readl_relaxed(rbase + GICR_CTLR);
2106         if ((gic_rdists->flags & RDIST_FLAGS_RD_TABLES_PREALLOCATED) &&
2107             (val & GICR_CTLR_ENABLE_LPIS)) {
2108                 /*
2109                  * Check that we get the same property table on all
2110                  * RDs. If we don't, this is hopeless.
2111                  */
2112                 paddr = gicr_read_propbaser(rbase + GICR_PROPBASER);
2113                 paddr &= GENMASK_ULL(51, 12);
2114                 if (WARN_ON(gic_rdists->prop_table_pa != paddr))
2115                         add_taint(TAINT_CRAP, LOCKDEP_STILL_OK);
2116
2117                 paddr = gicr_read_pendbaser(rbase + GICR_PENDBASER);
2118                 paddr &= GENMASK_ULL(51, 16);
2119
2120                 WARN_ON(!gic_check_reserved_range(paddr, LPI_PENDBASE_SZ));
2121                 its_free_pending_table(gic_data_rdist()->pend_page);
2122                 gic_data_rdist()->pend_page = NULL;
2123
2124                 goto out;
2125         }
2126
2127         pend_page = gic_data_rdist()->pend_page;
2128         paddr = page_to_phys(pend_page);
2129         WARN_ON(gic_reserve_range(paddr, LPI_PENDBASE_SZ));
2130
2131         /* set PROPBASE */
2132         val = (gic_rdists->prop_table_pa |
2133                GICR_PROPBASER_InnerShareable |
2134                GICR_PROPBASER_RaWaWb |
2135                ((LPI_NRBITS - 1) & GICR_PROPBASER_IDBITS_MASK));
2136
2137         gicr_write_propbaser(val, rbase + GICR_PROPBASER);
2138         tmp = gicr_read_propbaser(rbase + GICR_PROPBASER);
2139
2140         if ((tmp ^ val) & GICR_PROPBASER_SHAREABILITY_MASK) {
2141                 if (!(tmp & GICR_PROPBASER_SHAREABILITY_MASK)) {
2142                         /*
2143                          * The HW reports non-shareable, we must
2144                          * remove the cacheability attributes as
2145                          * well.
2146                          */
2147                         val &= ~(GICR_PROPBASER_SHAREABILITY_MASK |
2148                                  GICR_PROPBASER_CACHEABILITY_MASK);
2149                         val |= GICR_PROPBASER_nC;
2150                         gicr_write_propbaser(val, rbase + GICR_PROPBASER);
2151                 }
2152                 pr_info_once("GIC: using cache flushing for LPI property table\n");
2153                 gic_rdists->flags |= RDIST_FLAGS_PROPBASE_NEEDS_FLUSHING;
2154         }
2155
2156         /* set PENDBASE */
2157         val = (page_to_phys(pend_page) |
2158                GICR_PENDBASER_InnerShareable |
2159                GICR_PENDBASER_RaWaWb);
2160
2161         gicr_write_pendbaser(val, rbase + GICR_PENDBASER);
2162         tmp = gicr_read_pendbaser(rbase + GICR_PENDBASER);
2163
2164         if (!(tmp & GICR_PENDBASER_SHAREABILITY_MASK)) {
2165                 /*
2166                  * The HW reports non-shareable, we must remove the
2167                  * cacheability attributes as well.
2168                  */
2169                 val &= ~(GICR_PENDBASER_SHAREABILITY_MASK |
2170                          GICR_PENDBASER_CACHEABILITY_MASK);
2171                 val |= GICR_PENDBASER_nC;
2172                 gicr_write_pendbaser(val, rbase + GICR_PENDBASER);
2173         }
2174
2175         /* Enable LPIs */
2176         val = readl_relaxed(rbase + GICR_CTLR);
2177         val |= GICR_CTLR_ENABLE_LPIS;
2178         writel_relaxed(val, rbase + GICR_CTLR);
2179
2180         if (gic_rdists->has_vlpis) {
2181                 void __iomem *vlpi_base = gic_data_rdist_vlpi_base();
2182
2183                 /*
2184                  * It's possible for CPU to receive VLPIs before it is
2185                  * sheduled as a vPE, especially for the first CPU, and the
2186                  * VLPI with INTID larger than 2^(IDbits+1) will be considered
2187                  * as out of range and dropped by GIC.
2188                  * So we initialize IDbits to known value to avoid VLPI drop.
2189                  */
2190                 val = (LPI_NRBITS - 1) & GICR_VPROPBASER_IDBITS_MASK;
2191                 pr_debug("GICv4: CPU%d: Init IDbits to 0x%llx for GICR_VPROPBASER\n",
2192                         smp_processor_id(), val);
2193                 gits_write_vpropbaser(val, vlpi_base + GICR_VPROPBASER);
2194
2195                 /*
2196                  * Also clear Valid bit of GICR_VPENDBASER, in case some
2197                  * ancient programming gets left in and has possibility of
2198                  * corrupting memory.
2199                  */
2200                 val = its_clear_vpend_valid(vlpi_base);
2201                 WARN_ON(val & GICR_VPENDBASER_Dirty);
2202         }
2203
2204         /* Make sure the GIC has seen the above */
2205         dsb(sy);
2206 out:
2207         gic_data_rdist()->lpi_enabled = true;
2208         pr_info("GICv3: CPU%d: using %s LPI pending table @%pa\n",
2209                 smp_processor_id(),
2210                 gic_data_rdist()->pend_page ? "allocated" : "reserved",
2211                 &paddr);
2212 }
2213
2214 static void its_cpu_init_collection(struct its_node *its)
2215 {
2216         int cpu = smp_processor_id();
2217         u64 target;
2218
2219         /* avoid cross node collections and its mapping */
2220         if (its->flags & ITS_FLAGS_WORKAROUND_CAVIUM_23144) {
2221                 struct device_node *cpu_node;
2222
2223                 cpu_node = of_get_cpu_node(cpu, NULL);
2224                 if (its->numa_node != NUMA_NO_NODE &&
2225                         its->numa_node != of_node_to_nid(cpu_node))
2226                         return;
2227         }
2228
2229         /*
2230          * We now have to bind each collection to its target
2231          * redistributor.
2232          */
2233         if (gic_read_typer(its->base + GITS_TYPER) & GITS_TYPER_PTA) {
2234                 /*
2235                  * This ITS wants the physical address of the
2236                  * redistributor.
2237                  */
2238                 target = gic_data_rdist()->phys_base;
2239         } else {
2240                 /* This ITS wants a linear CPU number. */
2241                 target = gic_read_typer(gic_data_rdist_rd_base() + GICR_TYPER);
2242                 target = GICR_TYPER_CPU_NUMBER(target) << 16;
2243         }
2244
2245         /* Perform collection mapping */
2246         its->collections[cpu].target_address = target;
2247         its->collections[cpu].col_id = cpu;
2248
2249         its_send_mapc(its, &its->collections[cpu], 1);
2250         its_send_invall(its, &its->collections[cpu]);
2251 }
2252
2253 static void its_cpu_init_collections(void)
2254 {
2255         struct its_node *its;
2256
2257         raw_spin_lock(&its_lock);
2258
2259         list_for_each_entry(its, &its_nodes, entry)
2260                 its_cpu_init_collection(its);
2261
2262         raw_spin_unlock(&its_lock);
2263 }
2264
2265 static struct its_device *its_find_device(struct its_node *its, u32 dev_id)
2266 {
2267         struct its_device *its_dev = NULL, *tmp;
2268         unsigned long flags;
2269
2270         raw_spin_lock_irqsave(&its->lock, flags);
2271
2272         list_for_each_entry(tmp, &its->its_device_list, entry) {
2273                 if (tmp->device_id == dev_id) {
2274                         its_dev = tmp;
2275                         break;
2276                 }
2277         }
2278
2279         raw_spin_unlock_irqrestore(&its->lock, flags);
2280
2281         return its_dev;
2282 }
2283
2284 static struct its_baser *its_get_baser(struct its_node *its, u32 type)
2285 {
2286         int i;
2287
2288         for (i = 0; i < GITS_BASER_NR_REGS; i++) {
2289                 if (GITS_BASER_TYPE(its->tables[i].val) == type)
2290                         return &its->tables[i];
2291         }
2292
2293         return NULL;
2294 }
2295
2296 static bool its_alloc_table_entry(struct its_node *its,
2297                                   struct its_baser *baser, u32 id)
2298 {
2299         struct page *page;
2300         u32 esz, idx;
2301         __le64 *table;
2302
2303         /* Don't allow device id that exceeds single, flat table limit */
2304         esz = GITS_BASER_ENTRY_SIZE(baser->val);
2305         if (!(baser->val & GITS_BASER_INDIRECT))
2306                 return (id < (PAGE_ORDER_TO_SIZE(baser->order) / esz));
2307
2308         /* Compute 1st level table index & check if that exceeds table limit */
2309         idx = id >> ilog2(baser->psz / esz);
2310         if (idx >= (PAGE_ORDER_TO_SIZE(baser->order) / GITS_LVL1_ENTRY_SIZE))
2311                 return false;
2312
2313         table = baser->base;
2314
2315         /* Allocate memory for 2nd level table */
2316         if (!table[idx]) {
2317                 page = alloc_pages_node(its->numa_node, GFP_KERNEL | __GFP_ZERO,
2318                                         get_order(baser->psz));
2319                 if (!page)
2320                         return false;
2321
2322                 /* Flush Lvl2 table to PoC if hw doesn't support coherency */
2323                 if (!(baser->val & GITS_BASER_SHAREABILITY_MASK))
2324                         gic_flush_dcache_to_poc(page_address(page), baser->psz);
2325
2326                 table[idx] = cpu_to_le64(page_to_phys(page) | GITS_BASER_VALID);
2327
2328                 /* Flush Lvl1 entry to PoC if hw doesn't support coherency */
2329                 if (!(baser->val & GITS_BASER_SHAREABILITY_MASK))
2330                         gic_flush_dcache_to_poc(table + idx, GITS_LVL1_ENTRY_SIZE);
2331
2332                 /* Ensure updated table contents are visible to ITS hardware */
2333                 dsb(sy);
2334         }
2335
2336         return true;
2337 }
2338
2339 static bool its_alloc_device_table(struct its_node *its, u32 dev_id)
2340 {
2341         struct its_baser *baser;
2342
2343         baser = its_get_baser(its, GITS_BASER_TYPE_DEVICE);
2344
2345         /* Don't allow device id that exceeds ITS hardware limit */
2346         if (!baser)
2347                 return (ilog2(dev_id) < its->device_ids);
2348
2349         return its_alloc_table_entry(its, baser, dev_id);
2350 }
2351
2352 static bool its_alloc_vpe_table(u32 vpe_id)
2353 {
2354         struct its_node *its;
2355
2356         /*
2357          * Make sure the L2 tables are allocated on *all* v4 ITSs. We
2358          * could try and only do it on ITSs corresponding to devices
2359          * that have interrupts targeted at this VPE, but the
2360          * complexity becomes crazy (and you have tons of memory
2361          * anyway, right?).
2362          */
2363         list_for_each_entry(its, &its_nodes, entry) {
2364                 struct its_baser *baser;
2365
2366                 if (!its->is_v4)
2367                         continue;
2368
2369                 baser = its_get_baser(its, GITS_BASER_TYPE_VCPU);
2370                 if (!baser)
2371                         return false;
2372
2373                 if (!its_alloc_table_entry(its, baser, vpe_id))
2374                         return false;
2375         }
2376
2377         return true;
2378 }
2379
2380 static struct its_device *its_create_device(struct its_node *its, u32 dev_id,
2381                                             int nvecs, bool alloc_lpis)
2382 {
2383         struct its_device *dev;
2384         unsigned long *lpi_map = NULL;
2385         unsigned long flags;
2386         u16 *col_map = NULL;
2387         void *itt;
2388         int lpi_base;
2389         int nr_lpis;
2390         int nr_ites;
2391         int sz;
2392
2393         if (!its_alloc_device_table(its, dev_id))
2394                 return NULL;
2395
2396         if (WARN_ON(!is_power_of_2(nvecs)))
2397                 nvecs = roundup_pow_of_two(nvecs);
2398
2399         dev = kzalloc(sizeof(*dev), GFP_KERNEL);
2400         /*
2401          * Even if the device wants a single LPI, the ITT must be
2402          * sized as a power of two (and you need at least one bit...).
2403          */
2404         nr_ites = max(2, nvecs);
2405         sz = nr_ites * its->ite_size;
2406         sz = max(sz, ITS_ITT_ALIGN) + ITS_ITT_ALIGN - 1;
2407         itt = kzalloc_node(sz, GFP_KERNEL, its->numa_node);
2408         if (alloc_lpis) {
2409                 lpi_map = its_lpi_alloc(nvecs, &lpi_base, &nr_lpis);
2410                 if (lpi_map)
2411                         col_map = kcalloc(nr_lpis, sizeof(*col_map),
2412                                           GFP_KERNEL);
2413         } else {
2414                 col_map = kcalloc(nr_ites, sizeof(*col_map), GFP_KERNEL);
2415                 nr_lpis = 0;
2416                 lpi_base = 0;
2417         }
2418
2419         if (!dev || !itt ||  !col_map || (!lpi_map && alloc_lpis)) {
2420                 kfree(dev);
2421                 kfree(itt);
2422                 kfree(lpi_map);
2423                 kfree(col_map);
2424                 return NULL;
2425         }
2426
2427         gic_flush_dcache_to_poc(itt, sz);
2428
2429         dev->its = its;
2430         dev->itt = itt;
2431         dev->nr_ites = nr_ites;
2432         dev->event_map.lpi_map = lpi_map;
2433         dev->event_map.col_map = col_map;
2434         dev->event_map.lpi_base = lpi_base;
2435         dev->event_map.nr_lpis = nr_lpis;
2436         mutex_init(&dev->event_map.vlpi_lock);
2437         dev->device_id = dev_id;
2438         INIT_LIST_HEAD(&dev->entry);
2439
2440         raw_spin_lock_irqsave(&its->lock, flags);
2441         list_add(&dev->entry, &its->its_device_list);
2442         raw_spin_unlock_irqrestore(&its->lock, flags);
2443
2444         /* Map device to its ITT */
2445         its_send_mapd(dev, 1);
2446
2447         return dev;
2448 }
2449
2450 static void its_free_device(struct its_device *its_dev)
2451 {
2452         unsigned long flags;
2453
2454         raw_spin_lock_irqsave(&its_dev->its->lock, flags);
2455         list_del(&its_dev->entry);
2456         raw_spin_unlock_irqrestore(&its_dev->its->lock, flags);
2457         kfree(its_dev->itt);
2458         kfree(its_dev);
2459 }
2460
2461 static int its_alloc_device_irq(struct its_device *dev, int nvecs, irq_hw_number_t *hwirq)
2462 {
2463         int idx;
2464
2465         idx = bitmap_find_free_region(dev->event_map.lpi_map,
2466                                       dev->event_map.nr_lpis,
2467                                       get_count_order(nvecs));
2468         if (idx < 0)
2469                 return -ENOSPC;
2470
2471         *hwirq = dev->event_map.lpi_base + idx;
2472         set_bit(idx, dev->event_map.lpi_map);
2473
2474         return 0;
2475 }
2476
2477 static int its_msi_prepare(struct irq_domain *domain, struct device *dev,
2478                            int nvec, msi_alloc_info_t *info)
2479 {
2480         struct its_node *its;
2481         struct its_device *its_dev;
2482         struct msi_domain_info *msi_info;
2483         u32 dev_id;
2484         int err = 0;
2485
2486         /*
2487          * We ignore "dev" entirely, and rely on the dev_id that has
2488          * been passed via the scratchpad. This limits this domain's
2489          * usefulness to upper layers that definitely know that they
2490          * are built on top of the ITS.
2491          */
2492         dev_id = info->scratchpad[0].ul;
2493
2494         msi_info = msi_get_domain_info(domain);
2495         its = msi_info->data;
2496
2497         if (!gic_rdists->has_direct_lpi &&
2498             vpe_proxy.dev &&
2499             vpe_proxy.dev->its == its &&
2500             dev_id == vpe_proxy.dev->device_id) {
2501                 /* Bad luck. Get yourself a better implementation */
2502                 WARN_ONCE(1, "DevId %x clashes with GICv4 VPE proxy device\n",
2503                           dev_id);
2504                 return -EINVAL;
2505         }
2506
2507         mutex_lock(&its->dev_alloc_lock);
2508         its_dev = its_find_device(its, dev_id);
2509         if (its_dev) {
2510                 /*
2511                  * We already have seen this ID, probably through
2512                  * another alias (PCI bridge of some sort). No need to
2513                  * create the device.
2514                  */
2515                 its_dev->shared = true;
2516                 pr_debug("Reusing ITT for devID %x\n", dev_id);
2517                 goto out;
2518         }
2519
2520         its_dev = its_create_device(its, dev_id, nvec, true);
2521         if (!its_dev) {
2522                 err = -ENOMEM;
2523                 goto out;
2524         }
2525
2526         pr_debug("ITT %d entries, %d bits\n", nvec, ilog2(nvec));
2527 out:
2528         mutex_unlock(&its->dev_alloc_lock);
2529         info->scratchpad[0].ptr = its_dev;
2530         return err;
2531 }
2532
2533 static struct msi_domain_ops its_msi_domain_ops = {
2534         .msi_prepare    = its_msi_prepare,
2535 };
2536
2537 static int its_irq_gic_domain_alloc(struct irq_domain *domain,
2538                                     unsigned int virq,
2539                                     irq_hw_number_t hwirq)
2540 {
2541         struct irq_fwspec fwspec;
2542
2543         if (irq_domain_get_of_node(domain->parent)) {
2544                 fwspec.fwnode = domain->parent->fwnode;
2545                 fwspec.param_count = 3;
2546                 fwspec.param[0] = GIC_IRQ_TYPE_LPI;
2547                 fwspec.param[1] = hwirq;
2548                 fwspec.param[2] = IRQ_TYPE_EDGE_RISING;
2549         } else if (is_fwnode_irqchip(domain->parent->fwnode)) {
2550                 fwspec.fwnode = domain->parent->fwnode;
2551                 fwspec.param_count = 2;
2552                 fwspec.param[0] = hwirq;
2553                 fwspec.param[1] = IRQ_TYPE_EDGE_RISING;
2554         } else {
2555                 return -EINVAL;
2556         }
2557
2558         return irq_domain_alloc_irqs_parent(domain, virq, 1, &fwspec);
2559 }
2560
2561 static int its_irq_domain_alloc(struct irq_domain *domain, unsigned int virq,
2562                                 unsigned int nr_irqs, void *args)
2563 {
2564         msi_alloc_info_t *info = args;
2565         struct its_device *its_dev = info->scratchpad[0].ptr;
2566         irq_hw_number_t hwirq;
2567         int err;
2568         int i;
2569
2570         err = its_alloc_device_irq(its_dev, nr_irqs, &hwirq);
2571         if (err)
2572                 return err;
2573
2574         for (i = 0; i < nr_irqs; i++) {
2575                 err = its_irq_gic_domain_alloc(domain, virq + i, hwirq + i);
2576                 if (err)
2577                         return err;
2578
2579                 irq_domain_set_hwirq_and_chip(domain, virq + i,
2580                                               hwirq + i, &its_irq_chip, its_dev);
2581                 irqd_set_single_target(irq_desc_get_irq_data(irq_to_desc(virq + i)));
2582                 pr_debug("ID:%d pID:%d vID:%d\n",
2583                          (int)(hwirq + i - its_dev->event_map.lpi_base),
2584                          (int)(hwirq + i), virq + i);
2585         }
2586
2587         return 0;
2588 }
2589
2590 static int its_irq_domain_activate(struct irq_domain *domain,
2591                                    struct irq_data *d, bool reserve)
2592 {
2593         struct its_device *its_dev = irq_data_get_irq_chip_data(d);
2594         u32 event = its_get_event_id(d);
2595         const struct cpumask *cpu_mask = cpu_online_mask;
2596         int cpu;
2597
2598         /* get the cpu_mask of local node */
2599         if (its_dev->its->numa_node >= 0)
2600                 cpu_mask = cpumask_of_node(its_dev->its->numa_node);
2601
2602         /* Bind the LPI to the first possible CPU */
2603         cpu = cpumask_first_and(cpu_mask, cpu_online_mask);
2604         if (cpu >= nr_cpu_ids) {
2605                 if (its_dev->its->flags & ITS_FLAGS_WORKAROUND_CAVIUM_23144)
2606                         return -EINVAL;
2607
2608                 cpu = cpumask_first(cpu_online_mask);
2609         }
2610
2611         its_dev->event_map.col_map[event] = cpu;
2612         irq_data_update_effective_affinity(d, cpumask_of(cpu));
2613
2614         /* Map the GIC IRQ and event to the device */
2615         its_send_mapti(its_dev, d->hwirq, event);
2616         return 0;
2617 }
2618
2619 static void its_irq_domain_deactivate(struct irq_domain *domain,
2620                                       struct irq_data *d)
2621 {
2622         struct its_device *its_dev = irq_data_get_irq_chip_data(d);
2623         u32 event = its_get_event_id(d);
2624
2625         /* Stop the delivery of interrupts */
2626         its_send_discard(its_dev, event);
2627 }
2628
2629 static void its_irq_domain_free(struct irq_domain *domain, unsigned int virq,
2630                                 unsigned int nr_irqs)
2631 {
2632         struct irq_data *d = irq_domain_get_irq_data(domain, virq);
2633         struct its_device *its_dev = irq_data_get_irq_chip_data(d);
2634         struct its_node *its = its_dev->its;
2635         int i;
2636
2637         for (i = 0; i < nr_irqs; i++) {
2638                 struct irq_data *data = irq_domain_get_irq_data(domain,
2639                                                                 virq + i);
2640                 u32 event = its_get_event_id(data);
2641
2642                 /* Mark interrupt index as unused */
2643                 clear_bit(event, its_dev->event_map.lpi_map);
2644
2645                 /* Nuke the entry in the domain */
2646                 irq_domain_reset_irq_data(data);
2647         }
2648
2649         mutex_lock(&its->dev_alloc_lock);
2650
2651         /*
2652          * If all interrupts have been freed, start mopping the
2653          * floor. This is conditionned on the device not being shared.
2654          */
2655         if (!its_dev->shared &&
2656             bitmap_empty(its_dev->event_map.lpi_map,
2657                          its_dev->event_map.nr_lpis)) {
2658                 its_lpi_free(its_dev->event_map.lpi_map,
2659                              its_dev->event_map.lpi_base,
2660                              its_dev->event_map.nr_lpis);
2661                 kfree(its_dev->event_map.col_map);
2662
2663                 /* Unmap device/itt */
2664                 its_send_mapd(its_dev, 0);
2665                 its_free_device(its_dev);
2666         }
2667
2668         mutex_unlock(&its->dev_alloc_lock);
2669
2670         irq_domain_free_irqs_parent(domain, virq, nr_irqs);
2671 }
2672
2673 static const struct irq_domain_ops its_domain_ops = {
2674         .alloc                  = its_irq_domain_alloc,
2675         .free                   = its_irq_domain_free,
2676         .activate               = its_irq_domain_activate,
2677         .deactivate             = its_irq_domain_deactivate,
2678 };
2679
2680 /*
2681  * This is insane.
2682  *
2683  * If a GICv4 doesn't implement Direct LPIs (which is extremely
2684  * likely), the only way to perform an invalidate is to use a fake
2685  * device to issue an INV command, implying that the LPI has first
2686  * been mapped to some event on that device. Since this is not exactly
2687  * cheap, we try to keep that mapping around as long as possible, and
2688  * only issue an UNMAP if we're short on available slots.
2689  *
2690  * Broken by design(tm).
2691  */
2692 static void its_vpe_db_proxy_unmap_locked(struct its_vpe *vpe)
2693 {
2694         /* Already unmapped? */
2695         if (vpe->vpe_proxy_event == -1)
2696                 return;
2697
2698         its_send_discard(vpe_proxy.dev, vpe->vpe_proxy_event);
2699         vpe_proxy.vpes[vpe->vpe_proxy_event] = NULL;
2700
2701         /*
2702          * We don't track empty slots at all, so let's move the
2703          * next_victim pointer if we can quickly reuse that slot
2704          * instead of nuking an existing entry. Not clear that this is
2705          * always a win though, and this might just generate a ripple
2706          * effect... Let's just hope VPEs don't migrate too often.
2707          */
2708         if (vpe_proxy.vpes[vpe_proxy.next_victim])
2709                 vpe_proxy.next_victim = vpe->vpe_proxy_event;
2710
2711         vpe->vpe_proxy_event = -1;
2712 }
2713
2714 static void its_vpe_db_proxy_unmap(struct its_vpe *vpe)
2715 {
2716         if (!gic_rdists->has_direct_lpi) {
2717                 unsigned long flags;
2718
2719                 raw_spin_lock_irqsave(&vpe_proxy.lock, flags);
2720                 its_vpe_db_proxy_unmap_locked(vpe);
2721                 raw_spin_unlock_irqrestore(&vpe_proxy.lock, flags);
2722         }
2723 }
2724
2725 static void its_vpe_db_proxy_map_locked(struct its_vpe *vpe)
2726 {
2727         /* Already mapped? */
2728         if (vpe->vpe_proxy_event != -1)
2729                 return;
2730
2731         /* This slot was already allocated. Kick the other VPE out. */
2732         if (vpe_proxy.vpes[vpe_proxy.next_victim])
2733                 its_vpe_db_proxy_unmap_locked(vpe_proxy.vpes[vpe_proxy.next_victim]);
2734
2735         /* Map the new VPE instead */
2736         vpe_proxy.vpes[vpe_proxy.next_victim] = vpe;
2737         vpe->vpe_proxy_event = vpe_proxy.next_victim;
2738         vpe_proxy.next_victim = (vpe_proxy.next_victim + 1) % vpe_proxy.dev->nr_ites;
2739
2740         vpe_proxy.dev->event_map.col_map[vpe->vpe_proxy_event] = vpe->col_idx;
2741         its_send_mapti(vpe_proxy.dev, vpe->vpe_db_lpi, vpe->vpe_proxy_event);
2742 }
2743
2744 static void its_vpe_db_proxy_move(struct its_vpe *vpe, int from, int to)
2745 {
2746         unsigned long flags;
2747         struct its_collection *target_col;
2748
2749         if (gic_rdists->has_direct_lpi) {
2750                 void __iomem *rdbase;
2751
2752                 rdbase = per_cpu_ptr(gic_rdists->rdist, from)->rd_base;
2753                 gic_write_lpir(vpe->vpe_db_lpi, rdbase + GICR_CLRLPIR);
2754                 while (gic_read_lpir(rdbase + GICR_SYNCR) & 1)
2755                         cpu_relax();
2756
2757                 return;
2758         }
2759
2760         raw_spin_lock_irqsave(&vpe_proxy.lock, flags);
2761
2762         its_vpe_db_proxy_map_locked(vpe);
2763
2764         target_col = &vpe_proxy.dev->its->collections[to];
2765         its_send_movi(vpe_proxy.dev, target_col, vpe->vpe_proxy_event);
2766         vpe_proxy.dev->event_map.col_map[vpe->vpe_proxy_event] = to;
2767
2768         raw_spin_unlock_irqrestore(&vpe_proxy.lock, flags);
2769 }
2770
2771 static int its_vpe_set_affinity(struct irq_data *d,
2772                                 const struct cpumask *mask_val,
2773                                 bool force)
2774 {
2775         struct its_vpe *vpe = irq_data_get_irq_chip_data(d);
2776         int cpu = cpumask_first(mask_val);
2777
2778         /*
2779          * Changing affinity is mega expensive, so let's be as lazy as
2780          * we can and only do it if we really have to. Also, if mapped
2781          * into the proxy device, we need to move the doorbell
2782          * interrupt to its new location.
2783          */
2784         if (vpe->col_idx != cpu) {
2785                 int from = vpe->col_idx;
2786
2787                 vpe->col_idx = cpu;
2788                 its_send_vmovp(vpe);
2789                 its_vpe_db_proxy_move(vpe, from, cpu);
2790         }
2791
2792         irq_data_update_effective_affinity(d, cpumask_of(cpu));
2793
2794         return IRQ_SET_MASK_OK_DONE;
2795 }
2796
2797 static void its_vpe_schedule(struct its_vpe *vpe)
2798 {
2799         void __iomem *vlpi_base = gic_data_rdist_vlpi_base();
2800         u64 val;
2801
2802         /* Schedule the VPE */
2803         val  = virt_to_phys(page_address(vpe->its_vm->vprop_page)) &
2804                 GENMASK_ULL(51, 12);
2805         val |= (LPI_NRBITS - 1) & GICR_VPROPBASER_IDBITS_MASK;
2806         val |= GICR_VPROPBASER_RaWb;
2807         val |= GICR_VPROPBASER_InnerShareable;
2808         gits_write_vpropbaser(val, vlpi_base + GICR_VPROPBASER);
2809
2810         val  = virt_to_phys(page_address(vpe->vpt_page)) &
2811                 GENMASK_ULL(51, 16);
2812         val |= GICR_VPENDBASER_RaWaWb;
2813         val |= GICR_VPENDBASER_NonShareable;
2814         /*
2815          * There is no good way of finding out if the pending table is
2816          * empty as we can race against the doorbell interrupt very
2817          * easily. So in the end, vpe->pending_last is only an
2818          * indication that the vcpu has something pending, not one
2819          * that the pending table is empty. A good implementation
2820          * would be able to read its coarse map pretty quickly anyway,
2821          * making this a tolerable issue.
2822          */
2823         val |= GICR_VPENDBASER_PendingLast;
2824         val |= vpe->idai ? GICR_VPENDBASER_IDAI : 0;
2825         val |= GICR_VPENDBASER_Valid;
2826         gits_write_vpendbaser(val, vlpi_base + GICR_VPENDBASER);
2827 }
2828
2829 static void its_vpe_deschedule(struct its_vpe *vpe)
2830 {
2831         void __iomem *vlpi_base = gic_data_rdist_vlpi_base();
2832         u64 val;
2833
2834         val = its_clear_vpend_valid(vlpi_base);
2835
2836         if (unlikely(val & GICR_VPENDBASER_Dirty)) {
2837                 pr_err_ratelimited("ITS virtual pending table not cleaning\n");
2838                 vpe->idai = false;
2839                 vpe->pending_last = true;
2840         } else {
2841                 vpe->idai = !!(val & GICR_VPENDBASER_IDAI);
2842                 vpe->pending_last = !!(val & GICR_VPENDBASER_PendingLast);
2843         }
2844 }
2845
2846 static void its_vpe_invall(struct its_vpe *vpe)
2847 {
2848         struct its_node *its;
2849
2850         list_for_each_entry(its, &its_nodes, entry) {
2851                 if (!its->is_v4)
2852                         continue;
2853
2854                 if (its_list_map && !vpe->its_vm->vlpi_count[its->list_nr])
2855                         continue;
2856
2857                 /*
2858                  * Sending a VINVALL to a single ITS is enough, as all
2859                  * we need is to reach the redistributors.
2860                  */
2861                 its_send_vinvall(its, vpe);
2862                 return;
2863         }
2864 }
2865
2866 static int its_vpe_set_vcpu_affinity(struct irq_data *d, void *vcpu_info)
2867 {
2868         struct its_vpe *vpe = irq_data_get_irq_chip_data(d);
2869         struct its_cmd_info *info = vcpu_info;
2870
2871         switch (info->cmd_type) {
2872         case SCHEDULE_VPE:
2873                 its_vpe_schedule(vpe);
2874                 return 0;
2875
2876         case DESCHEDULE_VPE:
2877                 its_vpe_deschedule(vpe);
2878                 return 0;
2879
2880         case INVALL_VPE:
2881                 its_vpe_invall(vpe);
2882                 return 0;
2883
2884         default:
2885                 return -EINVAL;
2886         }
2887 }
2888
2889 static void its_vpe_send_cmd(struct its_vpe *vpe,
2890                              void (*cmd)(struct its_device *, u32))
2891 {
2892         unsigned long flags;
2893
2894         raw_spin_lock_irqsave(&vpe_proxy.lock, flags);
2895
2896         its_vpe_db_proxy_map_locked(vpe);
2897         cmd(vpe_proxy.dev, vpe->vpe_proxy_event);
2898
2899         raw_spin_unlock_irqrestore(&vpe_proxy.lock, flags);
2900 }
2901
2902 static void its_vpe_send_inv(struct irq_data *d)
2903 {
2904         struct its_vpe *vpe = irq_data_get_irq_chip_data(d);
2905
2906         if (gic_rdists->has_direct_lpi) {
2907                 void __iomem *rdbase;
2908
2909                 rdbase = per_cpu_ptr(gic_rdists->rdist, vpe->col_idx)->rd_base;
2910                 gic_write_lpir(vpe->vpe_db_lpi, rdbase + GICR_INVLPIR);
2911                 while (gic_read_lpir(rdbase + GICR_SYNCR) & 1)
2912                         cpu_relax();
2913         } else {
2914                 its_vpe_send_cmd(vpe, its_send_inv);
2915         }
2916 }
2917
2918 static void its_vpe_mask_irq(struct irq_data *d)
2919 {
2920         /*
2921          * We need to unmask the LPI, which is described by the parent
2922          * irq_data. Instead of calling into the parent (which won't
2923          * exactly do the right thing, let's simply use the
2924          * parent_data pointer. Yes, I'm naughty.
2925          */
2926         lpi_write_config(d->parent_data, LPI_PROP_ENABLED, 0);
2927         its_vpe_send_inv(d);
2928 }
2929
2930 static void its_vpe_unmask_irq(struct irq_data *d)
2931 {
2932         /* Same hack as above... */
2933         lpi_write_config(d->parent_data, 0, LPI_PROP_ENABLED);
2934         its_vpe_send_inv(d);
2935 }
2936
2937 static int its_vpe_set_irqchip_state(struct irq_data *d,
2938                                      enum irqchip_irq_state which,
2939                                      bool state)
2940 {
2941         struct its_vpe *vpe = irq_data_get_irq_chip_data(d);
2942
2943         if (which != IRQCHIP_STATE_PENDING)
2944                 return -EINVAL;
2945
2946         if (gic_rdists->has_direct_lpi) {
2947                 void __iomem *rdbase;
2948
2949                 rdbase = per_cpu_ptr(gic_rdists->rdist, vpe->col_idx)->rd_base;
2950                 if (state) {
2951                         gic_write_lpir(vpe->vpe_db_lpi, rdbase + GICR_SETLPIR);
2952                 } else {
2953                         gic_write_lpir(vpe->vpe_db_lpi, rdbase + GICR_CLRLPIR);
2954                         while (gic_read_lpir(rdbase + GICR_SYNCR) & 1)
2955                                 cpu_relax();
2956                 }
2957         } else {
2958                 if (state)
2959                         its_vpe_send_cmd(vpe, its_send_int);
2960                 else
2961                         its_vpe_send_cmd(vpe, its_send_clear);
2962         }
2963
2964         return 0;
2965 }
2966
2967 static struct irq_chip its_vpe_irq_chip = {
2968         .name                   = "GICv4-vpe",
2969         .irq_mask               = its_vpe_mask_irq,
2970         .irq_unmask             = its_vpe_unmask_irq,
2971         .irq_eoi                = irq_chip_eoi_parent,
2972         .irq_set_affinity       = its_vpe_set_affinity,
2973         .irq_set_irqchip_state  = its_vpe_set_irqchip_state,
2974         .irq_set_vcpu_affinity  = its_vpe_set_vcpu_affinity,
2975 };
2976
2977 static int its_vpe_id_alloc(void)
2978 {
2979         return ida_simple_get(&its_vpeid_ida, 0, ITS_MAX_VPEID, GFP_KERNEL);
2980 }
2981
2982 static void its_vpe_id_free(u16 id)
2983 {
2984         ida_simple_remove(&its_vpeid_ida, id);
2985 }
2986
2987 static int its_vpe_init(struct its_vpe *vpe)
2988 {
2989         struct page *vpt_page;
2990         int vpe_id;
2991
2992         /* Allocate vpe_id */
2993         vpe_id = its_vpe_id_alloc();
2994         if (vpe_id < 0)
2995                 return vpe_id;
2996
2997         /* Allocate VPT */
2998         vpt_page = its_allocate_pending_table(GFP_KERNEL);
2999         if (!vpt_page) {
3000                 its_vpe_id_free(vpe_id);
3001                 return -ENOMEM;
3002         }
3003
3004         if (!its_alloc_vpe_table(vpe_id)) {
3005                 its_vpe_id_free(vpe_id);
3006                 its_free_pending_table(vpe->vpt_page);
3007                 return -ENOMEM;
3008         }
3009
3010         vpe->vpe_id = vpe_id;
3011         vpe->vpt_page = vpt_page;
3012         vpe->vpe_proxy_event = -1;
3013
3014         return 0;
3015 }
3016
3017 static void its_vpe_teardown(struct its_vpe *vpe)
3018 {
3019         its_vpe_db_proxy_unmap(vpe);
3020         its_vpe_id_free(vpe->vpe_id);
3021         its_free_pending_table(vpe->vpt_page);
3022 }
3023
3024 static void its_vpe_irq_domain_free(struct irq_domain *domain,
3025                                     unsigned int virq,
3026                                     unsigned int nr_irqs)
3027 {
3028         struct its_vm *vm = domain->host_data;
3029         int i;
3030
3031         irq_domain_free_irqs_parent(domain, virq, nr_irqs);
3032
3033         for (i = 0; i < nr_irqs; i++) {
3034                 struct irq_data *data = irq_domain_get_irq_data(domain,
3035                                                                 virq + i);
3036                 struct its_vpe *vpe = irq_data_get_irq_chip_data(data);
3037
3038                 BUG_ON(vm != vpe->its_vm);
3039
3040                 clear_bit(data->hwirq, vm->db_bitmap);
3041                 its_vpe_teardown(vpe);
3042                 irq_domain_reset_irq_data(data);
3043         }
3044
3045         if (bitmap_empty(vm->db_bitmap, vm->nr_db_lpis)) {
3046                 its_lpi_free(vm->db_bitmap, vm->db_lpi_base, vm->nr_db_lpis);
3047                 its_free_prop_table(vm->vprop_page);
3048         }
3049 }
3050
3051 static int its_vpe_irq_domain_alloc(struct irq_domain *domain, unsigned int virq,
3052                                     unsigned int nr_irqs, void *args)
3053 {
3054         struct its_vm *vm = args;
3055         unsigned long *bitmap;
3056         struct page *vprop_page;
3057         int base, nr_ids, i, err = 0;
3058
3059         BUG_ON(!vm);
3060
3061         bitmap = its_lpi_alloc(roundup_pow_of_two(nr_irqs), &base, &nr_ids);
3062         if (!bitmap)
3063                 return -ENOMEM;
3064
3065         if (nr_ids < nr_irqs) {
3066                 its_lpi_free(bitmap, base, nr_ids);
3067                 return -ENOMEM;
3068         }
3069
3070         vprop_page = its_allocate_prop_table(GFP_KERNEL);
3071         if (!vprop_page) {
3072                 its_lpi_free(bitmap, base, nr_ids);
3073                 return -ENOMEM;
3074         }
3075
3076         vm->db_bitmap = bitmap;
3077         vm->db_lpi_base = base;
3078         vm->nr_db_lpis = nr_ids;
3079         vm->vprop_page = vprop_page;
3080
3081         for (i = 0; i < nr_irqs; i++) {
3082                 vm->vpes[i]->vpe_db_lpi = base + i;
3083                 err = its_vpe_init(vm->vpes[i]);
3084                 if (err)
3085                         break;
3086                 err = its_irq_gic_domain_alloc(domain, virq + i,
3087                                                vm->vpes[i]->vpe_db_lpi);
3088                 if (err)
3089                         break;
3090                 irq_domain_set_hwirq_and_chip(domain, virq + i, i,
3091                                               &its_vpe_irq_chip, vm->vpes[i]);
3092                 set_bit(i, bitmap);
3093         }
3094
3095         if (err) {
3096                 if (i > 0)
3097                         its_vpe_irq_domain_free(domain, virq, i - 1);
3098
3099                 its_lpi_free(bitmap, base, nr_ids);
3100                 its_free_prop_table(vprop_page);
3101         }
3102
3103         return err;
3104 }
3105
3106 static int its_vpe_irq_domain_activate(struct irq_domain *domain,
3107                                        struct irq_data *d, bool reserve)
3108 {
3109         struct its_vpe *vpe = irq_data_get_irq_chip_data(d);
3110         struct its_node *its;
3111
3112         /* If we use the list map, we issue VMAPP on demand... */
3113         if (its_list_map)
3114                 return 0;
3115
3116         /* Map the VPE to the first possible CPU */
3117         vpe->col_idx = cpumask_first(cpu_online_mask);
3118
3119         list_for_each_entry(its, &its_nodes, entry) {
3120                 if (!its->is_v4)
3121                         continue;
3122
3123                 its_send_vmapp(its, vpe, true);
3124                 its_send_vinvall(its, vpe);
3125         }
3126
3127         irq_data_update_effective_affinity(d, cpumask_of(vpe->col_idx));
3128
3129         return 0;
3130 }
3131
3132 static void its_vpe_irq_domain_deactivate(struct irq_domain *domain,
3133                                           struct irq_data *d)
3134 {
3135         struct its_vpe *vpe = irq_data_get_irq_chip_data(d);
3136         struct its_node *its;
3137
3138         /*
3139          * If we use the list map, we unmap the VPE once no VLPIs are
3140          * associated with the VM.
3141          */
3142         if (its_list_map)
3143                 return;
3144
3145         list_for_each_entry(its, &its_nodes, entry) {
3146                 if (!its->is_v4)
3147                         continue;
3148
3149                 its_send_vmapp(its, vpe, false);
3150         }
3151 }
3152
3153 static const struct irq_domain_ops its_vpe_domain_ops = {
3154         .alloc                  = its_vpe_irq_domain_alloc,
3155         .free                   = its_vpe_irq_domain_free,
3156         .activate               = its_vpe_irq_domain_activate,
3157         .deactivate             = its_vpe_irq_domain_deactivate,
3158 };
3159
3160 static int its_force_quiescent(void __iomem *base)
3161 {
3162         u32 count = 1000000;    /* 1s */
3163         u32 val;
3164
3165         val = readl_relaxed(base + GITS_CTLR);
3166         /*
3167          * GIC architecture specification requires the ITS to be both
3168          * disabled and quiescent for writes to GITS_BASER<n> or
3169          * GITS_CBASER to not have UNPREDICTABLE results.
3170          */
3171         if ((val & GITS_CTLR_QUIESCENT) && !(val & GITS_CTLR_ENABLE))
3172                 return 0;
3173
3174         /* Disable the generation of all interrupts to this ITS */
3175         val &= ~(GITS_CTLR_ENABLE | GITS_CTLR_ImDe);
3176         writel_relaxed(val, base + GITS_CTLR);
3177
3178         /* Poll GITS_CTLR and wait until ITS becomes quiescent */
3179         while (1) {
3180                 val = readl_relaxed(base + GITS_CTLR);
3181                 if (val & GITS_CTLR_QUIESCENT)
3182                         return 0;
3183
3184                 count--;
3185                 if (!count)
3186                         return -EBUSY;
3187
3188                 cpu_relax();
3189                 udelay(1);
3190         }
3191 }
3192
3193 static bool __maybe_unused its_enable_quirk_cavium_22375(void *data)
3194 {
3195         struct its_node *its = data;
3196
3197         /* erratum 22375: only alloc 8MB table size */
3198         its->device_ids = 0x14;         /* 20 bits, 8MB */
3199         its->flags |= ITS_FLAGS_WORKAROUND_CAVIUM_22375;
3200
3201         return true;
3202 }
3203
3204 static bool __maybe_unused its_enable_quirk_cavium_23144(void *data)
3205 {
3206         struct its_node *its = data;
3207
3208         its->flags |= ITS_FLAGS_WORKAROUND_CAVIUM_23144;
3209
3210         return true;
3211 }
3212
3213 static bool __maybe_unused its_enable_quirk_qdf2400_e0065(void *data)
3214 {
3215         struct its_node *its = data;
3216
3217         /* On QDF2400, the size of the ITE is 16Bytes */
3218         its->ite_size = 16;
3219
3220         return true;
3221 }
3222
3223 static u64 its_irq_get_msi_base_pre_its(struct its_device *its_dev)
3224 {
3225         struct its_node *its = its_dev->its;
3226
3227         /*
3228          * The Socionext Synquacer SoC has a so-called 'pre-ITS',
3229          * which maps 32-bit writes targeted at a separate window of
3230          * size '4 << device_id_bits' onto writes to GITS_TRANSLATER
3231          * with device ID taken from bits [device_id_bits + 1:2] of
3232          * the window offset.
3233          */
3234         return its->pre_its_base + (its_dev->device_id << 2);
3235 }
3236
3237 static bool __maybe_unused its_enable_quirk_socionext_synquacer(void *data)
3238 {
3239         struct its_node *its = data;
3240         u32 pre_its_window[2];
3241         u32 ids;
3242
3243         if (!fwnode_property_read_u32_array(its->fwnode_handle,
3244                                            "socionext,synquacer-pre-its",
3245                                            pre_its_window,
3246                                            ARRAY_SIZE(pre_its_window))) {
3247
3248                 its->pre_its_base = pre_its_window[0];
3249                 its->get_msi_base = its_irq_get_msi_base_pre_its;
3250
3251                 ids = ilog2(pre_its_window[1]) - 2;
3252                 if (its->device_ids > ids)
3253                         its->device_ids = ids;
3254
3255                 /* the pre-ITS breaks isolation, so disable MSI remapping */
3256                 its->msi_domain_flags &= ~IRQ_DOMAIN_FLAG_MSI_REMAP;
3257                 return true;
3258         }
3259         return false;
3260 }
3261
3262 static bool __maybe_unused its_enable_quirk_hip07_161600802(void *data)
3263 {
3264         struct its_node *its = data;
3265
3266         /*
3267          * Hip07 insists on using the wrong address for the VLPI
3268          * page. Trick it into doing the right thing...
3269          */
3270         its->vlpi_redist_offset = SZ_128K;
3271         return true;
3272 }
3273
3274 static const struct gic_quirk its_quirks[] = {
3275 #ifdef CONFIG_CAVIUM_ERRATUM_22375
3276         {
3277                 .desc   = "ITS: Cavium errata 22375, 24313",
3278                 .iidr   = 0xa100034c,   /* ThunderX pass 1.x */
3279                 .mask   = 0xffff0fff,
3280                 .init   = its_enable_quirk_cavium_22375,
3281         },
3282 #endif
3283 #ifdef CONFIG_CAVIUM_ERRATUM_23144
3284         {
3285                 .desc   = "ITS: Cavium erratum 23144",
3286                 .iidr   = 0xa100034c,   /* ThunderX pass 1.x */
3287                 .mask   = 0xffff0fff,
3288                 .init   = its_enable_quirk_cavium_23144,
3289         },
3290 #endif
3291 #ifdef CONFIG_QCOM_QDF2400_ERRATUM_0065
3292         {
3293                 .desc   = "ITS: QDF2400 erratum 0065",
3294                 .iidr   = 0x00001070, /* QDF2400 ITS rev 1.x */
3295                 .mask   = 0xffffffff,
3296                 .init   = its_enable_quirk_qdf2400_e0065,
3297         },
3298 #endif
3299 #ifdef CONFIG_SOCIONEXT_SYNQUACER_PREITS
3300         {
3301                 /*
3302                  * The Socionext Synquacer SoC incorporates ARM's own GIC-500
3303                  * implementation, but with a 'pre-ITS' added that requires
3304                  * special handling in software.
3305                  */
3306                 .desc   = "ITS: Socionext Synquacer pre-ITS",
3307                 .iidr   = 0x0001143b,
3308                 .mask   = 0xffffffff,
3309                 .init   = its_enable_quirk_socionext_synquacer,
3310         },
3311 #endif
3312 #ifdef CONFIG_HISILICON_ERRATUM_161600802
3313         {
3314                 .desc   = "ITS: Hip07 erratum 161600802",
3315                 .iidr   = 0x00000004,
3316                 .mask   = 0xffffffff,
3317                 .init   = its_enable_quirk_hip07_161600802,
3318         },
3319 #endif
3320         {
3321         }
3322 };
3323
3324 static void its_enable_quirks(struct its_node *its)
3325 {
3326         u32 iidr = readl_relaxed(its->base + GITS_IIDR);
3327
3328         gic_enable_quirks(iidr, its_quirks, its);
3329 }
3330
3331 static int its_save_disable(void)
3332 {
3333         struct its_node *its;
3334         int err = 0;
3335
3336         raw_spin_lock(&its_lock);
3337         list_for_each_entry(its, &its_nodes, entry) {
3338                 void __iomem *base;
3339
3340                 if (!(its->flags & ITS_FLAGS_SAVE_SUSPEND_STATE))
3341                         continue;
3342
3343                 base = its->base;
3344                 its->ctlr_save = readl_relaxed(base + GITS_CTLR);
3345                 err = its_force_quiescent(base);
3346                 if (err) {
3347                         pr_err("ITS@%pa: failed to quiesce: %d\n",
3348                                &its->phys_base, err);
3349                         writel_relaxed(its->ctlr_save, base + GITS_CTLR);
3350                         goto err;
3351                 }
3352
3353                 its->cbaser_save = gits_read_cbaser(base + GITS_CBASER);
3354         }
3355
3356 err:
3357         if (err) {
3358                 list_for_each_entry_continue_reverse(its, &its_nodes, entry) {
3359                         void __iomem *base;
3360
3361                         if (!(its->flags & ITS_FLAGS_SAVE_SUSPEND_STATE))
3362                                 continue;
3363
3364                         base = its->base;
3365                         writel_relaxed(its->ctlr_save, base + GITS_CTLR);
3366                 }
3367         }
3368         raw_spin_unlock(&its_lock);
3369
3370         return err;
3371 }
3372
3373 static void its_restore_enable(void)
3374 {
3375         struct its_node *its;
3376         int ret;
3377
3378         raw_spin_lock(&its_lock);
3379         list_for_each_entry(its, &its_nodes, entry) {
3380                 void __iomem *base;
3381                 int i;
3382
3383                 if (!(its->flags & ITS_FLAGS_SAVE_SUSPEND_STATE))
3384                         continue;
3385
3386                 base = its->base;
3387
3388                 /*
3389                  * Make sure that the ITS is disabled. If it fails to quiesce,
3390                  * don't restore it since writing to CBASER or BASER<n>
3391                  * registers is undefined according to the GIC v3 ITS
3392                  * Specification.
3393                  */
3394                 ret = its_force_quiescent(base);
3395                 if (ret) {
3396                         pr_err("ITS@%pa: failed to quiesce on resume: %d\n",
3397                                &its->phys_base, ret);
3398                         continue;
3399                 }
3400
3401                 gits_write_cbaser(its->cbaser_save, base + GITS_CBASER);
3402
3403                 /*
3404                  * Writing CBASER resets CREADR to 0, so make CWRITER and
3405                  * cmd_write line up with it.
3406                  */
3407                 its->cmd_write = its->cmd_base;
3408                 gits_write_cwriter(0, base + GITS_CWRITER);
3409
3410                 /* Restore GITS_BASER from the value cache. */
3411                 for (i = 0; i < GITS_BASER_NR_REGS; i++) {
3412                         struct its_baser *baser = &its->tables[i];
3413
3414                         if (!(baser->val & GITS_BASER_VALID))
3415                                 continue;
3416
3417                         its_write_baser(its, baser, baser->val);
3418                 }
3419                 writel_relaxed(its->ctlr_save, base + GITS_CTLR);
3420
3421                 /*
3422                  * Reinit the collection if it's stored in the ITS. This is
3423                  * indicated by the col_id being less than the HCC field.
3424                  * CID < HCC as specified in the GIC v3 Documentation.
3425                  */
3426                 if (its->collections[smp_processor_id()].col_id <
3427                     GITS_TYPER_HCC(gic_read_typer(base + GITS_TYPER)))
3428                         its_cpu_init_collection(its);
3429         }
3430         raw_spin_unlock(&its_lock);
3431 }
3432
3433 static struct syscore_ops its_syscore_ops = {
3434         .suspend = its_save_disable,
3435         .resume = its_restore_enable,
3436 };
3437
3438 static int its_init_domain(struct fwnode_handle *handle, struct its_node *its)
3439 {
3440         struct irq_domain *inner_domain;
3441         struct msi_domain_info *info;
3442
3443         info = kzalloc(sizeof(*info), GFP_KERNEL);
3444         if (!info)
3445                 return -ENOMEM;
3446
3447         inner_domain = irq_domain_create_tree(handle, &its_domain_ops, its);
3448         if (!inner_domain) {
3449                 kfree(info);
3450                 return -ENOMEM;
3451         }
3452
3453         inner_domain->parent = its_parent;
3454         irq_domain_update_bus_token(inner_domain, DOMAIN_BUS_NEXUS);
3455         inner_domain->flags |= its->msi_domain_flags;
3456         info->ops = &its_msi_domain_ops;
3457         info->data = its;
3458         inner_domain->host_data = info;
3459
3460         return 0;
3461 }
3462
3463 static int its_init_vpe_domain(void)
3464 {
3465         struct its_node *its;
3466         u32 devid;
3467         int entries;
3468
3469         if (gic_rdists->has_direct_lpi) {
3470                 pr_info("ITS: Using DirectLPI for VPE invalidation\n");
3471                 return 0;
3472         }
3473
3474         /* Any ITS will do, even if not v4 */
3475         its = list_first_entry(&its_nodes, struct its_node, entry);
3476
3477         entries = roundup_pow_of_two(nr_cpu_ids);
3478         vpe_proxy.vpes = kcalloc(entries, sizeof(*vpe_proxy.vpes),
3479                                  GFP_KERNEL);
3480         if (!vpe_proxy.vpes) {
3481                 pr_err("ITS: Can't allocate GICv4 proxy device array\n");
3482                 return -ENOMEM;
3483         }
3484
3485         /* Use the last possible DevID */
3486         devid = GENMASK(its->device_ids - 1, 0);
3487         vpe_proxy.dev = its_create_device(its, devid, entries, false);
3488         if (!vpe_proxy.dev) {
3489                 kfree(vpe_proxy.vpes);
3490                 pr_err("ITS: Can't allocate GICv4 proxy device\n");
3491                 return -ENOMEM;
3492         }
3493
3494         BUG_ON(entries > vpe_proxy.dev->nr_ites);
3495
3496         raw_spin_lock_init(&vpe_proxy.lock);
3497         vpe_proxy.next_victim = 0;
3498         pr_info("ITS: Allocated DevID %x as GICv4 proxy device (%d slots)\n",
3499                 devid, vpe_proxy.dev->nr_ites);
3500
3501         return 0;
3502 }
3503
3504 static int __init its_compute_its_list_map(struct resource *res,
3505                                            void __iomem *its_base)
3506 {
3507         int its_number;
3508         u32 ctlr;
3509
3510         /*
3511          * This is assumed to be done early enough that we're
3512          * guaranteed to be single-threaded, hence no
3513          * locking. Should this change, we should address
3514          * this.
3515          */
3516         its_number = find_first_zero_bit(&its_list_map, GICv4_ITS_LIST_MAX);
3517         if (its_number >= GICv4_ITS_LIST_MAX) {
3518                 pr_err("ITS@%pa: No ITSList entry available!\n",
3519                        &res->start);
3520                 return -EINVAL;
3521         }
3522
3523         ctlr = readl_relaxed(its_base + GITS_CTLR);
3524         ctlr &= ~GITS_CTLR_ITS_NUMBER;
3525         ctlr |= its_number << GITS_CTLR_ITS_NUMBER_SHIFT;
3526         writel_relaxed(ctlr, its_base + GITS_CTLR);
3527         ctlr = readl_relaxed(its_base + GITS_CTLR);
3528         if ((ctlr & GITS_CTLR_ITS_NUMBER) != (its_number << GITS_CTLR_ITS_NUMBER_SHIFT)) {
3529                 its_number = ctlr & GITS_CTLR_ITS_NUMBER;
3530                 its_number >>= GITS_CTLR_ITS_NUMBER_SHIFT;
3531         }
3532
3533         if (test_and_set_bit(its_number, &its_list_map)) {
3534                 pr_err("ITS@%pa: Duplicate ITSList entry %d\n",
3535                        &res->start, its_number);
3536                 return -EINVAL;
3537         }
3538
3539         return its_number;
3540 }
3541
3542 static int __init its_probe_one(struct resource *res,
3543                                 struct fwnode_handle *handle, int numa_node)
3544 {
3545         struct its_node *its;
3546         void __iomem *its_base;
3547         u32 val, ctlr;
3548         u64 baser, tmp, typer;
3549         struct page *page;
3550         int err;
3551
3552         its_base = ioremap(res->start, resource_size(res));
3553         if (!its_base) {
3554                 pr_warn("ITS@%pa: Unable to map ITS registers\n", &res->start);
3555                 return -ENOMEM;
3556         }
3557
3558         val = readl_relaxed(its_base + GITS_PIDR2) & GIC_PIDR2_ARCH_MASK;
3559         if (val != 0x30 && val != 0x40) {
3560                 pr_warn("ITS@%pa: No ITS detected, giving up\n", &res->start);
3561                 err = -ENODEV;
3562                 goto out_unmap;
3563         }
3564
3565         err = its_force_quiescent(its_base);
3566         if (err) {
3567                 pr_warn("ITS@%pa: Failed to quiesce, giving up\n", &res->start);
3568                 goto out_unmap;
3569         }
3570
3571         pr_info("ITS %pR\n", res);
3572
3573         its = kzalloc(sizeof(*its), GFP_KERNEL);
3574         if (!its) {
3575                 err = -ENOMEM;
3576                 goto out_unmap;
3577         }
3578
3579         raw_spin_lock_init(&its->lock);
3580         mutex_init(&its->dev_alloc_lock);
3581         INIT_LIST_HEAD(&its->entry);
3582         INIT_LIST_HEAD(&its->its_device_list);
3583         typer = gic_read_typer(its_base + GITS_TYPER);
3584         its->base = its_base;
3585         its->phys_base = res->start;
3586         its->ite_size = GITS_TYPER_ITT_ENTRY_SIZE(typer);
3587         its->device_ids = GITS_TYPER_DEVBITS(typer);
3588         its->is_v4 = !!(typer & GITS_TYPER_VLPIS);
3589         if (its->is_v4) {
3590                 if (!(typer & GITS_TYPER_VMOVP)) {
3591                         err = its_compute_its_list_map(res, its_base);
3592                         if (err < 0)
3593                                 goto out_free_its;
3594
3595                         its->list_nr = err;
3596
3597                         pr_info("ITS@%pa: Using ITS number %d\n",
3598                                 &res->start, err);
3599                 } else {
3600                         pr_info("ITS@%pa: Single VMOVP capable\n", &res->start);
3601                 }
3602         }
3603
3604         its->numa_node = numa_node;
3605
3606         page = alloc_pages_node(its->numa_node, GFP_KERNEL | __GFP_ZERO,
3607                                 get_order(ITS_CMD_QUEUE_SZ));
3608         if (!page) {
3609                 err = -ENOMEM;
3610                 goto out_free_its;
3611         }
3612         its->cmd_base = (void *)page_address(page);
3613         its->cmd_write = its->cmd_base;
3614         its->fwnode_handle = handle;
3615         its->get_msi_base = its_irq_get_msi_base;
3616         its->msi_domain_flags = IRQ_DOMAIN_FLAG_MSI_REMAP;
3617
3618         its_enable_quirks(its);
3619
3620         err = its_alloc_tables(its);
3621         if (err)
3622                 goto out_free_cmd;
3623
3624         err = its_alloc_collections(its);
3625         if (err)
3626                 goto out_free_tables;
3627
3628         baser = (virt_to_phys(its->cmd_base)    |
3629                  GITS_CBASER_RaWaWb             |
3630                  GITS_CBASER_InnerShareable     |
3631                  (ITS_CMD_QUEUE_SZ / SZ_4K - 1) |
3632                  GITS_CBASER_VALID);
3633
3634         gits_write_cbaser(baser, its->base + GITS_CBASER);
3635         tmp = gits_read_cbaser(its->base + GITS_CBASER);
3636
3637         if ((tmp ^ baser) & GITS_CBASER_SHAREABILITY_MASK) {
3638                 if (!(tmp & GITS_CBASER_SHAREABILITY_MASK)) {
3639                         /*
3640                          * The HW reports non-shareable, we must
3641                          * remove the cacheability attributes as
3642                          * well.
3643                          */
3644                         baser &= ~(GITS_CBASER_SHAREABILITY_MASK |
3645                                    GITS_CBASER_CACHEABILITY_MASK);
3646                         baser |= GITS_CBASER_nC;
3647                         gits_write_cbaser(baser, its->base + GITS_CBASER);
3648                 }
3649                 pr_info("ITS: using cache flushing for cmd queue\n");
3650                 its->flags |= ITS_FLAGS_CMDQ_NEEDS_FLUSHING;
3651         }
3652
3653         gits_write_cwriter(0, its->base + GITS_CWRITER);
3654         ctlr = readl_relaxed(its->base + GITS_CTLR);
3655         ctlr |= GITS_CTLR_ENABLE;
3656         if (its->is_v4)
3657                 ctlr |= GITS_CTLR_ImDe;
3658         writel_relaxed(ctlr, its->base + GITS_CTLR);
3659
3660         if (GITS_TYPER_HCC(typer))
3661                 its->flags |= ITS_FLAGS_SAVE_SUSPEND_STATE;
3662
3663         err = its_init_domain(handle, its);
3664         if (err)
3665                 goto out_free_tables;
3666
3667         raw_spin_lock(&its_lock);
3668         list_add(&its->entry, &its_nodes);
3669         raw_spin_unlock(&its_lock);
3670
3671         return 0;
3672
3673 out_free_tables:
3674         its_free_tables(its);
3675 out_free_cmd:
3676         free_pages((unsigned long)its->cmd_base, get_order(ITS_CMD_QUEUE_SZ));
3677 out_free_its:
3678         kfree(its);
3679 out_unmap:
3680         iounmap(its_base);
3681         pr_err("ITS@%pa: failed probing (%d)\n", &res->start, err);
3682         return err;
3683 }
3684
3685 static bool gic_rdists_supports_plpis(void)
3686 {
3687         return !!(gic_read_typer(gic_data_rdist_rd_base() + GICR_TYPER) & GICR_TYPER_PLPIS);
3688 }
3689
3690 static int redist_disable_lpis(void)
3691 {
3692         void __iomem *rbase = gic_data_rdist_rd_base();
3693         u64 timeout = USEC_PER_SEC;
3694         u64 val;
3695
3696         if (!gic_rdists_supports_plpis()) {
3697                 pr_info("CPU%d: LPIs not supported\n", smp_processor_id());
3698                 return -ENXIO;
3699         }
3700
3701         val = readl_relaxed(rbase + GICR_CTLR);
3702         if (!(val & GICR_CTLR_ENABLE_LPIS))
3703                 return 0;
3704
3705         /*
3706          * If coming via a CPU hotplug event, we don't need to disable
3707          * LPIs before trying to re-enable them. They are already
3708          * configured and all is well in the world.
3709          *
3710          * If running with preallocated tables, there is nothing to do.
3711          */
3712         if (gic_data_rdist()->lpi_enabled ||
3713             (gic_rdists->flags & RDIST_FLAGS_RD_TABLES_PREALLOCATED))
3714                 return 0;
3715
3716         /*
3717          * From that point on, we only try to do some damage control.
3718          */
3719         pr_warn("GICv3: CPU%d: Booted with LPIs enabled, memory probably corrupted\n",
3720                 smp_processor_id());
3721         add_taint(TAINT_CRAP, LOCKDEP_STILL_OK);
3722
3723         /* Disable LPIs */
3724         val &= ~GICR_CTLR_ENABLE_LPIS;
3725         writel_relaxed(val, rbase + GICR_CTLR);
3726
3727         /* Make sure any change to GICR_CTLR is observable by the GIC */
3728         dsb(sy);
3729
3730         /*
3731          * Software must observe RWP==0 after clearing GICR_CTLR.EnableLPIs
3732          * from 1 to 0 before programming GICR_PEND{PROP}BASER registers.
3733          * Error out if we time out waiting for RWP to clear.
3734          */
3735         while (readl_relaxed(rbase + GICR_CTLR) & GICR_CTLR_RWP) {
3736                 if (!timeout) {
3737                         pr_err("CPU%d: Timeout while disabling LPIs\n",
3738                                smp_processor_id());
3739                         return -ETIMEDOUT;
3740                 }
3741                 udelay(1);
3742                 timeout--;
3743         }
3744
3745         /*
3746          * After it has been written to 1, it is IMPLEMENTATION
3747          * DEFINED whether GICR_CTLR.EnableLPI becomes RES1 or can be
3748          * cleared to 0. Error out if clearing the bit failed.
3749          */
3750         if (readl_relaxed(rbase + GICR_CTLR) & GICR_CTLR_ENABLE_LPIS) {
3751                 pr_err("CPU%d: Failed to disable LPIs\n", smp_processor_id());
3752                 return -EBUSY;
3753         }
3754
3755         return 0;
3756 }
3757
3758 int its_cpu_init(void)
3759 {
3760         if (!list_empty(&its_nodes)) {
3761                 int ret;
3762
3763                 ret = redist_disable_lpis();
3764                 if (ret)
3765                         return ret;
3766
3767                 its_cpu_init_lpis();
3768                 its_cpu_init_collections();
3769         }
3770
3771         return 0;
3772 }
3773
3774 static const struct of_device_id its_device_id[] = {
3775         {       .compatible     = "arm,gic-v3-its",     },
3776         {},
3777 };
3778
3779 static int __init its_of_probe(struct device_node *node)
3780 {
3781         struct device_node *np;
3782         struct resource res;
3783
3784         for (np = of_find_matching_node(node, its_device_id); np;
3785              np = of_find_matching_node(np, its_device_id)) {
3786                 if (!of_device_is_available(np))
3787                         continue;
3788                 if (!of_property_read_bool(np, "msi-controller")) {
3789                         pr_warn("%pOF: no msi-controller property, ITS ignored\n",
3790                                 np);
3791                         continue;
3792                 }
3793
3794                 if (of_address_to_resource(np, 0, &res)) {
3795                         pr_warn("%pOF: no regs?\n", np);
3796                         continue;
3797                 }
3798
3799                 its_probe_one(&res, &np->fwnode, of_node_to_nid(np));
3800         }
3801         return 0;
3802 }
3803
3804 #ifdef CONFIG_ACPI
3805
3806 #define ACPI_GICV3_ITS_MEM_SIZE (SZ_128K)
3807
3808 #ifdef CONFIG_ACPI_NUMA
3809 struct its_srat_map {
3810         /* numa node id */
3811         u32     numa_node;
3812         /* GIC ITS ID */
3813         u32     its_id;
3814 };
3815
3816 static struct its_srat_map *its_srat_maps __initdata;
3817 static int its_in_srat __initdata;
3818
3819 static int __init acpi_get_its_numa_node(u32 its_id)
3820 {
3821         int i;
3822
3823         for (i = 0; i < its_in_srat; i++) {
3824                 if (its_id == its_srat_maps[i].its_id)
3825                         return its_srat_maps[i].numa_node;
3826         }
3827         return NUMA_NO_NODE;
3828 }
3829
3830 static int __init gic_acpi_match_srat_its(struct acpi_subtable_header *header,
3831                                           const unsigned long end)
3832 {
3833         return 0;
3834 }
3835
3836 static int __init gic_acpi_parse_srat_its(struct acpi_subtable_header *header,
3837                          const unsigned long end)
3838 {
3839         int node;
3840         struct acpi_srat_gic_its_affinity *its_affinity;
3841
3842         its_affinity = (struct acpi_srat_gic_its_affinity *)header;
3843         if (!its_affinity)
3844                 return -EINVAL;
3845
3846         if (its_affinity->header.length < sizeof(*its_affinity)) {
3847                 pr_err("SRAT: Invalid header length %d in ITS affinity\n",
3848                         its_affinity->header.length);
3849                 return -EINVAL;
3850         }
3851
3852         node = acpi_map_pxm_to_node(its_affinity->proximity_domain);
3853
3854         if (node == NUMA_NO_NODE || node >= MAX_NUMNODES) {
3855                 pr_err("SRAT: Invalid NUMA node %d in ITS affinity\n", node);
3856                 return 0;
3857         }
3858
3859         its_srat_maps[its_in_srat].numa_node = node;
3860         its_srat_maps[its_in_srat].its_id = its_affinity->its_id;
3861         its_in_srat++;
3862         pr_info("SRAT: PXM %d -> ITS %d -> Node %d\n",
3863                 its_affinity->proximity_domain, its_affinity->its_id, node);
3864
3865         return 0;
3866 }
3867
3868 static void __init acpi_table_parse_srat_its(void)
3869 {
3870         int count;
3871
3872         count = acpi_table_parse_entries(ACPI_SIG_SRAT,
3873                         sizeof(struct acpi_table_srat),
3874                         ACPI_SRAT_TYPE_GIC_ITS_AFFINITY,
3875                         gic_acpi_match_srat_its, 0);
3876         if (count <= 0)
3877                 return;
3878
3879         its_srat_maps = kmalloc_array(count, sizeof(struct its_srat_map),
3880                                       GFP_KERNEL);
3881         if (!its_srat_maps) {
3882                 pr_warn("SRAT: Failed to allocate memory for its_srat_maps!\n");
3883                 return;
3884         }
3885
3886         acpi_table_parse_entries(ACPI_SIG_SRAT,
3887                         sizeof(struct acpi_table_srat),
3888                         ACPI_SRAT_TYPE_GIC_ITS_AFFINITY,
3889                         gic_acpi_parse_srat_its, 0);
3890 }
3891
3892 /* free the its_srat_maps after ITS probing */
3893 static void __init acpi_its_srat_maps_free(void)
3894 {
3895         kfree(its_srat_maps);
3896 }
3897 #else
3898 static void __init acpi_table_parse_srat_its(void)      { }
3899 static int __init acpi_get_its_numa_node(u32 its_id) { return NUMA_NO_NODE; }
3900 static void __init acpi_its_srat_maps_free(void) { }
3901 #endif
3902
3903 static int __init gic_acpi_parse_madt_its(struct acpi_subtable_header *header,
3904                                           const unsigned long end)
3905 {
3906         struct acpi_madt_generic_translator *its_entry;
3907         struct fwnode_handle *dom_handle;
3908         struct resource res;
3909         int err;
3910
3911         its_entry = (struct acpi_madt_generic_translator *)header;
3912         memset(&res, 0, sizeof(res));
3913         res.start = its_entry->base_address;
3914         res.end = its_entry->base_address + ACPI_GICV3_ITS_MEM_SIZE - 1;
3915         res.flags = IORESOURCE_MEM;
3916
3917         dom_handle = irq_domain_alloc_fwnode((void *)its_entry->base_address);
3918         if (!dom_handle) {
3919                 pr_err("ITS@%pa: Unable to allocate GICv3 ITS domain token\n",
3920                        &res.start);
3921                 return -ENOMEM;
3922         }
3923
3924         err = iort_register_domain_token(its_entry->translation_id, res.start,
3925                                          dom_handle);
3926         if (err) {
3927                 pr_err("ITS@%pa: Unable to register GICv3 ITS domain token (ITS ID %d) to IORT\n",
3928                        &res.start, its_entry->translation_id);
3929                 goto dom_err;
3930         }
3931
3932         err = its_probe_one(&res, dom_handle,
3933                         acpi_get_its_numa_node(its_entry->translation_id));
3934         if (!err)
3935                 return 0;
3936
3937         iort_deregister_domain_token(its_entry->translation_id);
3938 dom_err:
3939         irq_domain_free_fwnode(dom_handle);
3940         return err;
3941 }
3942
3943 static void __init its_acpi_probe(void)
3944 {
3945         acpi_table_parse_srat_its();
3946         acpi_table_parse_madt(ACPI_MADT_TYPE_GENERIC_TRANSLATOR,
3947                               gic_acpi_parse_madt_its, 0);
3948         acpi_its_srat_maps_free();
3949 }
3950 #else
3951 static void __init its_acpi_probe(void) { }
3952 #endif
3953
3954 int __init its_init(struct fwnode_handle *handle, struct rdists *rdists,
3955                     struct irq_domain *parent_domain)
3956 {
3957         struct device_node *of_node;
3958         struct its_node *its;
3959         bool has_v4 = false;
3960         int err;
3961
3962         its_parent = parent_domain;
3963         of_node = to_of_node(handle);
3964         if (of_node)
3965                 its_of_probe(of_node);
3966         else
3967                 its_acpi_probe();
3968
3969         if (list_empty(&its_nodes)) {
3970                 pr_warn("ITS: No ITS available, not enabling LPIs\n");
3971                 return -ENXIO;
3972         }
3973
3974         gic_rdists = rdists;
3975
3976         err = allocate_lpi_tables();
3977         if (err)
3978                 return err;
3979
3980         list_for_each_entry(its, &its_nodes, entry)
3981                 has_v4 |= its->is_v4;
3982
3983         if (has_v4 & rdists->has_vlpis) {
3984                 if (its_init_vpe_domain() ||
3985                     its_init_v4(parent_domain, &its_vpe_domain_ops)) {
3986                         rdists->has_vlpis = false;
3987                         pr_err("ITS: Disabling GICv4 support\n");
3988                 }
3989         }
3990
3991         register_syscore_ops(&its_syscore_ops);
3992
3993         return 0;
3994 }