]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/arm64/arm64/gicv3_its.c
Use vm_page_unwire_noq() instead of directly modifying page wire counts.
[FreeBSD/FreeBSD.git] / sys / arm64 / arm64 / gicv3_its.c
1 /*-
2  * Copyright (c) 2015-2016 The FreeBSD Foundation
3  * All rights reserved.
4  *
5  * This software was developed by Andrew Turner under
6  * the sponsorship of the FreeBSD Foundation.
7  *
8  * This software was developed by Semihalf under
9  * the sponsorship of the FreeBSD Foundation.
10  *
11  * Redistribution and use in source and binary forms, with or without
12  * modification, are permitted provided that the following conditions
13  * are met:
14  * 1. Redistributions of source code must retain the above copyright
15  *    notice, this list of conditions and the following disclaimer.
16  * 2. Redistributions in binary form must reproduce the above copyright
17  *    notice, this list of conditions and the following disclaimer in the
18  *    documentation and/or other materials provided with the distribution.
19  *
20  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
21  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23  * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
24  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
25  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
26  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
27  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
28  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
29  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
30  * SUCH DAMAGE.
31  */
32
33 #include "opt_acpi.h"
34 #include "opt_platform.h"
35
36 #include <sys/cdefs.h>
37 __FBSDID("$FreeBSD$");
38
39 #include <sys/param.h>
40 #include <sys/systm.h>
41 #include <sys/bus.h>
42 #include <sys/cpuset.h>
43 #include <sys/endian.h>
44 #include <sys/kernel.h>
45 #include <sys/malloc.h>
46 #include <sys/module.h>
47 #include <sys/proc.h>
48 #include <sys/queue.h>
49 #include <sys/rman.h>
50 #include <sys/smp.h>
51 #include <sys/vmem.h>
52
53 #include <vm/vm.h>
54 #include <vm/pmap.h>
55
56 #include <machine/bus.h>
57 #include <machine/intr.h>
58
59 #include <arm/arm/gic_common.h>
60 #include <arm64/arm64/gic_v3_reg.h>
61 #include <arm64/arm64/gic_v3_var.h>
62
63 #ifdef FDT
64 #include <dev/ofw/openfirm.h>
65 #include <dev/ofw/ofw_bus.h>
66 #include <dev/ofw/ofw_bus_subr.h>
67 #endif
68 #include <dev/pci/pcireg.h>
69 #include <dev/pci/pcivar.h>
70
71 #include "pcib_if.h"
72 #include "pic_if.h"
73 #include "msi_if.h"
74
75 MALLOC_DEFINE(M_GICV3_ITS, "GICv3 ITS",
76     "ARM GICv3 Interrupt Translation Service");
77
78 #define LPI_NIRQS               (64 * 1024)
79
80 /* The size and alignment of the command circular buffer */
81 #define ITS_CMDQ_SIZE           (64 * 1024)     /* Must be a multiple of 4K */
82 #define ITS_CMDQ_ALIGN          (64 * 1024)
83
84 #define LPI_CONFTAB_SIZE        LPI_NIRQS
85 #define LPI_CONFTAB_ALIGN       (64 * 1024)
86 #define LPI_CONFTAB_MAX_ADDR    ((1ul << 48) - 1) /* We need a 47 bit PA */
87
88 /* 1 bit per SPI, PPI, and SGI (8k), and 1 bit per LPI (LPI_CONFTAB_SIZE) */
89 #define LPI_PENDTAB_SIZE        ((LPI_NIRQS + GIC_FIRST_LPI) / 8)
90 #define LPI_PENDTAB_ALIGN       (64 * 1024)
91 #define LPI_PENDTAB_MAX_ADDR    ((1ul << 48) - 1) /* We need a 47 bit PA */
92
93 #define LPI_INT_TRANS_TAB_ALIGN 256
94 #define LPI_INT_TRANS_TAB_MAX_ADDR ((1ul << 48) - 1)
95
96 /* ITS commands encoding */
97 #define ITS_CMD_MOVI            (0x01)
98 #define ITS_CMD_SYNC            (0x05)
99 #define ITS_CMD_MAPD            (0x08)
100 #define ITS_CMD_MAPC            (0x09)
101 #define ITS_CMD_MAPTI           (0x0a)
102 #define ITS_CMD_MAPI            (0x0b)
103 #define ITS_CMD_INV             (0x0c)
104 #define ITS_CMD_INVALL          (0x0d)
105 /* Command */
106 #define CMD_COMMAND_MASK        (0xFFUL)
107 /* PCI device ID */
108 #define CMD_DEVID_SHIFT         (32)
109 #define CMD_DEVID_MASK          (0xFFFFFFFFUL << CMD_DEVID_SHIFT)
110 /* Size of IRQ ID bitfield */
111 #define CMD_SIZE_MASK           (0xFFUL)
112 /* Virtual LPI ID */
113 #define CMD_ID_MASK             (0xFFFFFFFFUL)
114 /* Physical LPI ID */
115 #define CMD_PID_SHIFT           (32)
116 #define CMD_PID_MASK            (0xFFFFFFFFUL << CMD_PID_SHIFT)
117 /* Collection */
118 #define CMD_COL_MASK            (0xFFFFUL)
119 /* Target (CPU or Re-Distributor) */
120 #define CMD_TARGET_SHIFT        (16)
121 #define CMD_TARGET_MASK         (0xFFFFFFFFUL << CMD_TARGET_SHIFT)
122 /* Interrupt Translation Table address */
123 #define CMD_ITT_MASK            (0xFFFFFFFFFF00UL)
124 /* Valid command bit */
125 #define CMD_VALID_SHIFT         (63)
126 #define CMD_VALID_MASK          (1UL << CMD_VALID_SHIFT)
127
128 #define ITS_TARGET_NONE         0xFBADBEEF
129
130 /* LPI chunk owned by ITS device */
131 struct lpi_chunk {
132         u_int   lpi_base;
133         u_int   lpi_free;       /* First free LPI in set */
134         u_int   lpi_num;        /* Total number of LPIs in chunk */
135         u_int   lpi_busy;       /* Number of busy LPIs in chink */
136 };
137
138 /* ITS device */
139 struct its_dev {
140         TAILQ_ENTRY(its_dev)    entry;
141         /* PCI device */
142         device_t                pci_dev;
143         /* Device ID (i.e. PCI device ID) */
144         uint32_t                devid;
145         /* List of assigned LPIs */
146         struct lpi_chunk        lpis;
147         /* Virtual address of ITT */
148         vm_offset_t             itt;
149         size_t                  itt_size;
150 };
151
152 /*
153  * ITS command descriptor.
154  * Idea for command description passing taken from Linux.
155  */
156 struct its_cmd_desc {
157         uint8_t cmd_type;
158
159         union {
160                 struct {
161                         struct its_dev *its_dev;
162                         struct its_col *col;
163                         uint32_t id;
164                 } cmd_desc_movi;
165
166                 struct {
167                         struct its_col *col;
168                 } cmd_desc_sync;
169
170                 struct {
171                         struct its_col *col;
172                         uint8_t valid;
173                 } cmd_desc_mapc;
174
175                 struct {
176                         struct its_dev *its_dev;
177                         struct its_col *col;
178                         uint32_t pid;
179                         uint32_t id;
180                 } cmd_desc_mapvi;
181
182                 struct {
183                         struct its_dev *its_dev;
184                         struct its_col *col;
185                         uint32_t pid;
186                 } cmd_desc_mapi;
187
188                 struct {
189                         struct its_dev *its_dev;
190                         uint8_t valid;
191                 } cmd_desc_mapd;
192
193                 struct {
194                         struct its_dev *its_dev;
195                         struct its_col *col;
196                         uint32_t pid;
197                 } cmd_desc_inv;
198
199                 struct {
200                         struct its_col *col;
201                 } cmd_desc_invall;
202         };
203 };
204
205 /* ITS command. Each command is 32 bytes long */
206 struct its_cmd {
207         uint64_t        cmd_dword[4];   /* ITS command double word */
208 };
209
210 /* An ITS private table */
211 struct its_ptable {
212         vm_offset_t     ptab_vaddr;
213         unsigned long   ptab_size;
214 };
215
216 /* ITS collection description. */
217 struct its_col {
218         uint64_t        col_target;     /* Target Re-Distributor */
219         uint64_t        col_id;         /* Collection ID */
220 };
221
222 struct gicv3_its_irqsrc {
223         struct intr_irqsrc      gi_isrc;
224         u_int                   gi_irq;
225         struct its_dev          *gi_its_dev;
226 };
227
228 struct gicv3_its_softc {
229         struct intr_pic *sc_pic;
230         struct resource *sc_its_res;
231
232         cpuset_t        sc_cpus;
233         u_int           gic_irq_cpu;
234
235         struct its_ptable sc_its_ptab[GITS_BASER_NUM];
236         struct its_col *sc_its_cols[MAXCPU];    /* Per-CPU collections */
237
238         /*
239          * TODO: We should get these from the parent as we only want a
240          * single copy of each across the interrupt controller.
241          */
242         vm_offset_t sc_conf_base;
243         vm_offset_t sc_pend_base[MAXCPU];
244
245         /* Command handling */
246         struct mtx sc_its_cmd_lock;
247         struct its_cmd *sc_its_cmd_base; /* Command circular buffer address */
248         size_t sc_its_cmd_next_idx;
249
250         vmem_t *sc_irq_alloc;
251         struct gicv3_its_irqsrc *sc_irqs;
252         u_int   sc_irq_base;
253         u_int   sc_irq_length;
254
255         struct mtx sc_its_dev_lock;
256         TAILQ_HEAD(its_dev_list, its_dev) sc_its_dev_list;
257
258 #define ITS_FLAGS_CMDQ_FLUSH            0x00000001
259 #define ITS_FLAGS_LPI_CONF_FLUSH        0x00000002
260 #define ITS_FLAGS_ERRATA_CAVIUM_22375   0x00000004
261         u_int sc_its_flags;
262 };
263
264 typedef void (its_quirk_func_t)(device_t);
265 static its_quirk_func_t its_quirk_cavium_22375;
266
267 static const struct {
268         const char *desc;
269         uint32_t iidr;
270         uint32_t iidr_mask;
271         its_quirk_func_t *func;
272 } its_quirks[] = {
273         {
274                 /* Cavium ThunderX Pass 1.x */
275                 .desc = "Cavoum ThunderX errata: 22375, 24313",
276                 .iidr = GITS_IIDR_RAW(GITS_IIDR_IMPL_CAVIUM,
277                     GITS_IIDR_PROD_THUNDER, GITS_IIDR_VAR_THUNDER_1, 0),
278                 .iidr_mask = ~GITS_IIDR_REVISION_MASK,
279                 .func = its_quirk_cavium_22375,
280         },
281 };
282
283 #define gic_its_read_4(sc, reg)                 \
284     bus_read_4((sc)->sc_its_res, (reg))
285 #define gic_its_read_8(sc, reg)                 \
286     bus_read_8((sc)->sc_its_res, (reg))
287
288 #define gic_its_write_4(sc, reg, val)           \
289     bus_write_4((sc)->sc_its_res, (reg), (val))
290 #define gic_its_write_8(sc, reg, val)           \
291     bus_write_8((sc)->sc_its_res, (reg), (val))
292
293 static device_attach_t gicv3_its_attach;
294 static device_detach_t gicv3_its_detach;
295
296 static pic_disable_intr_t gicv3_its_disable_intr;
297 static pic_enable_intr_t gicv3_its_enable_intr;
298 static pic_map_intr_t gicv3_its_map_intr;
299 static pic_setup_intr_t gicv3_its_setup_intr;
300 static pic_post_filter_t gicv3_its_post_filter;
301 static pic_post_ithread_t gicv3_its_post_ithread;
302 static pic_pre_ithread_t gicv3_its_pre_ithread;
303 static pic_bind_intr_t gicv3_its_bind_intr;
304 #ifdef SMP
305 static pic_init_secondary_t gicv3_its_init_secondary;
306 #endif
307 static msi_alloc_msi_t gicv3_its_alloc_msi;
308 static msi_release_msi_t gicv3_its_release_msi;
309 static msi_alloc_msix_t gicv3_its_alloc_msix;
310 static msi_release_msix_t gicv3_its_release_msix;
311 static msi_map_msi_t gicv3_its_map_msi;
312
313 static void its_cmd_movi(device_t, struct gicv3_its_irqsrc *);
314 static void its_cmd_mapc(device_t, struct its_col *, uint8_t);
315 static void its_cmd_mapti(device_t, struct gicv3_its_irqsrc *);
316 static void its_cmd_mapd(device_t, struct its_dev *, uint8_t);
317 static void its_cmd_inv(device_t, struct its_dev *, struct gicv3_its_irqsrc *);
318 static void its_cmd_invall(device_t, struct its_col *);
319
320 static device_method_t gicv3_its_methods[] = {
321         /* Device interface */
322         DEVMETHOD(device_detach,        gicv3_its_detach),
323
324         /* Interrupt controller interface */
325         DEVMETHOD(pic_disable_intr,     gicv3_its_disable_intr),
326         DEVMETHOD(pic_enable_intr,      gicv3_its_enable_intr),
327         DEVMETHOD(pic_map_intr,         gicv3_its_map_intr),
328         DEVMETHOD(pic_setup_intr,       gicv3_its_setup_intr),
329         DEVMETHOD(pic_post_filter,      gicv3_its_post_filter),
330         DEVMETHOD(pic_post_ithread,     gicv3_its_post_ithread),
331         DEVMETHOD(pic_pre_ithread,      gicv3_its_pre_ithread),
332 #ifdef SMP
333         DEVMETHOD(pic_bind_intr,        gicv3_its_bind_intr),
334         DEVMETHOD(pic_init_secondary,   gicv3_its_init_secondary),
335 #endif
336
337         /* MSI/MSI-X */
338         DEVMETHOD(msi_alloc_msi,        gicv3_its_alloc_msi),
339         DEVMETHOD(msi_release_msi,      gicv3_its_release_msi),
340         DEVMETHOD(msi_alloc_msix,       gicv3_its_alloc_msix),
341         DEVMETHOD(msi_release_msix,     gicv3_its_release_msix),
342         DEVMETHOD(msi_map_msi,          gicv3_its_map_msi),
343
344         /* End */
345         DEVMETHOD_END
346 };
347
348 static DEFINE_CLASS_0(gic, gicv3_its_driver, gicv3_its_methods,
349     sizeof(struct gicv3_its_softc));
350
351 static void
352 gicv3_its_cmdq_init(struct gicv3_its_softc *sc)
353 {
354         vm_paddr_t cmd_paddr;
355         uint64_t reg, tmp;
356
357         /* Set up the command circular buffer */
358         sc->sc_its_cmd_base = contigmalloc(ITS_CMDQ_SIZE, M_GICV3_ITS,
359             M_WAITOK | M_ZERO, 0, (1ul << 48) - 1, ITS_CMDQ_ALIGN, 0);
360         sc->sc_its_cmd_next_idx = 0;
361
362         cmd_paddr = vtophys(sc->sc_its_cmd_base);
363
364         /* Set the base of the command buffer */
365         reg = GITS_CBASER_VALID |
366             (GITS_CBASER_CACHE_NIWAWB << GITS_CBASER_CACHE_SHIFT) |
367             cmd_paddr | (GITS_CBASER_SHARE_IS << GITS_CBASER_SHARE_SHIFT) |
368             (ITS_CMDQ_SIZE / 4096 - 1);
369         gic_its_write_8(sc, GITS_CBASER, reg);
370
371         /* Read back to check for fixed value fields */
372         tmp = gic_its_read_8(sc, GITS_CBASER);
373
374         if ((tmp & GITS_CBASER_SHARE_MASK) !=
375             (GITS_CBASER_SHARE_IS << GITS_CBASER_SHARE_SHIFT)) {
376                 /* Check if the hardware reported non-shareable */
377                 if ((tmp & GITS_CBASER_SHARE_MASK) ==
378                     (GITS_CBASER_SHARE_NS << GITS_CBASER_SHARE_SHIFT)) {
379                         /* If so remove the cache attribute */
380                         reg &= ~GITS_CBASER_CACHE_MASK;
381                         reg &= ~GITS_CBASER_SHARE_MASK;
382                         /* Set to Non-cacheable, Non-shareable */
383                         reg |= GITS_CBASER_CACHE_NIN << GITS_CBASER_CACHE_SHIFT;
384                         reg |= GITS_CBASER_SHARE_NS << GITS_CBASER_SHARE_SHIFT;
385
386                         gic_its_write_8(sc, GITS_CBASER, reg);
387                 }
388
389                 /* The command queue has to be flushed after each command */
390                 sc->sc_its_flags |= ITS_FLAGS_CMDQ_FLUSH;
391         }
392
393         /* Get the next command from the start of the buffer */
394         gic_its_write_8(sc, GITS_CWRITER, 0x0);
395 }
396
397 static int
398 gicv3_its_table_init(device_t dev, struct gicv3_its_softc *sc)
399 {
400         vm_offset_t table;
401         vm_paddr_t paddr;
402         uint64_t cache, reg, share, tmp, type;
403         size_t esize, its_tbl_size, nidents, nitspages, npages;
404         int i, page_size;
405         int devbits;
406
407         if ((sc->sc_its_flags & ITS_FLAGS_ERRATA_CAVIUM_22375) != 0) {
408                 /*
409                  * GITS_TYPER[17:13] of ThunderX reports that device IDs
410                  * are to be 21 bits in length. The entry size of the ITS
411                  * table can be read from GITS_BASERn[52:48] and on ThunderX
412                  * is supposed to be 8 bytes in length (for device table).
413                  * Finally the page size that is to be used by ITS to access
414                  * this table will be set to 64KB.
415                  *
416                  * This gives 0x200000 entries of size 0x8 bytes covered by
417                  * 256 pages each of which 64KB in size. The number of pages
418                  * (minus 1) should then be written to GITS_BASERn[7:0]. In
419                  * that case this value would be 0xFF but on ThunderX the
420                  * maximum value that HW accepts is 0xFD.
421                  *
422                  * Set an arbitrary number of device ID bits to 20 in order
423                  * to limit the number of entries in ITS device table to
424                  * 0x100000 and the table size to 8MB.
425                  */
426                 devbits = 20;
427                 cache = 0;
428         } else {
429                 devbits = GITS_TYPER_DEVB(gic_its_read_8(sc, GITS_TYPER));
430                 cache = GITS_BASER_CACHE_WAWB;
431         }
432         share = GITS_BASER_SHARE_IS;
433         page_size = PAGE_SIZE_64K;
434
435         for (i = 0; i < GITS_BASER_NUM; i++) {
436                 reg = gic_its_read_8(sc, GITS_BASER(i));
437                 /* The type of table */
438                 type = GITS_BASER_TYPE(reg);
439                 /* The table entry size */
440                 esize = GITS_BASER_ESIZE(reg);
441
442                 switch(type) {
443                 case GITS_BASER_TYPE_DEV:
444                         nidents = (1 << devbits);
445                         its_tbl_size = esize * nidents;
446                         its_tbl_size = roundup2(its_tbl_size, PAGE_SIZE_64K);
447                         break;
448                 case GITS_BASER_TYPE_VP:
449                 case GITS_BASER_TYPE_PP: /* Undocumented? */
450                 case GITS_BASER_TYPE_IC:
451                         its_tbl_size = page_size;
452                         break;
453                 default:
454                         continue;
455                 }
456                 npages = howmany(its_tbl_size, PAGE_SIZE);
457
458                 /* Allocate the table */
459                 table = (vm_offset_t)contigmalloc(npages * PAGE_SIZE,
460                     M_GICV3_ITS, M_WAITOK | M_ZERO, 0, (1ul << 48) - 1,
461                     PAGE_SIZE_64K, 0);
462
463                 sc->sc_its_ptab[i].ptab_vaddr = table;
464                 sc->sc_its_ptab[i].ptab_size = npages * PAGE_SIZE;
465
466                 paddr = vtophys(table);
467
468                 while (1) {
469                         nitspages = howmany(its_tbl_size, page_size);
470
471                         /* Clear the fields we will be setting */
472                         reg &= ~(GITS_BASER_VALID |
473                             GITS_BASER_CACHE_MASK | GITS_BASER_TYPE_MASK |
474                             GITS_BASER_ESIZE_MASK | GITS_BASER_PA_MASK |
475                             GITS_BASER_SHARE_MASK | GITS_BASER_PSZ_MASK |
476                             GITS_BASER_SIZE_MASK);
477                         /* Set the new values */
478                         reg |= GITS_BASER_VALID |
479                             (cache << GITS_BASER_CACHE_SHIFT) |
480                             (type << GITS_BASER_TYPE_SHIFT) |
481                             ((esize - 1) << GITS_BASER_ESIZE_SHIFT) |
482                             paddr | (share << GITS_BASER_SHARE_SHIFT) |
483                             (nitspages - 1);
484
485                         switch (page_size) {
486                         case PAGE_SIZE:         /* 4KB */
487                                 reg |=
488                                     GITS_BASER_PSZ_4K << GITS_BASER_PSZ_SHIFT;
489                                 break;
490                         case PAGE_SIZE_16K:     /* 16KB */
491                                 reg |=
492                                     GITS_BASER_PSZ_4K << GITS_BASER_PSZ_SHIFT;
493                                 break;
494                         case PAGE_SIZE_64K:     /* 64KB */
495                                 reg |=
496                                     GITS_BASER_PSZ_64K << GITS_BASER_PSZ_SHIFT;
497                                 break;
498                         }
499
500                         gic_its_write_8(sc, GITS_BASER(i), reg);
501
502                         /* Read back to check */
503                         tmp = gic_its_read_8(sc, GITS_BASER(i));
504
505                         /* Do the snareability masks line up? */
506                         if ((tmp & GITS_BASER_SHARE_MASK) !=
507                             (reg & GITS_BASER_SHARE_MASK)) {
508                                 share = (tmp & GITS_BASER_SHARE_MASK) >>
509                                     GITS_BASER_SHARE_SHIFT;
510                                 continue;
511                         }
512
513                         if ((tmp & GITS_BASER_PSZ_MASK) !=
514                             (reg & GITS_BASER_PSZ_MASK)) {
515                                 switch (page_size) {
516                                 case PAGE_SIZE_16K:
517                                         page_size = PAGE_SIZE;
518                                         continue;
519                                 case PAGE_SIZE_64K:
520                                         page_size = PAGE_SIZE_16K;
521                                         continue;
522                                 }
523                         }
524
525                         if (tmp != reg) {
526                                 device_printf(dev, "GITS_BASER%d: "
527                                     "unable to be updated: %lx != %lx\n",
528                                     i, reg, tmp);
529                                 return (ENXIO);
530                         }
531
532                         /* We should have made all needed changes */
533                         break;
534                 }
535         }
536
537         return (0);
538 }
539
540 static void
541 gicv3_its_conftable_init(struct gicv3_its_softc *sc)
542 {
543
544         sc->sc_conf_base = (vm_offset_t)contigmalloc(LPI_CONFTAB_SIZE,
545             M_GICV3_ITS, M_WAITOK, 0, LPI_CONFTAB_MAX_ADDR, LPI_CONFTAB_ALIGN,
546             0);
547
548         /* Set the default configuration */
549         memset((void *)sc->sc_conf_base, GIC_PRIORITY_MAX | LPI_CONF_GROUP1,
550             LPI_CONFTAB_SIZE);
551
552         /* Flush the table to memory */
553         cpu_dcache_wb_range(sc->sc_conf_base, LPI_CONFTAB_SIZE);
554 }
555
556 static void
557 gicv3_its_pendtables_init(struct gicv3_its_softc *sc)
558 {
559         int i;
560
561         for (i = 0; i <= mp_maxid; i++) {
562                 if (CPU_ISSET(i, &sc->sc_cpus) == 0)
563                         continue;
564
565                 sc->sc_pend_base[i] = (vm_offset_t)contigmalloc(
566                     LPI_PENDTAB_SIZE, M_GICV3_ITS, M_WAITOK | M_ZERO,
567                     0, LPI_PENDTAB_MAX_ADDR, LPI_PENDTAB_ALIGN, 0);
568
569                 /* Flush so the ITS can see the memory */
570                 cpu_dcache_wb_range((vm_offset_t)sc->sc_pend_base,
571                     LPI_PENDTAB_SIZE);
572         }
573 }
574
575 static int
576 its_init_cpu(device_t dev, struct gicv3_its_softc *sc)
577 {
578         device_t gicv3;
579         vm_paddr_t target;
580         uint64_t xbaser, tmp;
581         uint32_t ctlr;
582         u_int cpuid;
583         int domain;
584
585         if (!CPU_ISSET(PCPU_GET(cpuid), &sc->sc_cpus))
586                 return (0);
587
588         if (bus_get_domain(dev, &domain) == 0) {
589                 if (PCPU_GET(domain) != domain)
590                         return (0);
591         }
592
593         gicv3 = device_get_parent(dev);
594         cpuid = PCPU_GET(cpuid);
595
596         /* Check if the ITS is enabled on this CPU */
597         if ((gic_r_read_4(gicv3, GICR_TYPER) & GICR_TYPER_PLPIS) == 0) {
598                 return (ENXIO);
599         }
600
601         /* Disable LPIs */
602         ctlr = gic_r_read_4(gicv3, GICR_CTLR);
603         ctlr &= ~GICR_CTLR_LPI_ENABLE;
604         gic_r_write_4(gicv3, GICR_CTLR, ctlr);
605
606         /* Make sure changes are observable my the GIC */
607         dsb(sy);
608
609         /*
610          * Set the redistributor base
611          */
612         xbaser = vtophys(sc->sc_conf_base) |
613             (GICR_PROPBASER_SHARE_IS << GICR_PROPBASER_SHARE_SHIFT) |
614             (GICR_PROPBASER_CACHE_NIWAWB << GICR_PROPBASER_CACHE_SHIFT) |
615             (flsl(LPI_CONFTAB_SIZE | GIC_FIRST_LPI) - 1);
616         gic_r_write_8(gicv3, GICR_PROPBASER, xbaser);
617
618         /* Check the cache attributes we set */
619         tmp = gic_r_read_8(gicv3, GICR_PROPBASER);
620
621         if ((tmp & GICR_PROPBASER_SHARE_MASK) !=
622             (xbaser & GICR_PROPBASER_SHARE_MASK)) {
623                 if ((tmp & GICR_PROPBASER_SHARE_MASK) ==
624                     (GICR_PROPBASER_SHARE_NS << GICR_PROPBASER_SHARE_SHIFT)) {
625                         /* We need to mark as non-cacheable */
626                         xbaser &= ~(GICR_PROPBASER_SHARE_MASK |
627                             GICR_PROPBASER_CACHE_MASK);
628                         /* Non-cacheable */
629                         xbaser |= GICR_PROPBASER_CACHE_NIN <<
630                             GICR_PROPBASER_CACHE_SHIFT;
631                         /* Non-sareable */
632                         xbaser |= GICR_PROPBASER_SHARE_NS <<
633                             GICR_PROPBASER_SHARE_SHIFT;
634                         gic_r_write_8(gicv3, GICR_PROPBASER, xbaser);
635                 }
636                 sc->sc_its_flags |= ITS_FLAGS_LPI_CONF_FLUSH;
637         }
638
639         /*
640          * Set the LPI pending table base
641          */
642         xbaser = vtophys(sc->sc_pend_base[cpuid]) |
643             (GICR_PENDBASER_CACHE_NIWAWB << GICR_PENDBASER_CACHE_SHIFT) |
644             (GICR_PENDBASER_SHARE_IS << GICR_PENDBASER_SHARE_SHIFT);
645
646         gic_r_write_8(gicv3, GICR_PENDBASER, xbaser);
647
648         tmp = gic_r_read_8(gicv3, GICR_PENDBASER);
649
650         if ((tmp & GICR_PENDBASER_SHARE_MASK) ==
651             (GICR_PENDBASER_SHARE_NS << GICR_PENDBASER_SHARE_SHIFT)) {
652                 /* Clear the cahce and shareability bits */
653                 xbaser &= ~(GICR_PENDBASER_CACHE_MASK |
654                     GICR_PENDBASER_SHARE_MASK);
655                 /* Mark as non-shareable */
656                 xbaser |= GICR_PENDBASER_SHARE_NS << GICR_PENDBASER_SHARE_SHIFT;
657                 /* And non-cacheable */
658                 xbaser |= GICR_PENDBASER_CACHE_NIN <<
659                     GICR_PENDBASER_CACHE_SHIFT;
660         }
661
662         /* Enable LPIs */
663         ctlr = gic_r_read_4(gicv3, GICR_CTLR);
664         ctlr |= GICR_CTLR_LPI_ENABLE;
665         gic_r_write_4(gicv3, GICR_CTLR, ctlr);
666
667         /* Make sure the GIC has seen everything */
668         dsb(sy);
669
670         if ((gic_its_read_8(sc, GITS_TYPER) & GITS_TYPER_PTA) != 0) {
671                 /* This ITS wants the redistributor physical address */
672                 target = vtophys(gicv3_get_redist_vaddr(dev));
673         } else {
674                 /* This ITS wants the unique processor number */
675                 target = GICR_TYPER_CPUNUM(gic_r_read_8(gicv3, GICR_TYPER));
676         }
677
678         sc->sc_its_cols[cpuid]->col_target = target;
679         sc->sc_its_cols[cpuid]->col_id = cpuid;
680
681         its_cmd_mapc(dev, sc->sc_its_cols[cpuid], 1);
682         its_cmd_invall(dev, sc->sc_its_cols[cpuid]);
683
684         return (0);
685 }
686
687 static int
688 gicv3_its_attach(device_t dev)
689 {
690         struct gicv3_its_softc *sc;
691         const char *name;
692         uint32_t iidr;
693         int domain, err, i, rid;
694
695         sc = device_get_softc(dev);
696
697         rid = 0;
698         sc->sc_its_res = bus_alloc_resource_any(dev, SYS_RES_MEMORY, &rid,
699             RF_ACTIVE);
700         if (sc->sc_its_res == NULL) {
701                 device_printf(dev, "Could not allocate memory\n");
702                 return (ENXIO);
703         }
704
705         iidr = gic_its_read_4(sc, GITS_IIDR);
706         for (i = 0; i < nitems(its_quirks); i++) {
707                 if ((iidr & its_quirks[i].iidr_mask) == its_quirks[i].iidr) {
708                         if (bootverbose) {
709                                 device_printf(dev, "Applying %s\n",
710                                     its_quirks[i].desc);
711                         }
712                         its_quirks[i].func(dev);
713                         break;
714                 }
715         }
716
717         /* Allocate the private tables */
718         err = gicv3_its_table_init(dev, sc);
719         if (err != 0)
720                 return (err);
721
722         /* Protects access to the device list */
723         mtx_init(&sc->sc_its_dev_lock, "ITS device lock", NULL, MTX_SPIN);
724
725         /* Protects access to the ITS command circular buffer. */
726         mtx_init(&sc->sc_its_cmd_lock, "ITS cmd lock", NULL, MTX_SPIN);
727
728         if (bus_get_domain(dev, &domain) == 0) {
729                 CPU_ZERO(&sc->sc_cpus);
730                 if (domain < MAXMEMDOM)
731                         CPU_COPY(&cpuset_domain[domain], &sc->sc_cpus);
732         } else {
733                 CPU_COPY(&all_cpus, &sc->sc_cpus);
734         }
735
736         /* Allocate the command circular buffer */
737         gicv3_its_cmdq_init(sc);
738
739         /* Allocate the per-CPU collections */
740         for (int cpu = 0; cpu <= mp_maxid; cpu++)
741                 if (CPU_ISSET(cpu, &sc->sc_cpus) != 0)
742                         sc->sc_its_cols[cpu] = malloc(
743                             sizeof(*sc->sc_its_cols[0]), M_GICV3_ITS,
744                             M_WAITOK | M_ZERO);
745                 else
746                         sc->sc_its_cols[cpu] = NULL;
747
748         /* Enable the ITS */
749         gic_its_write_4(sc, GITS_CTLR,
750             gic_its_read_4(sc, GITS_CTLR) | GITS_CTLR_EN);
751
752         /* Create the LPI configuration table */
753         gicv3_its_conftable_init(sc);
754
755         /* And the pending tebles */
756         gicv3_its_pendtables_init(sc);
757
758         /* Enable LPIs on this CPU */
759         its_init_cpu(dev, sc);
760
761         TAILQ_INIT(&sc->sc_its_dev_list);
762
763         /*
764          * Create the vmem object to allocate INTRNG IRQs from. We try to
765          * use all IRQs not already used by the GICv3.
766          * XXX: This assumes there are no other interrupt controllers in the
767          * system.
768          */
769         sc->sc_irq_alloc = vmem_create("GICv3 ITS IRQs", 0,
770             gicv3_get_nirqs(dev), 1, 1, M_FIRSTFIT | M_WAITOK);
771
772         sc->sc_irqs = malloc(sizeof(*sc->sc_irqs) * sc->sc_irq_length,
773             M_GICV3_ITS, M_WAITOK | M_ZERO);
774         name = device_get_nameunit(dev);
775         for (i = 0; i < sc->sc_irq_length; i++) {
776                 sc->sc_irqs[i].gi_irq = i;
777                 err = intr_isrc_register(&sc->sc_irqs[i].gi_isrc, dev, 0,
778                     "%s,%u", name, i);
779         }
780
781         return (0);
782 }
783
784 static int
785 gicv3_its_detach(device_t dev)
786 {
787
788         return (ENXIO);
789 }
790
791 static void
792 its_quirk_cavium_22375(device_t dev)
793 {
794         struct gicv3_its_softc *sc;
795
796         sc = device_get_softc(dev);
797         sc->sc_its_flags |= ITS_FLAGS_ERRATA_CAVIUM_22375;
798 }
799
800 static void
801 gicv3_its_disable_intr(device_t dev, struct intr_irqsrc *isrc)
802 {
803         struct gicv3_its_softc *sc;
804         struct gicv3_its_irqsrc *girq;
805         uint8_t *conf;
806
807         sc = device_get_softc(dev);
808         girq = (struct gicv3_its_irqsrc *)isrc;
809         conf = (uint8_t *)sc->sc_conf_base;
810
811         conf[girq->gi_irq] &= ~LPI_CONF_ENABLE;
812
813         if ((sc->sc_its_flags & ITS_FLAGS_LPI_CONF_FLUSH) != 0) {
814                 /* Clean D-cache under command. */
815                 cpu_dcache_wb_range((vm_offset_t)&conf[girq->gi_irq], 1);
816         } else {
817                 /* DSB inner shareable, store */
818                 dsb(ishst);
819         }
820
821         its_cmd_inv(dev, girq->gi_its_dev, girq);
822 }
823
824 static void
825 gicv3_its_enable_intr(device_t dev, struct intr_irqsrc *isrc)
826 {
827         struct gicv3_its_softc *sc;
828         struct gicv3_its_irqsrc *girq;
829         uint8_t *conf;
830
831         sc = device_get_softc(dev);
832         girq = (struct gicv3_its_irqsrc *)isrc;
833         conf = (uint8_t *)sc->sc_conf_base;
834
835         conf[girq->gi_irq] |= LPI_CONF_ENABLE;
836
837         if ((sc->sc_its_flags & ITS_FLAGS_LPI_CONF_FLUSH) != 0) {
838                 /* Clean D-cache under command. */
839                 cpu_dcache_wb_range((vm_offset_t)&conf[girq->gi_irq], 1);
840         } else {
841                 /* DSB inner shareable, store */
842                 dsb(ishst);
843         }
844
845         its_cmd_inv(dev, girq->gi_its_dev, girq);
846 }
847
848 static int
849 gicv3_its_intr(void *arg, uintptr_t irq)
850 {
851         struct gicv3_its_softc *sc = arg;
852         struct gicv3_its_irqsrc *girq;
853         struct trapframe *tf;
854
855         irq -= sc->sc_irq_base;
856         girq = &sc->sc_irqs[irq];
857         if (girq == NULL)
858                 panic("gicv3_its_intr: Invalid interrupt %ld",
859                     irq + sc->sc_irq_base);
860
861         tf = curthread->td_intr_frame;
862         intr_isrc_dispatch(&girq->gi_isrc, tf);
863         return (FILTER_HANDLED);
864 }
865
866 static void
867 gicv3_its_pre_ithread(device_t dev, struct intr_irqsrc *isrc)
868 {
869         struct gicv3_its_irqsrc *girq;
870         struct gicv3_its_softc *sc;
871
872         sc = device_get_softc(dev);
873         girq = (struct gicv3_its_irqsrc *)isrc;
874         gicv3_its_disable_intr(dev, isrc);
875         gic_icc_write(EOIR1, girq->gi_irq + sc->sc_irq_base);
876 }
877
878 static void
879 gicv3_its_post_ithread(device_t dev, struct intr_irqsrc *isrc)
880 {
881
882         gicv3_its_enable_intr(dev, isrc);
883 }
884
885 static void
886 gicv3_its_post_filter(device_t dev, struct intr_irqsrc *isrc)
887 {
888         struct gicv3_its_irqsrc *girq;
889         struct gicv3_its_softc *sc;
890
891         sc = device_get_softc(dev);
892         girq = (struct gicv3_its_irqsrc *)isrc;
893         gic_icc_write(EOIR1, girq->gi_irq + sc->sc_irq_base);
894 }
895
896 static int
897 gicv3_its_bind_intr(device_t dev, struct intr_irqsrc *isrc)
898 {
899         struct gicv3_its_irqsrc *girq;
900         struct gicv3_its_softc *sc;
901
902         sc = device_get_softc(dev);
903         girq = (struct gicv3_its_irqsrc *)isrc;
904         if (CPU_EMPTY(&isrc->isrc_cpu)) {
905                 sc->gic_irq_cpu = intr_irq_next_cpu(sc->gic_irq_cpu,
906                     &sc->sc_cpus);
907                 CPU_SETOF(sc->gic_irq_cpu, &isrc->isrc_cpu);
908         }
909
910         its_cmd_movi(dev, girq);
911
912         return (0);
913 }
914
915 static int
916 gicv3_its_map_intr(device_t dev, struct intr_map_data *data,
917     struct intr_irqsrc **isrcp)
918 {
919
920         /*
921          * This should never happen, we only call this function to map
922          * interrupts found before the controller driver is ready.
923          */
924         panic("gicv3_its_map_intr: Unable to map a MSI interrupt");
925 }
926
927 static int
928 gicv3_its_setup_intr(device_t dev, struct intr_irqsrc *isrc,
929     struct resource *res, struct intr_map_data *data)
930 {
931
932         /* Bind the interrupt to a CPU */
933         gicv3_its_bind_intr(dev, isrc);
934
935         return (0);
936 }
937
938 #ifdef SMP
939 static void
940 gicv3_its_init_secondary(device_t dev)
941 {
942         struct gicv3_its_softc *sc;
943
944         sc = device_get_softc(dev);
945
946         /*
947          * This is fatal as otherwise we may bind interrupts to this CPU.
948          * We need a way to tell the interrupt framework to only bind to a
949          * subset of given CPUs when it performs the shuffle.
950          */
951         if (its_init_cpu(dev, sc) != 0)
952                 panic("gicv3_its_init_secondary: No usable ITS on CPU%d",
953                     PCPU_GET(cpuid));
954 }
955 #endif
956
957 static uint32_t
958 its_get_devid(device_t pci_dev)
959 {
960         uintptr_t id;
961
962         if (pci_get_id(pci_dev, PCI_ID_MSI, &id) != 0)
963                 panic("its_get_devid: Unable to get the MSI DeviceID");
964
965         return (id);
966 }
967
968 static struct its_dev *
969 its_device_find(device_t dev, device_t child)
970 {
971         struct gicv3_its_softc *sc;
972         struct its_dev *its_dev = NULL;
973
974         sc = device_get_softc(dev);
975
976         mtx_lock_spin(&sc->sc_its_dev_lock);
977         TAILQ_FOREACH(its_dev, &sc->sc_its_dev_list, entry) {
978                 if (its_dev->pci_dev == child)
979                         break;
980         }
981         mtx_unlock_spin(&sc->sc_its_dev_lock);
982
983         return (its_dev);
984 }
985
986 static struct its_dev *
987 its_device_get(device_t dev, device_t child, u_int nvecs)
988 {
989         struct gicv3_its_softc *sc;
990         struct its_dev *its_dev;
991         vmem_addr_t irq_base;
992         size_t esize;
993
994         sc = device_get_softc(dev);
995
996         its_dev = its_device_find(dev, child);
997         if (its_dev != NULL)
998                 return (its_dev);
999
1000         its_dev = malloc(sizeof(*its_dev), M_GICV3_ITS, M_NOWAIT | M_ZERO);
1001         if (its_dev == NULL)
1002                 return (NULL);
1003
1004         its_dev->pci_dev = child;
1005         its_dev->devid = its_get_devid(child);
1006
1007         its_dev->lpis.lpi_busy = 0;
1008         its_dev->lpis.lpi_num = nvecs;
1009         its_dev->lpis.lpi_free = nvecs;
1010
1011         if (vmem_alloc(sc->sc_irq_alloc, nvecs, M_FIRSTFIT | M_NOWAIT,
1012             &irq_base) != 0) {
1013                 free(its_dev, M_GICV3_ITS);
1014                 return (NULL);
1015         }
1016         its_dev->lpis.lpi_base = irq_base;
1017
1018         /* Get ITT entry size */
1019         esize = GITS_TYPER_ITTES(gic_its_read_8(sc, GITS_TYPER));
1020
1021         /*
1022          * Allocate ITT for this device.
1023          * PA has to be 256 B aligned. At least two entries for device.
1024          */
1025         its_dev->itt_size = roundup2(MAX(nvecs, 2) * esize, 256);
1026         its_dev->itt = (vm_offset_t)contigmalloc(its_dev->itt_size,
1027             M_GICV3_ITS, M_NOWAIT | M_ZERO, 0, LPI_INT_TRANS_TAB_MAX_ADDR,
1028             LPI_INT_TRANS_TAB_ALIGN, 0);
1029         if (its_dev->itt == 0) {
1030                 vmem_free(sc->sc_irq_alloc, its_dev->lpis.lpi_base, nvecs);
1031                 free(its_dev, M_GICV3_ITS);
1032                 return (NULL);
1033         }
1034
1035         mtx_lock_spin(&sc->sc_its_dev_lock);
1036         TAILQ_INSERT_TAIL(&sc->sc_its_dev_list, its_dev, entry);
1037         mtx_unlock_spin(&sc->sc_its_dev_lock);
1038
1039         /* Map device to its ITT */
1040         its_cmd_mapd(dev, its_dev, 1);
1041
1042         return (its_dev);
1043 }
1044
1045 static void
1046 its_device_release(device_t dev, struct its_dev *its_dev)
1047 {
1048         struct gicv3_its_softc *sc;
1049
1050         KASSERT(its_dev->lpis.lpi_busy == 0,
1051             ("its_device_release: Trying to release an inuse ITS device"));
1052
1053         /* Unmap device in ITS */
1054         its_cmd_mapd(dev, its_dev, 0);
1055
1056         sc = device_get_softc(dev);
1057
1058         /* Remove the device from the list of devices */
1059         mtx_lock_spin(&sc->sc_its_dev_lock);
1060         TAILQ_REMOVE(&sc->sc_its_dev_list, its_dev, entry);
1061         mtx_unlock_spin(&sc->sc_its_dev_lock);
1062
1063         /* Free ITT */
1064         KASSERT(its_dev->itt != 0, ("Invalid ITT in valid ITS device"));
1065         contigfree((void *)its_dev->itt, its_dev->itt_size, M_GICV3_ITS);
1066
1067         /* Free the IRQ allocation */
1068         vmem_free(sc->sc_irq_alloc, its_dev->lpis.lpi_base,
1069             its_dev->lpis.lpi_num);
1070
1071         free(its_dev, M_GICV3_ITS);
1072 }
1073
1074 static int
1075 gicv3_its_alloc_msi(device_t dev, device_t child, int count, int maxcount,
1076     device_t *pic, struct intr_irqsrc **srcs)
1077 {
1078         struct gicv3_its_softc *sc;
1079         struct gicv3_its_irqsrc *girq;
1080         struct its_dev *its_dev;
1081         u_int irq;
1082         int i;
1083
1084         its_dev = its_device_get(dev, child, count);
1085         if (its_dev == NULL)
1086                 return (ENXIO);
1087
1088         KASSERT(its_dev->lpis.lpi_free >= count,
1089             ("gicv3_its_alloc_msi: No free LPIs"));
1090         sc = device_get_softc(dev);
1091         irq = its_dev->lpis.lpi_base + its_dev->lpis.lpi_num -
1092             its_dev->lpis.lpi_free;
1093         for (i = 0; i < count; i++, irq++) {
1094                 its_dev->lpis.lpi_free--;
1095                 girq = &sc->sc_irqs[irq];
1096                 girq->gi_its_dev = its_dev;
1097                 srcs[i] = (struct intr_irqsrc *)girq;
1098         }
1099         its_dev->lpis.lpi_busy += count;
1100         *pic = dev;
1101
1102         return (0);
1103 }
1104
1105 static int
1106 gicv3_its_release_msi(device_t dev, device_t child, int count,
1107     struct intr_irqsrc **isrc)
1108 {
1109         struct gicv3_its_irqsrc *girq;
1110         struct its_dev *its_dev;
1111         int i;
1112
1113         its_dev = its_device_find(dev, child);
1114
1115         KASSERT(its_dev != NULL,
1116             ("gicv3_its_release_msi: Releasing a MSI interrupt with "
1117              "no ITS device"));
1118         KASSERT(its_dev->lpis.lpi_busy >= count,
1119             ("gicv3_its_release_msi: Releasing more interrupts than "
1120              "were allocated: releasing %d, allocated %d", count,
1121              its_dev->lpis.lpi_busy));
1122         for (i = 0; i < count; i++) {
1123                 girq = (struct gicv3_its_irqsrc *)isrc[i];
1124                 girq->gi_its_dev = NULL;
1125         }
1126         its_dev->lpis.lpi_busy -= count;
1127
1128         if (its_dev->lpis.lpi_busy == 0)
1129                 its_device_release(dev, its_dev);
1130
1131         return (0);
1132 }
1133
1134 static int
1135 gicv3_its_alloc_msix(device_t dev, device_t child, device_t *pic,
1136     struct intr_irqsrc **isrcp)
1137 {
1138         struct gicv3_its_softc *sc;
1139         struct gicv3_its_irqsrc *girq;
1140         struct its_dev *its_dev;
1141         u_int nvecs, irq;
1142
1143         nvecs = pci_msix_count(child);
1144         its_dev = its_device_get(dev, child, nvecs);
1145         if (its_dev == NULL)
1146                 return (ENXIO);
1147
1148         KASSERT(its_dev->lpis.lpi_free > 0,
1149             ("gicv3_its_alloc_msix: No free LPIs"));
1150         sc = device_get_softc(dev);
1151         irq = its_dev->lpis.lpi_base + its_dev->lpis.lpi_num -
1152             its_dev->lpis.lpi_free;
1153         its_dev->lpis.lpi_free--;
1154         its_dev->lpis.lpi_busy++;
1155         girq = &sc->sc_irqs[irq];
1156         girq->gi_its_dev = its_dev;
1157
1158         *pic = dev;
1159         *isrcp = (struct intr_irqsrc *)girq;
1160
1161         return (0);
1162 }
1163
1164 static int
1165 gicv3_its_release_msix(device_t dev, device_t child, struct intr_irqsrc *isrc)
1166 {
1167         struct gicv3_its_irqsrc *girq;
1168         struct its_dev *its_dev;
1169
1170         its_dev = its_device_find(dev, child);
1171
1172         KASSERT(its_dev != NULL,
1173             ("gicv3_its_release_msix: Releasing a MSI-X interrupt with "
1174              "no ITS device"));
1175         KASSERT(its_dev->lpis.lpi_busy > 0,
1176             ("gicv3_its_release_msix: Releasing more interrupts than "
1177              "were allocated: allocated %d", its_dev->lpis.lpi_busy));
1178         girq = (struct gicv3_its_irqsrc *)isrc;
1179         girq->gi_its_dev = NULL;
1180         its_dev->lpis.lpi_busy--;
1181
1182         if (its_dev->lpis.lpi_busy == 0)
1183                 its_device_release(dev, its_dev);
1184
1185         return (0);
1186 }
1187
1188 static int
1189 gicv3_its_map_msi(device_t dev, device_t child, struct intr_irqsrc *isrc,
1190     uint64_t *addr, uint32_t *data)
1191 {
1192         struct gicv3_its_softc *sc;
1193         struct gicv3_its_irqsrc *girq;
1194
1195         sc = device_get_softc(dev);
1196         girq = (struct gicv3_its_irqsrc *)isrc;
1197
1198         /* Map the message to the given IRQ */
1199         its_cmd_mapti(dev, girq);
1200
1201         *addr = vtophys(rman_get_virtual(sc->sc_its_res)) + GITS_TRANSLATER;
1202         *data = girq->gi_irq - girq->gi_its_dev->lpis.lpi_base;
1203
1204         return (0);
1205 }
1206
1207 /*
1208  * Commands handling.
1209  */
1210
1211 static __inline void
1212 cmd_format_command(struct its_cmd *cmd, uint8_t cmd_type)
1213 {
1214         /* Command field: DW0 [7:0] */
1215         cmd->cmd_dword[0] &= htole64(~CMD_COMMAND_MASK);
1216         cmd->cmd_dword[0] |= htole64(cmd_type);
1217 }
1218
1219 static __inline void
1220 cmd_format_devid(struct its_cmd *cmd, uint32_t devid)
1221 {
1222         /* Device ID field: DW0 [63:32] */
1223         cmd->cmd_dword[0] &= htole64(~CMD_DEVID_MASK);
1224         cmd->cmd_dword[0] |= htole64((uint64_t)devid << CMD_DEVID_SHIFT);
1225 }
1226
1227 static __inline void
1228 cmd_format_size(struct its_cmd *cmd, uint16_t size)
1229 {
1230         /* Size field: DW1 [4:0] */
1231         cmd->cmd_dword[1] &= htole64(~CMD_SIZE_MASK);
1232         cmd->cmd_dword[1] |= htole64((size & CMD_SIZE_MASK));
1233 }
1234
1235 static __inline void
1236 cmd_format_id(struct its_cmd *cmd, uint32_t id)
1237 {
1238         /* ID field: DW1 [31:0] */
1239         cmd->cmd_dword[1] &= htole64(~CMD_ID_MASK);
1240         cmd->cmd_dword[1] |= htole64(id);
1241 }
1242
1243 static __inline void
1244 cmd_format_pid(struct its_cmd *cmd, uint32_t pid)
1245 {
1246         /* Physical ID field: DW1 [63:32] */
1247         cmd->cmd_dword[1] &= htole64(~CMD_PID_MASK);
1248         cmd->cmd_dword[1] |= htole64((uint64_t)pid << CMD_PID_SHIFT);
1249 }
1250
1251 static __inline void
1252 cmd_format_col(struct its_cmd *cmd, uint16_t col_id)
1253 {
1254         /* Collection field: DW2 [16:0] */
1255         cmd->cmd_dword[2] &= htole64(~CMD_COL_MASK);
1256         cmd->cmd_dword[2] |= htole64(col_id);
1257 }
1258
1259 static __inline void
1260 cmd_format_target(struct its_cmd *cmd, uint64_t target)
1261 {
1262         /* Target Address field: DW2 [47:16] */
1263         cmd->cmd_dword[2] &= htole64(~CMD_TARGET_MASK);
1264         cmd->cmd_dword[2] |= htole64(target & CMD_TARGET_MASK);
1265 }
1266
1267 static __inline void
1268 cmd_format_itt(struct its_cmd *cmd, uint64_t itt)
1269 {
1270         /* ITT Address field: DW2 [47:8] */
1271         cmd->cmd_dword[2] &= htole64(~CMD_ITT_MASK);
1272         cmd->cmd_dword[2] |= htole64(itt & CMD_ITT_MASK);
1273 }
1274
1275 static __inline void
1276 cmd_format_valid(struct its_cmd *cmd, uint8_t valid)
1277 {
1278         /* Valid field: DW2 [63] */
1279         cmd->cmd_dword[2] &= htole64(~CMD_VALID_MASK);
1280         cmd->cmd_dword[2] |= htole64((uint64_t)valid << CMD_VALID_SHIFT);
1281 }
1282
1283 static inline bool
1284 its_cmd_queue_full(struct gicv3_its_softc *sc)
1285 {
1286         size_t read_idx, next_write_idx;
1287
1288         /* Get the index of the next command */
1289         next_write_idx = (sc->sc_its_cmd_next_idx + 1) %
1290             (ITS_CMDQ_SIZE / sizeof(struct its_cmd));
1291         /* And the index of the current command being read */
1292         read_idx = gic_its_read_4(sc, GITS_CREADR) / sizeof(struct its_cmd);
1293
1294         /*
1295          * The queue is full when the write offset points
1296          * at the command before the current read offset.
1297          */
1298         return (next_write_idx == read_idx);
1299 }
1300
1301 static inline void
1302 its_cmd_sync(struct gicv3_its_softc *sc, struct its_cmd *cmd)
1303 {
1304
1305         if ((sc->sc_its_flags & ITS_FLAGS_CMDQ_FLUSH) != 0) {
1306                 /* Clean D-cache under command. */
1307                 cpu_dcache_wb_range((vm_offset_t)cmd, sizeof(*cmd));
1308         } else {
1309                 /* DSB inner shareable, store */
1310                 dsb(ishst);
1311         }
1312
1313 }
1314
1315 static inline uint64_t
1316 its_cmd_cwriter_offset(struct gicv3_its_softc *sc, struct its_cmd *cmd)
1317 {
1318         uint64_t off;
1319
1320         off = (cmd - sc->sc_its_cmd_base) * sizeof(*cmd);
1321
1322         return (off);
1323 }
1324
1325 static void
1326 its_cmd_wait_completion(device_t dev, struct its_cmd *cmd_first,
1327     struct its_cmd *cmd_last)
1328 {
1329         struct gicv3_its_softc *sc;
1330         uint64_t first, last, read;
1331         size_t us_left;
1332
1333         sc = device_get_softc(dev);
1334
1335         /*
1336          * XXX ARM64TODO: This is obviously a significant delay.
1337          * The reason for that is that currently the time frames for
1338          * the command to complete are not known.
1339          */
1340         us_left = 1000000;
1341
1342         first = its_cmd_cwriter_offset(sc, cmd_first);
1343         last = its_cmd_cwriter_offset(sc, cmd_last);
1344
1345         for (;;) {
1346                 read = gic_its_read_8(sc, GITS_CREADR);
1347                 if (first < last) {
1348                         if (read < first || read >= last)
1349                                 break;
1350                 } else if (read < first && read >= last)
1351                         break;
1352
1353                 if (us_left-- == 0) {
1354                         /* This means timeout */
1355                         device_printf(dev,
1356                             "Timeout while waiting for CMD completion.\n");
1357                         return;
1358                 }
1359                 DELAY(1);
1360         }
1361 }
1362
1363
1364 static struct its_cmd *
1365 its_cmd_alloc_locked(device_t dev)
1366 {
1367         struct gicv3_its_softc *sc;
1368         struct its_cmd *cmd;
1369         size_t us_left;
1370
1371         sc = device_get_softc(dev);
1372
1373         /*
1374          * XXX ARM64TODO: This is obviously a significant delay.
1375          * The reason for that is that currently the time frames for
1376          * the command to complete (and therefore free the descriptor)
1377          * are not known.
1378          */
1379         us_left = 1000000;
1380
1381         mtx_assert(&sc->sc_its_cmd_lock, MA_OWNED);
1382         while (its_cmd_queue_full(sc)) {
1383                 if (us_left-- == 0) {
1384                         /* Timeout while waiting for free command */
1385                         device_printf(dev,
1386                             "Timeout while waiting for free command\n");
1387                         return (NULL);
1388                 }
1389                 DELAY(1);
1390         }
1391
1392         cmd = &sc->sc_its_cmd_base[sc->sc_its_cmd_next_idx];
1393         sc->sc_its_cmd_next_idx++;
1394         sc->sc_its_cmd_next_idx %= ITS_CMDQ_SIZE / sizeof(struct its_cmd);
1395
1396         return (cmd);
1397 }
1398
1399 static uint64_t
1400 its_cmd_prepare(struct its_cmd *cmd, struct its_cmd_desc *desc)
1401 {
1402         uint64_t target;
1403         uint8_t cmd_type;
1404         u_int size;
1405
1406         cmd_type = desc->cmd_type;
1407         target = ITS_TARGET_NONE;
1408
1409         switch (cmd_type) {
1410         case ITS_CMD_MOVI:      /* Move interrupt ID to another collection */
1411                 target = desc->cmd_desc_movi.col->col_target;
1412                 cmd_format_command(cmd, ITS_CMD_MOVI);
1413                 cmd_format_id(cmd, desc->cmd_desc_movi.id);
1414                 cmd_format_col(cmd, desc->cmd_desc_movi.col->col_id);
1415                 cmd_format_devid(cmd, desc->cmd_desc_movi.its_dev->devid);
1416                 break;
1417         case ITS_CMD_SYNC:      /* Wait for previous commands completion */
1418                 target = desc->cmd_desc_sync.col->col_target;
1419                 cmd_format_command(cmd, ITS_CMD_SYNC);
1420                 cmd_format_target(cmd, target);
1421                 break;
1422         case ITS_CMD_MAPD:      /* Assign ITT to device */
1423                 cmd_format_command(cmd, ITS_CMD_MAPD);
1424                 cmd_format_itt(cmd, vtophys(desc->cmd_desc_mapd.its_dev->itt));
1425                 /*
1426                  * Size describes number of bits to encode interrupt IDs
1427                  * supported by the device minus one.
1428                  * When V (valid) bit is zero, this field should be written
1429                  * as zero.
1430                  */
1431                 if (desc->cmd_desc_mapd.valid != 0) {
1432                         size = fls(desc->cmd_desc_mapd.its_dev->lpis.lpi_num);
1433                         size = MAX(1, size) - 1;
1434                 } else
1435                         size = 0;
1436
1437                 cmd_format_size(cmd, size);
1438                 cmd_format_devid(cmd, desc->cmd_desc_mapd.its_dev->devid);
1439                 cmd_format_valid(cmd, desc->cmd_desc_mapd.valid);
1440                 break;
1441         case ITS_CMD_MAPC:      /* Map collection to Re-Distributor */
1442                 target = desc->cmd_desc_mapc.col->col_target;
1443                 cmd_format_command(cmd, ITS_CMD_MAPC);
1444                 cmd_format_col(cmd, desc->cmd_desc_mapc.col->col_id);
1445                 cmd_format_valid(cmd, desc->cmd_desc_mapc.valid);
1446                 cmd_format_target(cmd, target);
1447                 break;
1448         case ITS_CMD_MAPTI:
1449                 target = desc->cmd_desc_mapvi.col->col_target;
1450                 cmd_format_command(cmd, ITS_CMD_MAPTI);
1451                 cmd_format_devid(cmd, desc->cmd_desc_mapvi.its_dev->devid);
1452                 cmd_format_id(cmd, desc->cmd_desc_mapvi.id);
1453                 cmd_format_pid(cmd, desc->cmd_desc_mapvi.pid);
1454                 cmd_format_col(cmd, desc->cmd_desc_mapvi.col->col_id);
1455                 break;
1456         case ITS_CMD_MAPI:
1457                 target = desc->cmd_desc_mapi.col->col_target;
1458                 cmd_format_command(cmd, ITS_CMD_MAPI);
1459                 cmd_format_devid(cmd, desc->cmd_desc_mapi.its_dev->devid);
1460                 cmd_format_id(cmd, desc->cmd_desc_mapi.pid);
1461                 cmd_format_col(cmd, desc->cmd_desc_mapi.col->col_id);
1462                 break;
1463         case ITS_CMD_INV:
1464                 target = desc->cmd_desc_inv.col->col_target;
1465                 cmd_format_command(cmd, ITS_CMD_INV);
1466                 cmd_format_devid(cmd, desc->cmd_desc_inv.its_dev->devid);
1467                 cmd_format_id(cmd, desc->cmd_desc_inv.pid);
1468                 break;
1469         case ITS_CMD_INVALL:
1470                 cmd_format_command(cmd, ITS_CMD_INVALL);
1471                 cmd_format_col(cmd, desc->cmd_desc_invall.col->col_id);
1472                 break;
1473         default:
1474                 panic("its_cmd_prepare: Invalid command: %x", cmd_type);
1475         }
1476
1477         return (target);
1478 }
1479
1480 static int
1481 its_cmd_send(device_t dev, struct its_cmd_desc *desc)
1482 {
1483         struct gicv3_its_softc *sc;
1484         struct its_cmd *cmd, *cmd_sync, *cmd_write;
1485         struct its_col col_sync;
1486         struct its_cmd_desc desc_sync;
1487         uint64_t target, cwriter;
1488
1489         sc = device_get_softc(dev);
1490         mtx_lock_spin(&sc->sc_its_cmd_lock);
1491         cmd = its_cmd_alloc_locked(dev);
1492         if (cmd == NULL) {
1493                 device_printf(dev, "could not allocate ITS command\n");
1494                 mtx_unlock_spin(&sc->sc_its_cmd_lock);
1495                 return (EBUSY);
1496         }
1497
1498         target = its_cmd_prepare(cmd, desc);
1499         its_cmd_sync(sc, cmd);
1500
1501         if (target != ITS_TARGET_NONE) {
1502                 cmd_sync = its_cmd_alloc_locked(dev);
1503                 if (cmd_sync != NULL) {
1504                         desc_sync.cmd_type = ITS_CMD_SYNC;
1505                         col_sync.col_target = target;
1506                         desc_sync.cmd_desc_sync.col = &col_sync;
1507                         its_cmd_prepare(cmd_sync, &desc_sync);
1508                         its_cmd_sync(sc, cmd_sync);
1509                 }
1510         }
1511
1512         /* Update GITS_CWRITER */
1513         cwriter = sc->sc_its_cmd_next_idx * sizeof(struct its_cmd);
1514         gic_its_write_8(sc, GITS_CWRITER, cwriter);
1515         cmd_write = &sc->sc_its_cmd_base[sc->sc_its_cmd_next_idx];
1516         mtx_unlock_spin(&sc->sc_its_cmd_lock);
1517
1518         its_cmd_wait_completion(dev, cmd, cmd_write);
1519
1520         return (0);
1521 }
1522
1523 /* Handlers to send commands */
1524 static void
1525 its_cmd_movi(device_t dev, struct gicv3_its_irqsrc *girq)
1526 {
1527         struct gicv3_its_softc *sc;
1528         struct its_cmd_desc desc;
1529         struct its_col *col;
1530
1531         sc = device_get_softc(dev);
1532         col = sc->sc_its_cols[CPU_FFS(&girq->gi_isrc.isrc_cpu) - 1];
1533
1534         desc.cmd_type = ITS_CMD_MOVI;
1535         desc.cmd_desc_movi.its_dev = girq->gi_its_dev;
1536         desc.cmd_desc_movi.col = col;
1537         desc.cmd_desc_movi.id = girq->gi_irq - girq->gi_its_dev->lpis.lpi_base;
1538
1539         its_cmd_send(dev, &desc);
1540 }
1541
1542 static void
1543 its_cmd_mapc(device_t dev, struct its_col *col, uint8_t valid)
1544 {
1545         struct its_cmd_desc desc;
1546
1547         desc.cmd_type = ITS_CMD_MAPC;
1548         desc.cmd_desc_mapc.col = col;
1549         /*
1550          * Valid bit set - map the collection.
1551          * Valid bit cleared - unmap the collection.
1552          */
1553         desc.cmd_desc_mapc.valid = valid;
1554
1555         its_cmd_send(dev, &desc);
1556 }
1557
1558 static void
1559 its_cmd_mapti(device_t dev, struct gicv3_its_irqsrc *girq)
1560 {
1561         struct gicv3_its_softc *sc;
1562         struct its_cmd_desc desc;
1563         struct its_col *col;
1564         u_int col_id;
1565
1566         sc = device_get_softc(dev);
1567
1568         col_id = CPU_FFS(&girq->gi_isrc.isrc_cpu) - 1;
1569         col = sc->sc_its_cols[col_id];
1570
1571         desc.cmd_type = ITS_CMD_MAPTI;
1572         desc.cmd_desc_mapvi.its_dev = girq->gi_its_dev;
1573         desc.cmd_desc_mapvi.col = col;
1574         /* The EventID sent to the device */
1575         desc.cmd_desc_mapvi.id = girq->gi_irq - girq->gi_its_dev->lpis.lpi_base;
1576         /* The physical interrupt presented to softeware */
1577         desc.cmd_desc_mapvi.pid = girq->gi_irq + sc->sc_irq_base;
1578
1579         its_cmd_send(dev, &desc);
1580 }
1581
1582 static void
1583 its_cmd_mapd(device_t dev, struct its_dev *its_dev, uint8_t valid)
1584 {
1585         struct its_cmd_desc desc;
1586
1587         desc.cmd_type = ITS_CMD_MAPD;
1588         desc.cmd_desc_mapd.its_dev = its_dev;
1589         desc.cmd_desc_mapd.valid = valid;
1590
1591         its_cmd_send(dev, &desc);
1592 }
1593
1594 static void
1595 its_cmd_inv(device_t dev, struct its_dev *its_dev,
1596     struct gicv3_its_irqsrc *girq)
1597 {
1598         struct gicv3_its_softc *sc;
1599         struct its_cmd_desc desc;
1600         struct its_col *col;
1601
1602         sc = device_get_softc(dev);
1603         col = sc->sc_its_cols[CPU_FFS(&girq->gi_isrc.isrc_cpu) - 1];
1604
1605         desc.cmd_type = ITS_CMD_INV;
1606         /* The EventID sent to the device */
1607         desc.cmd_desc_inv.pid = girq->gi_irq - its_dev->lpis.lpi_base;
1608         desc.cmd_desc_inv.its_dev = its_dev;
1609         desc.cmd_desc_inv.col = col;
1610
1611         its_cmd_send(dev, &desc);
1612 }
1613
1614 static void
1615 its_cmd_invall(device_t dev, struct its_col *col)
1616 {
1617         struct its_cmd_desc desc;
1618
1619         desc.cmd_type = ITS_CMD_INVALL;
1620         desc.cmd_desc_invall.col = col;
1621
1622         its_cmd_send(dev, &desc);
1623 }
1624
1625 #ifdef FDT
1626 static device_probe_t gicv3_its_fdt_probe;
1627 static device_attach_t gicv3_its_fdt_attach;
1628
1629 static device_method_t gicv3_its_fdt_methods[] = {
1630         /* Device interface */
1631         DEVMETHOD(device_probe,         gicv3_its_fdt_probe),
1632         DEVMETHOD(device_attach,        gicv3_its_fdt_attach),
1633
1634         /* End */
1635         DEVMETHOD_END
1636 };
1637
1638 #define its_baseclasses its_fdt_baseclasses
1639 DEFINE_CLASS_1(its, gicv3_its_fdt_driver, gicv3_its_fdt_methods,
1640     sizeof(struct gicv3_its_softc), gicv3_its_driver);
1641 #undef its_baseclasses
1642 static devclass_t gicv3_its_fdt_devclass;
1643
1644 EARLY_DRIVER_MODULE(its_fdt, gic, gicv3_its_fdt_driver,
1645     gicv3_its_fdt_devclass, 0, 0, BUS_PASS_INTERRUPT + BUS_PASS_ORDER_MIDDLE);
1646
1647 static int
1648 gicv3_its_fdt_probe(device_t dev)
1649 {
1650
1651         if (!ofw_bus_status_okay(dev))
1652                 return (ENXIO);
1653
1654         if (!ofw_bus_is_compatible(dev, "arm,gic-v3-its"))
1655                 return (ENXIO);
1656
1657         device_set_desc(dev, "ARM GIC Interrupt Translation Service");
1658         return (BUS_PROBE_DEFAULT);
1659 }
1660
1661 static int
1662 gicv3_its_fdt_attach(device_t dev)
1663 {
1664         struct gicv3_its_softc *sc;
1665         phandle_t xref;
1666         int err;
1667
1668         sc = device_get_softc(dev);
1669
1670         sc->sc_irq_length = gicv3_get_nirqs(dev);
1671         sc->sc_irq_base = GIC_FIRST_LPI;
1672         sc->sc_irq_base += device_get_unit(dev) * sc->sc_irq_length;
1673
1674         err = gicv3_its_attach(dev);
1675         if (err != 0)
1676                 return (err);
1677
1678         /* Register this device as a interrupt controller */
1679         xref = OF_xref_from_node(ofw_bus_get_node(dev));
1680         sc->sc_pic = intr_pic_register(dev, xref);
1681         intr_pic_add_handler(device_get_parent(dev), sc->sc_pic,
1682             gicv3_its_intr, sc, sc->sc_irq_base, sc->sc_irq_length);
1683
1684         /* Register this device to handle MSI interrupts */
1685         intr_msi_register(dev, xref);
1686
1687         return (0);
1688 }
1689 #endif
1690
1691 #ifdef DEV_ACPI
1692 static device_probe_t gicv3_its_acpi_probe;
1693 static device_attach_t gicv3_its_acpi_attach;
1694
1695 static device_method_t gicv3_its_acpi_methods[] = {
1696         /* Device interface */
1697         DEVMETHOD(device_probe,         gicv3_its_acpi_probe),
1698         DEVMETHOD(device_attach,        gicv3_its_acpi_attach),
1699
1700         /* End */
1701         DEVMETHOD_END
1702 };
1703
1704 #define its_baseclasses its_acpi_baseclasses
1705 DEFINE_CLASS_1(its, gicv3_its_acpi_driver, gicv3_its_acpi_methods,
1706     sizeof(struct gicv3_its_softc), gicv3_its_driver);
1707 #undef its_baseclasses
1708 static devclass_t gicv3_its_acpi_devclass;
1709
1710 EARLY_DRIVER_MODULE(its_acpi, gic, gicv3_its_acpi_driver,
1711     gicv3_its_acpi_devclass, 0, 0, BUS_PASS_INTERRUPT + BUS_PASS_ORDER_MIDDLE);
1712
1713 static int
1714 gicv3_its_acpi_probe(device_t dev)
1715 {
1716
1717         if (gic_get_bus(dev) != GIC_BUS_ACPI)
1718                 return (EINVAL);
1719
1720         if (gic_get_hw_rev(dev) < 3)
1721                 return (EINVAL);
1722
1723         device_set_desc(dev, "ARM GIC Interrupt Translation Service");
1724         return (BUS_PROBE_DEFAULT);
1725 }
1726
1727 static int
1728 gicv3_its_acpi_attach(device_t dev)
1729 {
1730         struct gicv3_its_softc *sc;
1731         int err;
1732
1733         err = gicv3_its_attach(dev);
1734         if (err != 0)
1735                 return (err);
1736
1737         sc = device_get_softc(dev);
1738
1739         sc->sc_pic = intr_pic_register(dev, 1);
1740         intr_pic_add_handler(device_get_parent(dev), sc->sc_pic,
1741             gicv3_its_intr, sc, GIC_FIRST_LPI, LPI_NIRQS);
1742
1743         /* Register this device to handle MSI interrupts */
1744         intr_msi_register(dev, 1);
1745
1746         return (0);
1747 }
1748 #endif