xref: /freebsd/sys/arm64/arm64/gic_v3.c (revision 4b9d6057)
1 /*-
2  * Copyright (c) 2015-2016 The FreeBSD Foundation
3  *
4  * This software was developed by Andrew Turner under
5  * the sponsorship of the FreeBSD Foundation.
6  *
7  * This software was developed by Semihalf under
8  * the sponsorship of the FreeBSD Foundation.
9  *
10  * Redistribution and use in source and binary forms, with or without
11  * modification, are permitted provided that the following conditions
12  * are met:
13  * 1. Redistributions of source code must retain the above copyright
14  *    notice, this list of conditions and the following disclaimer.
15  * 2. Redistributions in binary form must reproduce the above copyright
16  *    notice, this list of conditions and the following disclaimer in the
17  *    documentation and/or other materials provided with the distribution.
18  *
19  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
20  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
21  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
22  * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
23  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
24  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
25  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
26  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
27  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
28  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
29  * SUCH DAMAGE.
30  */
31 
32 #include "opt_acpi.h"
33 #include "opt_platform.h"
34 
35 #include <sys/param.h>
36 #include <sys/systm.h>
37 #include <sys/bitstring.h>
38 #include <sys/bus.h>
39 #include <sys/kernel.h>
40 #include <sys/ktr.h>
41 #include <sys/malloc.h>
42 #include <sys/module.h>
43 #include <sys/rman.h>
44 #include <sys/pcpu.h>
45 #include <sys/proc.h>
46 #include <sys/cpuset.h>
47 #include <sys/lock.h>
48 #include <sys/mutex.h>
49 #include <sys/smp.h>
50 #include <sys/interrupt.h>
51 
52 #include <vm/vm.h>
53 #include <vm/pmap.h>
54 
55 #include <machine/bus.h>
56 #include <machine/cpu.h>
57 #include <machine/intr.h>
58 
59 #ifdef FDT
60 #include <dev/fdt/fdt_intr.h>
61 #include <dev/ofw/ofw_bus_subr.h>
62 #endif
63 
64 #ifdef DEV_ACPI
65 #include <contrib/dev/acpica/include/acpi.h>
66 #include <dev/acpica/acpivar.h>
67 #endif
68 
69 #include "gic_if.h"
70 #include "pic_if.h"
71 #include "msi_if.h"
72 
73 #include <arm/arm/gic_common.h>
74 #include "gic_v3_reg.h"
75 #include "gic_v3_var.h"
76 
77 static bus_print_child_t gic_v3_print_child;
78 static bus_get_domain_t gic_v3_get_domain;
79 static bus_read_ivar_t gic_v3_read_ivar;
80 static bus_write_ivar_t gic_v3_write_ivar;
81 static bus_alloc_resource_t gic_v3_alloc_resource;
82 
83 static pic_disable_intr_t gic_v3_disable_intr;
84 static pic_enable_intr_t gic_v3_enable_intr;
85 static pic_map_intr_t gic_v3_map_intr;
86 static pic_setup_intr_t gic_v3_setup_intr;
87 static pic_teardown_intr_t gic_v3_teardown_intr;
88 static pic_post_filter_t gic_v3_post_filter;
89 static pic_post_ithread_t gic_v3_post_ithread;
90 static pic_pre_ithread_t gic_v3_pre_ithread;
91 static pic_bind_intr_t gic_v3_bind_intr;
92 #ifdef SMP
93 static pic_init_secondary_t gic_v3_init_secondary;
94 static pic_ipi_send_t gic_v3_ipi_send;
95 static pic_ipi_setup_t gic_v3_ipi_setup;
96 #endif
97 
98 static gic_reserve_msi_range_t gic_v3_reserve_msi_range;
99 static gic_alloc_msi_t gic_v3_gic_alloc_msi;
100 static gic_release_msi_t gic_v3_gic_release_msi;
101 static gic_alloc_msix_t gic_v3_gic_alloc_msix;
102 static gic_release_msix_t gic_v3_gic_release_msix;
103 
104 static msi_alloc_msi_t gic_v3_alloc_msi;
105 static msi_release_msi_t gic_v3_release_msi;
106 static msi_alloc_msix_t gic_v3_alloc_msix;
107 static msi_release_msix_t gic_v3_release_msix;
108 static msi_map_msi_t gic_v3_map_msi;
109 
110 static u_int gic_irq_cpu;
111 #ifdef SMP
112 static u_int sgi_to_ipi[GIC_LAST_SGI - GIC_FIRST_SGI + 1];
113 static u_int sgi_first_unused = GIC_FIRST_SGI;
114 #endif
115 
116 static device_method_t gic_v3_methods[] = {
117 	/* Device interface */
118 	DEVMETHOD(device_detach,	gic_v3_detach),
119 
120 	/* Bus interface */
121 	DEVMETHOD(bus_print_child,	gic_v3_print_child),
122 	DEVMETHOD(bus_get_domain,	gic_v3_get_domain),
123 	DEVMETHOD(bus_read_ivar,	gic_v3_read_ivar),
124 	DEVMETHOD(bus_write_ivar,	gic_v3_write_ivar),
125 	DEVMETHOD(bus_alloc_resource,	gic_v3_alloc_resource),
126 	DEVMETHOD(bus_activate_resource, bus_generic_activate_resource),
127 
128 	/* Interrupt controller interface */
129 	DEVMETHOD(pic_disable_intr,	gic_v3_disable_intr),
130 	DEVMETHOD(pic_enable_intr,	gic_v3_enable_intr),
131 	DEVMETHOD(pic_map_intr,		gic_v3_map_intr),
132 	DEVMETHOD(pic_setup_intr,	gic_v3_setup_intr),
133 	DEVMETHOD(pic_teardown_intr,	gic_v3_teardown_intr),
134 	DEVMETHOD(pic_post_filter,	gic_v3_post_filter),
135 	DEVMETHOD(pic_post_ithread,	gic_v3_post_ithread),
136 	DEVMETHOD(pic_pre_ithread,	gic_v3_pre_ithread),
137 #ifdef SMP
138 	DEVMETHOD(pic_bind_intr,	gic_v3_bind_intr),
139 	DEVMETHOD(pic_init_secondary,	gic_v3_init_secondary),
140 	DEVMETHOD(pic_ipi_send,		gic_v3_ipi_send),
141 	DEVMETHOD(pic_ipi_setup,	gic_v3_ipi_setup),
142 #endif
143 
144 	/* MSI/MSI-X */
145 	DEVMETHOD(msi_alloc_msi,        gic_v3_alloc_msi),
146 	DEVMETHOD(msi_release_msi,      gic_v3_release_msi),
147 	DEVMETHOD(msi_alloc_msix,       gic_v3_alloc_msix),
148 	DEVMETHOD(msi_release_msix,     gic_v3_release_msix),
149 	DEVMETHOD(msi_map_msi,          gic_v3_map_msi),
150 
151 	/* GIC */
152 	DEVMETHOD(gic_reserve_msi_range, gic_v3_reserve_msi_range),
153 	DEVMETHOD(gic_alloc_msi,	gic_v3_gic_alloc_msi),
154 	DEVMETHOD(gic_release_msi,	gic_v3_gic_release_msi),
155 	DEVMETHOD(gic_alloc_msix,	gic_v3_gic_alloc_msix),
156 	DEVMETHOD(gic_release_msix,	gic_v3_gic_release_msix),
157 
158 	/* End */
159 	DEVMETHOD_END
160 };
161 
162 DEFINE_CLASS_0(gic, gic_v3_driver, gic_v3_methods,
163     sizeof(struct gic_v3_softc));
164 
165 /*
166  * Driver-specific definitions.
167  */
168 MALLOC_DEFINE(M_GIC_V3, "GICv3", GIC_V3_DEVSTR);
169 
170 /*
171  * Helper functions and definitions.
172  */
173 /* Destination registers, either Distributor or Re-Distributor */
174 enum gic_v3_xdist {
175 	DIST = 0,
176 	REDIST,
177 };
178 
179 struct gic_v3_irqsrc {
180 	struct intr_irqsrc	gi_isrc;
181 	uint32_t		gi_irq;
182 	enum intr_polarity	gi_pol;
183 	enum intr_trigger	gi_trig;
184 #define GI_FLAG_MSI		(1 << 1) /* This interrupt source should only */
185 					 /* be used for MSI/MSI-X interrupts */
186 #define GI_FLAG_MSI_USED	(1 << 2) /* This irq is already allocated */
187 					 /* for a MSI/MSI-X interrupt */
188 	u_int			gi_flags;
189 };
190 
191 /* Helper routines starting with gic_v3_ */
192 static int gic_v3_dist_init(struct gic_v3_softc *);
193 static int gic_v3_redist_alloc(struct gic_v3_softc *);
194 static int gic_v3_redist_find(struct gic_v3_softc *);
195 static int gic_v3_redist_init(struct gic_v3_softc *);
196 static int gic_v3_cpu_init(struct gic_v3_softc *);
197 static void gic_v3_wait_for_rwp(struct gic_v3_softc *, enum gic_v3_xdist);
198 
199 /* A sequence of init functions for primary (boot) CPU */
200 typedef int (*gic_v3_initseq_t) (struct gic_v3_softc *);
201 /* Primary CPU initialization sequence */
202 static gic_v3_initseq_t gic_v3_primary_init[] = {
203 	gic_v3_dist_init,
204 	gic_v3_redist_alloc,
205 	gic_v3_redist_init,
206 	gic_v3_cpu_init,
207 	NULL
208 };
209 
210 #ifdef SMP
211 /* Secondary CPU initialization sequence */
212 static gic_v3_initseq_t gic_v3_secondary_init[] = {
213 	gic_v3_redist_init,
214 	gic_v3_cpu_init,
215 	NULL
216 };
217 #endif
218 
219 uint32_t
220 gic_r_read_4(device_t dev, bus_size_t offset)
221 {
222 	struct gic_v3_softc *sc;
223 	struct resource *rdist;
224 
225 	sc = device_get_softc(dev);
226 	rdist = sc->gic_redists.pcpu[PCPU_GET(cpuid)].res;
227 	offset += sc->gic_redists.pcpu[PCPU_GET(cpuid)].offset;
228 	return (bus_read_4(rdist, offset));
229 }
230 
231 uint64_t
232 gic_r_read_8(device_t dev, bus_size_t offset)
233 {
234 	struct gic_v3_softc *sc;
235 	struct resource *rdist;
236 
237 	sc = device_get_softc(dev);
238 	rdist = sc->gic_redists.pcpu[PCPU_GET(cpuid)].res;
239 	offset += sc->gic_redists.pcpu[PCPU_GET(cpuid)].offset;
240 	return (bus_read_8(rdist, offset));
241 }
242 
243 void
244 gic_r_write_4(device_t dev, bus_size_t offset, uint32_t val)
245 {
246 	struct gic_v3_softc *sc;
247 	struct resource *rdist;
248 
249 	sc = device_get_softc(dev);
250 	rdist = sc->gic_redists.pcpu[PCPU_GET(cpuid)].res;
251 	offset += sc->gic_redists.pcpu[PCPU_GET(cpuid)].offset;
252 	bus_write_4(rdist, offset, val);
253 }
254 
255 void
256 gic_r_write_8(device_t dev, bus_size_t offset, uint64_t val)
257 {
258 	struct gic_v3_softc *sc;
259 	struct resource *rdist;
260 
261 	sc = device_get_softc(dev);
262 	rdist = sc->gic_redists.pcpu[PCPU_GET(cpuid)].res;
263 	offset += sc->gic_redists.pcpu[PCPU_GET(cpuid)].offset;
264 	bus_write_8(rdist, offset, val);
265 }
266 
267 static void
268 gic_v3_reserve_msi_range(device_t dev, u_int start, u_int count)
269 {
270 	struct gic_v3_softc *sc;
271 	int i;
272 
273 	sc = device_get_softc(dev);
274 
275 	KASSERT((start + count) < sc->gic_nirqs,
276 	    ("%s: Trying to allocate too many MSI IRQs: %d + %d > %d", __func__,
277 	    start, count, sc->gic_nirqs));
278 	for (i = 0; i < count; i++) {
279 		KASSERT(sc->gic_irqs[start + i].gi_isrc.isrc_handlers == 0,
280 		    ("%s: MSI interrupt %d already has a handler", __func__,
281 		    count + i));
282 		KASSERT(sc->gic_irqs[start + i].gi_pol == INTR_POLARITY_CONFORM,
283 		    ("%s: MSI interrupt %d already has a polarity", __func__,
284 		    count + i));
285 		KASSERT(sc->gic_irqs[start + i].gi_trig == INTR_TRIGGER_CONFORM,
286 		    ("%s: MSI interrupt %d already has a trigger", __func__,
287 		    count + i));
288 		sc->gic_irqs[start + i].gi_pol = INTR_POLARITY_HIGH;
289 		sc->gic_irqs[start + i].gi_trig = INTR_TRIGGER_EDGE;
290 		sc->gic_irqs[start + i].gi_flags |= GI_FLAG_MSI;
291 	}
292 }
293 
294 /*
295  * Device interface.
296  */
297 int
298 gic_v3_attach(device_t dev)
299 {
300 	struct gic_v3_softc *sc;
301 	gic_v3_initseq_t *init_func;
302 	uint32_t typer;
303 	int rid;
304 	int err;
305 	size_t i;
306 	u_int irq;
307 	const char *name;
308 
309 	sc = device_get_softc(dev);
310 	sc->gic_registered = FALSE;
311 	sc->dev = dev;
312 	err = 0;
313 
314 	/* Initialize mutex */
315 	mtx_init(&sc->gic_mtx, "GICv3 lock", NULL, MTX_SPIN);
316 
317 	/*
318 	 * Allocate array of struct resource.
319 	 * One entry for Distributor and all remaining for Re-Distributor.
320 	 */
321 	sc->gic_res = malloc(
322 	    sizeof(*sc->gic_res) * (sc->gic_redists.nregions + 1),
323 	    M_GIC_V3, M_WAITOK);
324 
325 	/* Now allocate corresponding resources */
326 	for (i = 0, rid = 0; i < (sc->gic_redists.nregions + 1); i++, rid++) {
327 		sc->gic_res[rid] = bus_alloc_resource_any(dev, SYS_RES_MEMORY,
328 		    &rid, RF_ACTIVE);
329 		if (sc->gic_res[rid] == NULL)
330 			return (ENXIO);
331 	}
332 
333 	/*
334 	 * Distributor interface
335 	 */
336 	sc->gic_dist = sc->gic_res[0];
337 
338 	/*
339 	 * Re-Dristributor interface
340 	 */
341 	/* Allocate space under region descriptions */
342 	sc->gic_redists.regions = malloc(
343 	    sizeof(*sc->gic_redists.regions) * sc->gic_redists.nregions,
344 	    M_GIC_V3, M_WAITOK);
345 
346 	/* Fill-up bus_space information for each region. */
347 	for (i = 0, rid = 1; i < sc->gic_redists.nregions; i++, rid++)
348 		sc->gic_redists.regions[i] = sc->gic_res[rid];
349 
350 	/* Get the number of supported SPI interrupts */
351 	typer = gic_d_read(sc, 4, GICD_TYPER);
352 	sc->gic_nirqs = GICD_TYPER_I_NUM(typer);
353 	if (sc->gic_nirqs > GIC_I_NUM_MAX)
354 		sc->gic_nirqs = GIC_I_NUM_MAX;
355 
356 	sc->gic_irqs = malloc(sizeof(*sc->gic_irqs) * sc->gic_nirqs,
357 	    M_GIC_V3, M_WAITOK | M_ZERO);
358 	name = device_get_nameunit(dev);
359 	for (irq = 0; irq < sc->gic_nirqs; irq++) {
360 		struct intr_irqsrc *isrc;
361 
362 		sc->gic_irqs[irq].gi_irq = irq;
363 		sc->gic_irqs[irq].gi_pol = INTR_POLARITY_CONFORM;
364 		sc->gic_irqs[irq].gi_trig = INTR_TRIGGER_CONFORM;
365 
366 		isrc = &sc->gic_irqs[irq].gi_isrc;
367 		if (irq <= GIC_LAST_SGI) {
368 			err = intr_isrc_register(isrc, sc->dev,
369 			    INTR_ISRCF_IPI, "%s,i%u", name, irq - GIC_FIRST_SGI);
370 		} else if (irq <= GIC_LAST_PPI) {
371 			err = intr_isrc_register(isrc, sc->dev,
372 			    INTR_ISRCF_PPI, "%s,p%u", name, irq - GIC_FIRST_PPI);
373 		} else {
374 			err = intr_isrc_register(isrc, sc->dev, 0,
375 			    "%s,s%u", name, irq - GIC_FIRST_SPI);
376 		}
377 		if (err != 0) {
378 			/* XXX call intr_isrc_deregister() */
379 			free(sc->gic_irqs, M_DEVBUF);
380 			return (err);
381 		}
382 	}
383 
384 	mtx_init(&sc->gic_mbi_mtx, "GICv3 mbi lock", NULL, MTX_DEF);
385 	if (sc->gic_mbi_start > 0) {
386 		if (!sc->gic_mbi_end) {
387 			/*
388 			 * This is to address SPI based msi ranges, where
389 			 * SPI range is not specified in ACPI
390 			 */
391 			sc->gic_mbi_end = sc->gic_nirqs - 1;
392 		}
393 		gic_v3_reserve_msi_range(dev, sc->gic_mbi_start,
394 		    sc->gic_mbi_end - sc->gic_mbi_start);
395 
396 		if (bootverbose) {
397 			device_printf(dev, "using spi %u to %u\n", sc->gic_mbi_start,
398 					sc->gic_mbi_end);
399 		}
400 	}
401 
402 	/*
403 	 * Read the Peripheral ID2 register. This is an implementation
404 	 * defined register, but seems to be implemented in all GICv3
405 	 * parts and Linux expects it to be there.
406 	 */
407 	sc->gic_pidr2 = gic_d_read(sc, 4, GICD_PIDR2);
408 
409 	/* Get the number of supported interrupt identifier bits */
410 	sc->gic_idbits = GICD_TYPER_IDBITS(typer);
411 
412 	if (bootverbose) {
413 		device_printf(dev, "SPIs: %u, IDs: %u\n",
414 		    sc->gic_nirqs, (1 << sc->gic_idbits) - 1);
415 	}
416 
417 	/* Train init sequence for boot CPU */
418 	for (init_func = gic_v3_primary_init; *init_func != NULL; init_func++) {
419 		err = (*init_func)(sc);
420 		if (err != 0)
421 			return (err);
422 	}
423 
424 	return (0);
425 }
426 
427 int
428 gic_v3_detach(device_t dev)
429 {
430 	struct gic_v3_softc *sc;
431 	int rid;
432 
433 	sc = device_get_softc(dev);
434 
435 	if (device_is_attached(dev)) {
436 		/*
437 		 * XXX: We should probably deregister PIC
438 		 */
439 		if (sc->gic_registered)
440 			panic("Trying to detach registered PIC");
441 	}
442 	for (rid = 0; rid < (sc->gic_redists.nregions + 1); rid++)
443 		bus_release_resource(dev, SYS_RES_MEMORY, rid, sc->gic_res[rid]);
444 
445 	free(sc->gic_redists.pcpu, M_GIC_V3);
446 
447 	free(sc->ranges, M_GIC_V3);
448 	free(sc->gic_res, M_GIC_V3);
449 	free(sc->gic_redists.regions, M_GIC_V3);
450 
451 	return (0);
452 }
453 
454 static int
455 gic_v3_print_child(device_t bus, device_t child)
456 {
457 	struct resource_list *rl;
458 	int retval = 0;
459 
460 	rl = BUS_GET_RESOURCE_LIST(bus, child);
461 	KASSERT(rl != NULL, ("%s: No resource list", __func__));
462 	retval += bus_print_child_header(bus, child);
463 	retval += resource_list_print_type(rl, "mem", SYS_RES_MEMORY, "%#jx");
464 	retval += bus_print_child_footer(bus, child);
465 
466 	return (retval);
467 }
468 
469 static int
470 gic_v3_get_domain(device_t dev, device_t child, int *domain)
471 {
472 	struct gic_v3_devinfo *di;
473 
474 	di = device_get_ivars(child);
475 	if (di->gic_domain < 0)
476 		return (ENOENT);
477 
478 	*domain = di->gic_domain;
479 	return (0);
480 }
481 
482 static int
483 gic_v3_read_ivar(device_t dev, device_t child, int which, uintptr_t *result)
484 {
485 	struct gic_v3_softc *sc;
486 	struct gic_v3_devinfo *di;
487 
488 	sc = device_get_softc(dev);
489 
490 	switch (which) {
491 	case GICV3_IVAR_NIRQS:
492 		*result = (intr_nirq - sc->gic_nirqs) / sc->gic_nchildren;
493 		return (0);
494 	case GICV3_IVAR_REDIST:
495 		*result = (uintptr_t)&sc->gic_redists.pcpu[PCPU_GET(cpuid)];
496 		return (0);
497 	case GIC_IVAR_HW_REV:
498 		KASSERT(
499 		    GICR_PIDR2_ARCH(sc->gic_pidr2) == GICR_PIDR2_ARCH_GICv3 ||
500 		    GICR_PIDR2_ARCH(sc->gic_pidr2) == GICR_PIDR2_ARCH_GICv4,
501 		    ("gic_v3_read_ivar: Invalid GIC architecture: %d (%.08X)",
502 		     GICR_PIDR2_ARCH(sc->gic_pidr2), sc->gic_pidr2));
503 		*result = GICR_PIDR2_ARCH(sc->gic_pidr2);
504 		return (0);
505 	case GIC_IVAR_BUS:
506 		KASSERT(sc->gic_bus != GIC_BUS_UNKNOWN,
507 		    ("gic_v3_read_ivar: Unknown bus type"));
508 		KASSERT(sc->gic_bus <= GIC_BUS_MAX,
509 		    ("gic_v3_read_ivar: Invalid bus type %u", sc->gic_bus));
510 		*result = sc->gic_bus;
511 		return (0);
512 	case GIC_IVAR_VGIC:
513 		di = device_get_ivars(child);
514 		if (di == NULL)
515 			return (EINVAL);
516 		*result = di->is_vgic;
517 		return (0);
518 	}
519 
520 	return (ENOENT);
521 }
522 
523 static int
524 gic_v3_write_ivar(device_t dev, device_t child, int which, uintptr_t value)
525 {
526 	switch(which) {
527 	case GICV3_IVAR_NIRQS:
528 	case GICV3_IVAR_REDIST:
529 	case GIC_IVAR_HW_REV:
530 	case GIC_IVAR_BUS:
531 		return (EINVAL);
532 	}
533 
534 	return (ENOENT);
535 }
536 
537 static struct resource *
538 gic_v3_alloc_resource(device_t bus, device_t child, int type, int *rid,
539     rman_res_t start, rman_res_t end, rman_res_t count, u_int flags)
540 {
541 	struct gic_v3_softc *sc;
542 	struct resource_list_entry *rle;
543 	struct resource_list *rl;
544 	int j;
545 
546 	/* We only allocate memory */
547 	if (type != SYS_RES_MEMORY)
548 		return (NULL);
549 
550 	sc = device_get_softc(bus);
551 
552 	if (RMAN_IS_DEFAULT_RANGE(start, end)) {
553 		rl = BUS_GET_RESOURCE_LIST(bus, child);
554 		if (rl == NULL)
555 			return (NULL);
556 
557 		/* Find defaults for this rid */
558 		rle = resource_list_find(rl, type, *rid);
559 		if (rle == NULL)
560 			return (NULL);
561 
562 		start = rle->start;
563 		end = rle->end;
564 		count = rle->count;
565 	}
566 
567 	/* Remap through ranges property */
568 	for (j = 0; j < sc->nranges; j++) {
569 		if (start >= sc->ranges[j].bus && end <
570 		    sc->ranges[j].bus + sc->ranges[j].size) {
571 			start -= sc->ranges[j].bus;
572 			start += sc->ranges[j].host;
573 			end -= sc->ranges[j].bus;
574 			end += sc->ranges[j].host;
575 			break;
576 		}
577 	}
578 	if (j == sc->nranges && sc->nranges != 0) {
579 		if (bootverbose)
580 			device_printf(bus, "Could not map resource "
581 			    "%#jx-%#jx\n", (uintmax_t)start, (uintmax_t)end);
582 
583 		return (NULL);
584 	}
585 
586 	return (bus_generic_alloc_resource(bus, child, type, rid, start, end,
587 	    count, flags));
588 }
589 
590 int
591 arm_gic_v3_intr(void *arg)
592 {
593 	struct gic_v3_softc *sc = arg;
594 	struct gic_v3_irqsrc *gi;
595 	struct intr_pic *pic;
596 	uint64_t active_irq;
597 	struct trapframe *tf;
598 
599 	pic = sc->gic_pic;
600 
601 	while (1) {
602 		if (CPU_MATCH_ERRATA_CAVIUM_THUNDERX_1_1) {
603 			/*
604 			 * Hardware:		Cavium ThunderX
605 			 * Chip revision:	Pass 1.0 (early version)
606 			 *			Pass 1.1 (production)
607 			 * ERRATUM:		22978, 23154
608 			 */
609 			__asm __volatile(
610 			    "nop;nop;nop;nop;nop;nop;nop;nop;	\n"
611 			    "mrs %0, ICC_IAR1_EL1		\n"
612 			    "nop;nop;nop;nop;			\n"
613 			    "dsb sy				\n"
614 			    : "=&r" (active_irq));
615 		} else {
616 			active_irq = gic_icc_read(IAR1);
617 		}
618 
619 		if (active_irq >= GIC_FIRST_LPI) {
620 			intr_child_irq_handler(pic, active_irq);
621 			continue;
622 		}
623 
624 		if (__predict_false(active_irq >= sc->gic_nirqs))
625 			return (FILTER_HANDLED);
626 
627 		tf = curthread->td_intr_frame;
628 		gi = &sc->gic_irqs[active_irq];
629 		if (active_irq <= GIC_LAST_SGI) {
630 			/* Call EOI for all IPI before dispatch. */
631 			gic_icc_write(EOIR1, (uint64_t)active_irq);
632 #ifdef SMP
633 			intr_ipi_dispatch(sgi_to_ipi[gi->gi_irq]);
634 #else
635 			device_printf(sc->dev, "SGI %ju on UP system detected\n",
636 			    (uintmax_t)(active_irq - GIC_FIRST_SGI));
637 #endif
638 		} else if (active_irq >= GIC_FIRST_PPI &&
639 		    active_irq <= GIC_LAST_SPI) {
640 			if (gi->gi_trig == INTR_TRIGGER_EDGE)
641 				gic_icc_write(EOIR1, gi->gi_irq);
642 
643 			if (intr_isrc_dispatch(&gi->gi_isrc, tf) != 0) {
644 				if (gi->gi_trig != INTR_TRIGGER_EDGE)
645 					gic_icc_write(EOIR1, gi->gi_irq);
646 				gic_v3_disable_intr(sc->dev, &gi->gi_isrc);
647 				device_printf(sc->dev,
648 				    "Stray irq %lu disabled\n", active_irq);
649 			}
650 		}
651 	}
652 }
653 
654 #ifdef FDT
655 static int
656 gic_map_fdt(device_t dev, u_int ncells, pcell_t *cells, u_int *irqp,
657     enum intr_polarity *polp, enum intr_trigger *trigp)
658 {
659 	u_int irq;
660 
661 	if (ncells < 3)
662 		return (EINVAL);
663 
664 	/*
665 	 * The 1st cell is the interrupt type:
666 	 *	0 = SPI
667 	 *	1 = PPI
668 	 * The 2nd cell contains the interrupt number:
669 	 *	[0 - 987] for SPI
670 	 *	[0 -  15] for PPI
671 	 * The 3rd cell is the flags, encoded as follows:
672 	 *   bits[3:0] trigger type and level flags
673 	 *	1 = edge triggered
674 	 *      2 = edge triggered (PPI only)
675 	 *	4 = level-sensitive
676 	 *	8 = level-sensitive (PPI only)
677 	 */
678 	switch (cells[0]) {
679 	case 0:
680 		irq = GIC_FIRST_SPI + cells[1];
681 		/* SPI irq is checked later. */
682 		break;
683 	case 1:
684 		irq = GIC_FIRST_PPI + cells[1];
685 		if (irq > GIC_LAST_PPI) {
686 			device_printf(dev, "unsupported PPI interrupt "
687 			    "number %u\n", cells[1]);
688 			return (EINVAL);
689 		}
690 		break;
691 	default:
692 		device_printf(dev, "unsupported interrupt type "
693 		    "configuration %u\n", cells[0]);
694 		return (EINVAL);
695 	}
696 
697 	switch (cells[2] & FDT_INTR_MASK) {
698 	case FDT_INTR_EDGE_RISING:
699 		*trigp = INTR_TRIGGER_EDGE;
700 		*polp = INTR_POLARITY_HIGH;
701 		break;
702 	case FDT_INTR_EDGE_FALLING:
703 		*trigp = INTR_TRIGGER_EDGE;
704 		*polp = INTR_POLARITY_LOW;
705 		break;
706 	case FDT_INTR_LEVEL_HIGH:
707 		*trigp = INTR_TRIGGER_LEVEL;
708 		*polp = INTR_POLARITY_HIGH;
709 		break;
710 	case FDT_INTR_LEVEL_LOW:
711 		*trigp = INTR_TRIGGER_LEVEL;
712 		*polp = INTR_POLARITY_LOW;
713 		break;
714 	default:
715 		device_printf(dev, "unsupported trigger/polarity "
716 		    "configuration 0x%02x\n", cells[2]);
717 		return (EINVAL);
718 	}
719 
720 	/* Check the interrupt is valid */
721 	if (irq >= GIC_FIRST_SPI && *polp != INTR_POLARITY_HIGH)
722 		return (EINVAL);
723 
724 	*irqp = irq;
725 	return (0);
726 }
727 #endif
728 
729 static int
730 gic_map_msi(device_t dev, struct intr_map_data_msi *msi_data, u_int *irqp,
731     enum intr_polarity *polp, enum intr_trigger *trigp)
732 {
733 	struct gic_v3_irqsrc *gi;
734 
735 	/* SPI-mapped MSI */
736 	gi = (struct gic_v3_irqsrc *)msi_data->isrc;
737 	if (gi == NULL)
738 		return (ENXIO);
739 
740 	*irqp = gi->gi_irq;
741 
742 	/* MSI/MSI-X interrupts are always edge triggered with high polarity */
743 	*polp = INTR_POLARITY_HIGH;
744 	*trigp = INTR_TRIGGER_EDGE;
745 
746 	return (0);
747 }
748 
749 static int
750 do_gic_v3_map_intr(device_t dev, struct intr_map_data *data, u_int *irqp,
751     enum intr_polarity *polp, enum intr_trigger *trigp)
752 {
753 	struct gic_v3_softc *sc;
754 	enum intr_polarity pol;
755 	enum intr_trigger trig;
756 	struct intr_map_data_msi *dam;
757 #ifdef FDT
758 	struct intr_map_data_fdt *daf;
759 #endif
760 #ifdef DEV_ACPI
761 	struct intr_map_data_acpi *daa;
762 #endif
763 	u_int irq;
764 
765 	sc = device_get_softc(dev);
766 
767 	switch (data->type) {
768 #ifdef FDT
769 	case INTR_MAP_DATA_FDT:
770 		daf = (struct intr_map_data_fdt *)data;
771 		if (gic_map_fdt(dev, daf->ncells, daf->cells, &irq, &pol,
772 		    &trig) != 0)
773 			return (EINVAL);
774 		break;
775 #endif
776 #ifdef DEV_ACPI
777 	case INTR_MAP_DATA_ACPI:
778 		daa = (struct intr_map_data_acpi *)data;
779 		irq = daa->irq;
780 		pol = daa->pol;
781 		trig = daa->trig;
782 		break;
783 #endif
784 	case INTR_MAP_DATA_MSI:
785 		/* SPI-mapped MSI */
786 		dam = (struct intr_map_data_msi *)data;
787 		if (gic_map_msi(dev, dam, &irq, &pol, &trig) != 0)
788 			return (EINVAL);
789 		break;
790 	default:
791 		return (EINVAL);
792 	}
793 
794 	if (irq >= sc->gic_nirqs)
795 		return (EINVAL);
796 	switch (pol) {
797 	case INTR_POLARITY_CONFORM:
798 	case INTR_POLARITY_LOW:
799 	case INTR_POLARITY_HIGH:
800 		break;
801 	default:
802 		return (EINVAL);
803 	}
804 	switch (trig) {
805 	case INTR_TRIGGER_CONFORM:
806 	case INTR_TRIGGER_EDGE:
807 	case INTR_TRIGGER_LEVEL:
808 		break;
809 	default:
810 		return (EINVAL);
811 	}
812 
813 	*irqp = irq;
814 	if (polp != NULL)
815 		*polp = pol;
816 	if (trigp != NULL)
817 		*trigp = trig;
818 	return (0);
819 }
820 
821 static int
822 gic_v3_map_intr(device_t dev, struct intr_map_data *data,
823     struct intr_irqsrc **isrcp)
824 {
825 	struct gic_v3_softc *sc;
826 	int error;
827 	u_int irq;
828 
829 	error = do_gic_v3_map_intr(dev, data, &irq, NULL, NULL);
830 	if (error == 0) {
831 		sc = device_get_softc(dev);
832 		*isrcp = GIC_INTR_ISRC(sc, irq);
833 	}
834 	return (error);
835 }
836 
837 struct gic_v3_setup_periph_args {
838 	device_t		 dev;
839 	struct intr_irqsrc	*isrc;
840 };
841 
842 static void
843 gic_v3_setup_intr_periph(void *argp)
844 {
845 	struct gic_v3_setup_periph_args *args = argp;
846 	struct intr_irqsrc *isrc = args->isrc;
847 	struct gic_v3_irqsrc *gi = (struct gic_v3_irqsrc *)isrc;
848 	device_t dev = args->dev;
849 	u_int irq = gi->gi_irq;
850 	struct gic_v3_softc *sc = device_get_softc(dev);
851 	uint32_t reg;
852 
853 	MPASS(irq <= GIC_LAST_SPI);
854 
855 	/*
856 	 * We need the lock for both SGIs and PPIs for an atomic CPU_SET() at a
857 	 * minimum, but we also need it below for SPIs.
858 	 */
859 	mtx_lock_spin(&sc->gic_mtx);
860 
861 	if (isrc->isrc_flags & INTR_ISRCF_PPI)
862 		CPU_SET(PCPU_GET(cpuid), &isrc->isrc_cpu);
863 
864 	if (irq >= GIC_FIRST_PPI && irq <= GIC_LAST_SPI) {
865 		/* Set the trigger and polarity */
866 		if (irq <= GIC_LAST_PPI)
867 			reg = gic_r_read(sc, 4,
868 			    GICR_SGI_BASE_SIZE + GICD_ICFGR(irq));
869 		else
870 			reg = gic_d_read(sc, 4, GICD_ICFGR(irq));
871 		if (gi->gi_trig == INTR_TRIGGER_LEVEL)
872 			reg &= ~(2 << ((irq % 16) * 2));
873 		else
874 			reg |= 2 << ((irq % 16) * 2);
875 
876 		if (irq <= GIC_LAST_PPI) {
877 			gic_r_write(sc, 4,
878 			    GICR_SGI_BASE_SIZE + GICD_ICFGR(irq), reg);
879 			gic_v3_wait_for_rwp(sc, REDIST);
880 		} else {
881 			gic_d_write(sc, 4, GICD_ICFGR(irq), reg);
882 			gic_v3_wait_for_rwp(sc, DIST);
883 		}
884 	}
885 
886 	mtx_unlock_spin(&sc->gic_mtx);
887 }
888 
889 static int
890 gic_v3_setup_intr(device_t dev, struct intr_irqsrc *isrc,
891     struct resource *res, struct intr_map_data *data)
892 {
893 	struct gic_v3_irqsrc *gi = (struct gic_v3_irqsrc *)isrc;
894 	struct gic_v3_setup_periph_args pargs;
895 	enum intr_trigger trig;
896 	enum intr_polarity pol;
897 	u_int irq;
898 	int error;
899 
900 	if (data == NULL)
901 		return (ENOTSUP);
902 
903 	error = do_gic_v3_map_intr(dev, data, &irq, &pol, &trig);
904 	if (error != 0)
905 		return (error);
906 
907 	if (gi->gi_irq != irq || pol == INTR_POLARITY_CONFORM ||
908 	    trig == INTR_TRIGGER_CONFORM)
909 		return (EINVAL);
910 
911 	/* Compare config if this is not first setup. */
912 	if (isrc->isrc_handlers != 0) {
913 		if (pol != gi->gi_pol || trig != gi->gi_trig)
914 			return (EINVAL);
915 		else
916 			return (0);
917 	}
918 
919 	/* For MSI/MSI-X we should have already configured these */
920 	if ((gi->gi_flags & GI_FLAG_MSI) == 0) {
921 		gi->gi_pol = pol;
922 		gi->gi_trig = trig;
923 	}
924 
925 	pargs.dev = dev;
926 	pargs.isrc = isrc;
927 
928 	if (isrc->isrc_flags & INTR_ISRCF_PPI) {
929 		/*
930 		 * If APs haven't been fired up yet, smp_rendezvous() will just
931 		 * execute it on the single CPU and gic_v3_init_secondary() will
932 		 * clean up afterwards.
933 		 */
934 		smp_rendezvous(NULL, gic_v3_setup_intr_periph, NULL, &pargs);
935 	} else if (irq >= GIC_FIRST_SPI && irq <= GIC_LAST_SPI) {
936 		gic_v3_setup_intr_periph(&pargs);
937 		gic_v3_bind_intr(dev, isrc);
938 	}
939 
940 	return (0);
941 }
942 
943 static int
944 gic_v3_teardown_intr(device_t dev, struct intr_irqsrc *isrc,
945     struct resource *res, struct intr_map_data *data)
946 {
947 	struct gic_v3_irqsrc *gi = (struct gic_v3_irqsrc *)isrc;
948 
949 	if (isrc->isrc_handlers == 0 && (gi->gi_flags & GI_FLAG_MSI) == 0) {
950 		gi->gi_pol = INTR_POLARITY_CONFORM;
951 		gi->gi_trig = INTR_TRIGGER_CONFORM;
952 	}
953 
954 	return (0);
955 }
956 
957 static void
958 gic_v3_disable_intr(device_t dev, struct intr_irqsrc *isrc)
959 {
960 	struct gic_v3_softc *sc;
961 	struct gic_v3_irqsrc *gi;
962 	u_int irq;
963 
964 	sc = device_get_softc(dev);
965 	gi = (struct gic_v3_irqsrc *)isrc;
966 	irq = gi->gi_irq;
967 
968 	if (irq <= GIC_LAST_PPI) {
969 		/* SGIs and PPIs in corresponding Re-Distributor */
970 		gic_r_write(sc, 4, GICR_SGI_BASE_SIZE + GICD_ICENABLER(irq),
971 		    GICD_I_MASK(irq));
972 		gic_v3_wait_for_rwp(sc, REDIST);
973 	} else if (irq >= GIC_FIRST_SPI && irq <= GIC_LAST_SPI) {
974 		/* SPIs in distributor */
975 		gic_d_write(sc, 4, GICD_ICENABLER(irq), GICD_I_MASK(irq));
976 		gic_v3_wait_for_rwp(sc, DIST);
977 	} else
978 		panic("%s: Unsupported IRQ %u", __func__, irq);
979 }
980 
981 static void
982 gic_v3_enable_intr_periph(void *argp)
983 {
984 	struct gic_v3_setup_periph_args *args = argp;
985 	struct gic_v3_irqsrc *gi = (struct gic_v3_irqsrc *)args->isrc;
986 	device_t dev = args->dev;
987 	struct gic_v3_softc *sc = device_get_softc(dev);
988 	u_int irq = gi->gi_irq;
989 
990 	/* SGIs and PPIs in corresponding Re-Distributor */
991 	gic_r_write(sc, 4, GICR_SGI_BASE_SIZE + GICD_ISENABLER(irq),
992 	    GICD_I_MASK(irq));
993 	gic_v3_wait_for_rwp(sc, REDIST);
994 }
995 
996 static void
997 gic_v3_enable_intr(device_t dev, struct intr_irqsrc *isrc)
998 {
999 	struct gic_v3_setup_periph_args pargs;
1000 	struct gic_v3_softc *sc;
1001 	struct gic_v3_irqsrc *gi;
1002 	u_int irq;
1003 
1004 	gi = (struct gic_v3_irqsrc *)isrc;
1005 	irq = gi->gi_irq;
1006 	pargs.isrc = isrc;
1007 	pargs.dev = dev;
1008 
1009 	if (irq <= GIC_LAST_PPI) {
1010 		/*
1011 		 * SGIs only need configured on the current AP.  We'll setup and
1012 		 * enable IPIs as APs come online.
1013 		 */
1014 		if (irq <= GIC_LAST_SGI)
1015 			gic_v3_enable_intr_periph(&pargs);
1016 		else
1017 			smp_rendezvous(NULL, gic_v3_enable_intr_periph, NULL,
1018 			    &pargs);
1019 		return;
1020 	}
1021 
1022 	sc = device_get_softc(dev);
1023 
1024 	if (irq >= GIC_FIRST_SPI && irq <= GIC_LAST_SPI) {
1025 		/* SPIs in distributor */
1026 		gic_d_write(sc, 4, GICD_ISENABLER(irq), GICD_I_MASK(irq));
1027 		gic_v3_wait_for_rwp(sc, DIST);
1028 	} else
1029 		panic("%s: Unsupported IRQ %u", __func__, irq);
1030 }
1031 
1032 static void
1033 gic_v3_pre_ithread(device_t dev, struct intr_irqsrc *isrc)
1034 {
1035 	struct gic_v3_irqsrc *gi = (struct gic_v3_irqsrc *)isrc;
1036 
1037 	gic_v3_disable_intr(dev, isrc);
1038 	gic_icc_write(EOIR1, gi->gi_irq);
1039 }
1040 
1041 static void
1042 gic_v3_post_ithread(device_t dev, struct intr_irqsrc *isrc)
1043 {
1044 
1045 	gic_v3_enable_intr(dev, isrc);
1046 }
1047 
1048 static void
1049 gic_v3_post_filter(device_t dev, struct intr_irqsrc *isrc)
1050 {
1051 	struct gic_v3_irqsrc *gi = (struct gic_v3_irqsrc *)isrc;
1052 
1053 	if (gi->gi_trig == INTR_TRIGGER_EDGE)
1054 		return;
1055 
1056 	gic_icc_write(EOIR1, gi->gi_irq);
1057 }
1058 
1059 static int
1060 gic_v3_bind_intr(device_t dev, struct intr_irqsrc *isrc)
1061 {
1062 	struct gic_v3_softc *sc;
1063 	struct gic_v3_irqsrc *gi;
1064 	int cpu;
1065 
1066 	gi = (struct gic_v3_irqsrc *)isrc;
1067 
1068 	KASSERT(gi->gi_irq >= GIC_FIRST_SPI && gi->gi_irq <= GIC_LAST_SPI,
1069 	    ("%s: Attempting to bind an invalid IRQ", __func__));
1070 
1071 	sc = device_get_softc(dev);
1072 
1073 	if (CPU_EMPTY(&isrc->isrc_cpu)) {
1074 		gic_irq_cpu = intr_irq_next_cpu(gic_irq_cpu, &all_cpus);
1075 		CPU_SETOF(gic_irq_cpu, &isrc->isrc_cpu);
1076 		gic_d_write(sc, 8, GICD_IROUTER(gi->gi_irq),
1077 		    CPU_AFFINITY(gic_irq_cpu));
1078 	} else {
1079 		/*
1080 		 * We can only bind to a single CPU so select
1081 		 * the first CPU found.
1082 		 */
1083 		cpu = CPU_FFS(&isrc->isrc_cpu) - 1;
1084 		gic_d_write(sc, 8, GICD_IROUTER(gi->gi_irq), CPU_AFFINITY(cpu));
1085 	}
1086 
1087 	return (0);
1088 }
1089 
1090 #ifdef SMP
1091 static void
1092 gic_v3_init_secondary(device_t dev)
1093 {
1094 	struct gic_v3_setup_periph_args pargs;
1095 	device_t child;
1096 	struct gic_v3_softc *sc;
1097 	gic_v3_initseq_t *init_func;
1098 	struct intr_irqsrc *isrc;
1099 	u_int cpu, irq;
1100 	int err, i;
1101 
1102 	sc = device_get_softc(dev);
1103 	cpu = PCPU_GET(cpuid);
1104 
1105 	/* Train init sequence for boot CPU */
1106 	for (init_func = gic_v3_secondary_init; *init_func != NULL;
1107 	    init_func++) {
1108 		err = (*init_func)(sc);
1109 		if (err != 0) {
1110 			device_printf(dev,
1111 			    "Could not initialize GIC for CPU%u\n", cpu);
1112 			return;
1113 		}
1114 	}
1115 
1116 	pargs.dev = dev;
1117 
1118 	/* Unmask attached SGI interrupts. */
1119 	for (irq = GIC_FIRST_SGI; irq <= GIC_LAST_SGI; irq++) {
1120 		isrc = GIC_INTR_ISRC(sc, irq);
1121 		if (intr_isrc_init_on_cpu(isrc, cpu)) {
1122 			pargs.isrc = isrc;
1123 			gic_v3_enable_intr_periph(&pargs);
1124 		}
1125 	}
1126 
1127 	/* Unmask attached PPI interrupts. */
1128 	for (irq = GIC_FIRST_PPI; irq <= GIC_LAST_PPI; irq++) {
1129 		isrc = GIC_INTR_ISRC(sc, irq);
1130 		if (intr_isrc_init_on_cpu(isrc, cpu)) {
1131 			pargs.isrc = isrc;
1132 			gic_v3_setup_intr_periph(&pargs);
1133 			gic_v3_enable_intr_periph(&pargs);
1134 		}
1135 	}
1136 
1137 	for (i = 0; i < sc->gic_nchildren; i++) {
1138 		child = sc->gic_children[i];
1139 		PIC_INIT_SECONDARY(child);
1140 	}
1141 }
1142 
1143 static void
1144 gic_v3_ipi_send(device_t dev, struct intr_irqsrc *isrc, cpuset_t cpus,
1145     u_int ipi)
1146 {
1147 	struct gic_v3_irqsrc *gi = (struct gic_v3_irqsrc *)isrc;
1148 	uint64_t aff, val, irq;
1149 	int i;
1150 
1151 #define	GIC_AFF_MASK	(CPU_AFF3_MASK | CPU_AFF2_MASK | CPU_AFF1_MASK)
1152 #define	GIC_AFFINITY(i)	(CPU_AFFINITY(i) & GIC_AFF_MASK)
1153 	aff = GIC_AFFINITY(0);
1154 	irq = gi->gi_irq;
1155 	val = 0;
1156 
1157 	/* Iterate through all CPUs in set */
1158 	for (i = 0; i <= mp_maxid; i++) {
1159 		/* Move to the next affinity group */
1160 		if (aff != GIC_AFFINITY(i)) {
1161 			/* Send the IPI */
1162 			if (val != 0) {
1163 				gic_icc_write(SGI1R, val);
1164 				val = 0;
1165 			}
1166 			aff = GIC_AFFINITY(i);
1167 		}
1168 
1169 		/* Send the IPI to this cpu */
1170 		if (CPU_ISSET(i, &cpus)) {
1171 #define	ICC_SGI1R_AFFINITY(aff)					\
1172     (((uint64_t)CPU_AFF3(aff) << ICC_SGI1R_EL1_AFF3_SHIFT) |	\
1173      ((uint64_t)CPU_AFF2(aff) << ICC_SGI1R_EL1_AFF2_SHIFT) |	\
1174      ((uint64_t)CPU_AFF1(aff) << ICC_SGI1R_EL1_AFF1_SHIFT))
1175 			/* Set the affinity when the first at this level */
1176 			if (val == 0)
1177 				val = ICC_SGI1R_AFFINITY(aff) |
1178 				    irq << ICC_SGI1R_EL1_SGIID_SHIFT;
1179 			/* Set the bit to send the IPI to te CPU */
1180 			val |= 1 << CPU_AFF0(CPU_AFFINITY(i));
1181 		}
1182 	}
1183 
1184 	/* Send the IPI to the last cpu affinity group */
1185 	if (val != 0)
1186 		gic_icc_write(SGI1R, val);
1187 #undef GIC_AFF_MASK
1188 #undef GIC_AFFINITY
1189 }
1190 
1191 static int
1192 gic_v3_ipi_setup(device_t dev, u_int ipi, struct intr_irqsrc **isrcp)
1193 {
1194 	struct intr_irqsrc *isrc;
1195 	struct gic_v3_softc *sc = device_get_softc(dev);
1196 
1197 	if (sgi_first_unused > GIC_LAST_SGI)
1198 		return (ENOSPC);
1199 
1200 	isrc = GIC_INTR_ISRC(sc, sgi_first_unused);
1201 	sgi_to_ipi[sgi_first_unused++] = ipi;
1202 
1203 	CPU_SET(PCPU_GET(cpuid), &isrc->isrc_cpu);
1204 
1205 	*isrcp = isrc;
1206 	return (0);
1207 }
1208 #endif /* SMP */
1209 
1210 /*
1211  * Helper routines
1212  */
1213 static void
1214 gic_v3_wait_for_rwp(struct gic_v3_softc *sc, enum gic_v3_xdist xdist)
1215 {
1216 	struct resource *res;
1217 	bus_size_t offset;
1218 	u_int cpuid;
1219 	size_t us_left = 1000000;
1220 
1221 	cpuid = PCPU_GET(cpuid);
1222 
1223 	switch (xdist) {
1224 	case DIST:
1225 		res = sc->gic_dist;
1226 		offset = 0;
1227 		break;
1228 	case REDIST:
1229 		res = sc->gic_redists.pcpu[cpuid].res;
1230 		offset = sc->gic_redists.pcpu[PCPU_GET(cpuid)].offset;
1231 		break;
1232 	default:
1233 		KASSERT(0, ("%s: Attempt to wait for unknown RWP", __func__));
1234 		return;
1235 	}
1236 
1237 	while ((bus_read_4(res, offset + GICD_CTLR) & GICD_CTLR_RWP) != 0) {
1238 		DELAY(1);
1239 		if (us_left-- == 0)
1240 			panic("GICD Register write pending for too long");
1241 	}
1242 }
1243 
1244 /* CPU interface. */
1245 static __inline void
1246 gic_v3_cpu_priority(uint64_t mask)
1247 {
1248 
1249 	/* Set prority mask */
1250 	gic_icc_write(PMR, mask & ICC_PMR_EL1_PRIO_MASK);
1251 }
1252 
1253 static int
1254 gic_v3_cpu_enable_sre(struct gic_v3_softc *sc)
1255 {
1256 	uint64_t sre;
1257 	u_int cpuid;
1258 
1259 	cpuid = PCPU_GET(cpuid);
1260 	/*
1261 	 * Set the SRE bit to enable access to GIC CPU interface
1262 	 * via system registers.
1263 	 */
1264 	sre = READ_SPECIALREG(icc_sre_el1);
1265 	sre |= ICC_SRE_EL1_SRE;
1266 	WRITE_SPECIALREG(icc_sre_el1, sre);
1267 	isb();
1268 	/*
1269 	 * Now ensure that the bit is set.
1270 	 */
1271 	sre = READ_SPECIALREG(icc_sre_el1);
1272 	if ((sre & ICC_SRE_EL1_SRE) == 0) {
1273 		/* We are done. This was disabled in EL2 */
1274 		device_printf(sc->dev, "ERROR: CPU%u cannot enable CPU interface "
1275 		    "via system registers\n", cpuid);
1276 		return (ENXIO);
1277 	} else if (bootverbose) {
1278 		device_printf(sc->dev,
1279 		    "CPU%u enabled CPU interface via system registers\n",
1280 		    cpuid);
1281 	}
1282 
1283 	return (0);
1284 }
1285 
1286 static int
1287 gic_v3_cpu_init(struct gic_v3_softc *sc)
1288 {
1289 	int err;
1290 
1291 	/* Enable access to CPU interface via system registers */
1292 	err = gic_v3_cpu_enable_sre(sc);
1293 	if (err != 0)
1294 		return (err);
1295 	/* Priority mask to minimum - accept all interrupts */
1296 	gic_v3_cpu_priority(GIC_PRIORITY_MIN);
1297 	/* Disable EOI mode */
1298 	gic_icc_clear(CTLR, ICC_CTLR_EL1_EOIMODE);
1299 	/* Enable group 1 (insecure) interrups */
1300 	gic_icc_set(IGRPEN1, ICC_IGRPEN0_EL1_EN);
1301 
1302 	return (0);
1303 }
1304 
1305 /* Distributor */
1306 static int
1307 gic_v3_dist_init(struct gic_v3_softc *sc)
1308 {
1309 	uint64_t aff;
1310 	u_int i;
1311 
1312 	/*
1313 	 * 1. Disable the Distributor
1314 	 */
1315 	gic_d_write(sc, 4, GICD_CTLR, 0);
1316 	gic_v3_wait_for_rwp(sc, DIST);
1317 
1318 	/*
1319 	 * 2. Configure the Distributor
1320 	 */
1321 	/* Set all SPIs to be Group 1 Non-secure */
1322 	for (i = GIC_FIRST_SPI; i < sc->gic_nirqs; i += GICD_I_PER_IGROUPRn)
1323 		gic_d_write(sc, 4, GICD_IGROUPR(i), 0xFFFFFFFF);
1324 
1325 	/* Set all global interrupts to be level triggered, active low. */
1326 	for (i = GIC_FIRST_SPI; i < sc->gic_nirqs; i += GICD_I_PER_ICFGRn)
1327 		gic_d_write(sc, 4, GICD_ICFGR(i), 0x00000000);
1328 
1329 	/* Set priority to all shared interrupts */
1330 	for (i = GIC_FIRST_SPI;
1331 	    i < sc->gic_nirqs; i += GICD_I_PER_IPRIORITYn) {
1332 		/* Set highest priority */
1333 		gic_d_write(sc, 4, GICD_IPRIORITYR(i), GIC_PRIORITY_MAX);
1334 	}
1335 
1336 	/*
1337 	 * Disable all interrupts. Leave PPI and SGIs as they are enabled in
1338 	 * Re-Distributor registers.
1339 	 */
1340 	for (i = GIC_FIRST_SPI; i < sc->gic_nirqs; i += GICD_I_PER_ISENABLERn)
1341 		gic_d_write(sc, 4, GICD_ICENABLER(i), 0xFFFFFFFF);
1342 
1343 	gic_v3_wait_for_rwp(sc, DIST);
1344 
1345 	/*
1346 	 * 3. Enable Distributor
1347 	 */
1348 	/* Enable Distributor with ARE, Group 1 */
1349 	gic_d_write(sc, 4, GICD_CTLR, GICD_CTLR_ARE_NS | GICD_CTLR_G1A |
1350 	    GICD_CTLR_G1);
1351 
1352 	/*
1353 	 * 4. Route all interrupts to boot CPU.
1354 	 */
1355 	aff = CPU_AFFINITY(0);
1356 	for (i = GIC_FIRST_SPI; i < sc->gic_nirqs; i++)
1357 		gic_d_write(sc, 8, GICD_IROUTER(i), aff);
1358 
1359 	return (0);
1360 }
1361 
1362 /* Re-Distributor */
1363 static int
1364 gic_v3_redist_alloc(struct gic_v3_softc *sc)
1365 {
1366 	sc->gic_redists.pcpu = mallocarray(mp_maxid + 1,
1367 	    sizeof(sc->gic_redists.pcpu[0]), M_GIC_V3, M_WAITOK);
1368 	return (0);
1369 }
1370 
1371 static int
1372 gic_v3_redist_find(struct gic_v3_softc *sc)
1373 {
1374 	struct resource *r_res;
1375 	bus_size_t offset;
1376 	uint64_t aff;
1377 	uint64_t typer;
1378 	uint32_t pidr2;
1379 	u_int cpuid;
1380 	size_t i;
1381 
1382 	cpuid = PCPU_GET(cpuid);
1383 
1384 	aff = CPU_AFFINITY(cpuid);
1385 	/* Affinity in format for comparison with typer */
1386 	aff = (CPU_AFF3(aff) << 24) | (CPU_AFF2(aff) << 16) |
1387 	    (CPU_AFF1(aff) << 8) | CPU_AFF0(aff);
1388 
1389 	if (bootverbose) {
1390 		device_printf(sc->dev,
1391 		    "Start searching for Re-Distributor\n");
1392 	}
1393 	/* Iterate through Re-Distributor regions */
1394 	for (i = 0; i < sc->gic_redists.nregions; i++) {
1395 		/* Take a copy of the region's resource */
1396 		r_res = sc->gic_redists.regions[i];
1397 
1398 		pidr2 = bus_read_4(r_res, GICR_PIDR2);
1399 		switch (GICR_PIDR2_ARCH(pidr2)) {
1400 		case GICR_PIDR2_ARCH_GICv3: /* fall through */
1401 		case GICR_PIDR2_ARCH_GICv4:
1402 			break;
1403 		default:
1404 			device_printf(sc->dev,
1405 			    "No Re-Distributor found for CPU%u\n", cpuid);
1406 			return (ENODEV);
1407 		}
1408 
1409 		offset = 0;
1410 		do {
1411 			typer = bus_read_8(r_res, offset + GICR_TYPER);
1412 			if ((typer >> GICR_TYPER_AFF_SHIFT) == aff) {
1413 				KASSERT(cpuid <= mp_maxid,
1414 				    ("Invalid pointer to per-CPU redistributor"));
1415 				/* Copy res contents to its final destination */
1416 				sc->gic_redists.pcpu[cpuid].res = r_res;
1417 				sc->gic_redists.pcpu[cpuid].offset = offset;
1418 				sc->gic_redists.pcpu[cpuid].lpi_enabled = false;
1419 				if (bootverbose) {
1420 					device_printf(sc->dev,
1421 					    "CPU%u Re-Distributor has been found\n",
1422 					    cpuid);
1423 				}
1424 				return (0);
1425 			}
1426 
1427 			offset += (GICR_RD_BASE_SIZE + GICR_SGI_BASE_SIZE);
1428 			if ((typer & GICR_TYPER_VLPIS) != 0) {
1429 				offset +=
1430 				    (GICR_VLPI_BASE_SIZE + GICR_RESERVED_SIZE);
1431 			}
1432 		} while (offset < rman_get_size(r_res) &&
1433 		    (typer & GICR_TYPER_LAST) == 0);
1434 	}
1435 
1436 	device_printf(sc->dev, "No Re-Distributor found for CPU%u\n", cpuid);
1437 	return (ENXIO);
1438 }
1439 
1440 static int
1441 gic_v3_redist_wake(struct gic_v3_softc *sc)
1442 {
1443 	uint32_t waker;
1444 	size_t us_left = 1000000;
1445 
1446 	waker = gic_r_read(sc, 4, GICR_WAKER);
1447 	/* Wake up Re-Distributor for this CPU */
1448 	waker &= ~GICR_WAKER_PS;
1449 	gic_r_write(sc, 4, GICR_WAKER, waker);
1450 	/*
1451 	 * When clearing ProcessorSleep bit it is required to wait for
1452 	 * ChildrenAsleep to become zero following the processor power-on.
1453 	 */
1454 	while ((gic_r_read(sc, 4, GICR_WAKER) & GICR_WAKER_CA) != 0) {
1455 		DELAY(1);
1456 		if (us_left-- == 0) {
1457 			panic("Could not wake Re-Distributor for CPU%u",
1458 			    PCPU_GET(cpuid));
1459 		}
1460 	}
1461 
1462 	if (bootverbose) {
1463 		device_printf(sc->dev, "CPU%u Re-Distributor woke up\n",
1464 		    PCPU_GET(cpuid));
1465 	}
1466 
1467 	return (0);
1468 }
1469 
1470 static int
1471 gic_v3_redist_init(struct gic_v3_softc *sc)
1472 {
1473 	int err;
1474 	size_t i;
1475 
1476 	err = gic_v3_redist_find(sc);
1477 	if (err != 0)
1478 		return (err);
1479 
1480 	err = gic_v3_redist_wake(sc);
1481 	if (err != 0)
1482 		return (err);
1483 
1484 	/* Configure SGIs and PPIs to be Group1 Non-secure */
1485 	gic_r_write(sc, 4, GICR_SGI_BASE_SIZE + GICR_IGROUPR0,
1486 	    0xFFFFFFFF);
1487 
1488 	/* Disable SPIs */
1489 	gic_r_write(sc, 4, GICR_SGI_BASE_SIZE + GICR_ICENABLER0,
1490 	    GICR_I_ENABLER_PPI_MASK);
1491 	/* Enable SGIs */
1492 	gic_r_write(sc, 4, GICR_SGI_BASE_SIZE + GICR_ISENABLER0,
1493 	    GICR_I_ENABLER_SGI_MASK);
1494 
1495 	/* Set priority for SGIs and PPIs */
1496 	for (i = 0; i <= GIC_LAST_PPI; i += GICR_I_PER_IPRIORITYn) {
1497 		gic_r_write(sc, 4, GICR_SGI_BASE_SIZE + GICD_IPRIORITYR(i),
1498 		    GIC_PRIORITY_MAX);
1499 	}
1500 
1501 	gic_v3_wait_for_rwp(sc, REDIST);
1502 
1503 	return (0);
1504 }
1505 
1506 /*
1507  * SPI-mapped Message Based Interrupts -- a GICv3 MSI/MSI-X controller.
1508  */
1509 
1510 static int
1511 gic_v3_gic_alloc_msi(device_t dev, u_int mbi_start, u_int mbi_count,
1512     int count, int maxcount, struct intr_irqsrc **isrc)
1513 {
1514 	struct gic_v3_softc *sc;
1515 	int i, irq, end_irq;
1516 	bool found;
1517 
1518 	KASSERT(powerof2(count), ("%s: bad count", __func__));
1519 	KASSERT(powerof2(maxcount), ("%s: bad maxcount", __func__));
1520 
1521 	sc = device_get_softc(dev);
1522 
1523 	mtx_lock(&sc->gic_mbi_mtx);
1524 
1525 	found = false;
1526 	for (irq = mbi_start; irq < mbi_start + mbi_count; irq++) {
1527 		/* Start on an aligned interrupt */
1528 		if ((irq & (maxcount - 1)) != 0)
1529 			continue;
1530 
1531 		/* Assume we found a valid range until shown otherwise */
1532 		found = true;
1533 
1534 		/* Check this range is valid */
1535 		for (end_irq = irq; end_irq != irq + count; end_irq++) {
1536 			/* No free interrupts */
1537 			if (end_irq == mbi_start + mbi_count) {
1538 				found = false;
1539 				break;
1540 			}
1541 
1542 			KASSERT((sc->gic_irqs[end_irq].gi_flags & GI_FLAG_MSI)!= 0,
1543 			    ("%s: Non-MSI interrupt found", __func__));
1544 
1545 			/* This is already used */
1546 			if ((sc->gic_irqs[end_irq].gi_flags & GI_FLAG_MSI_USED) ==
1547 			    GI_FLAG_MSI_USED) {
1548 				found = false;
1549 				break;
1550 			}
1551 		}
1552 		if (found)
1553 			break;
1554 	}
1555 
1556 	/* Not enough interrupts were found */
1557 	if (!found || irq == mbi_start + mbi_count) {
1558 		mtx_unlock(&sc->gic_mbi_mtx);
1559 		return (ENXIO);
1560 	}
1561 
1562 	for (i = 0; i < count; i++) {
1563 		/* Mark the interrupt as used */
1564 		sc->gic_irqs[irq + i].gi_flags |= GI_FLAG_MSI_USED;
1565 	}
1566 	mtx_unlock(&sc->gic_mbi_mtx);
1567 
1568 	for (i = 0; i < count; i++)
1569 		isrc[i] = (struct intr_irqsrc *)&sc->gic_irqs[irq + i];
1570 
1571 	return (0);
1572 }
1573 
1574 static int
1575 gic_v3_gic_release_msi(device_t dev, int count, struct intr_irqsrc **isrc)
1576 {
1577 	struct gic_v3_softc *sc;
1578 	struct gic_v3_irqsrc *gi;
1579 	int i;
1580 
1581 	sc = device_get_softc(dev);
1582 
1583 	mtx_lock(&sc->gic_mbi_mtx);
1584 	for (i = 0; i < count; i++) {
1585 		gi = (struct gic_v3_irqsrc *)isrc[i];
1586 
1587 		KASSERT((gi->gi_flags & GI_FLAG_MSI_USED) == GI_FLAG_MSI_USED,
1588 		    ("%s: Trying to release an unused MSI-X interrupt",
1589 		    __func__));
1590 
1591 		gi->gi_flags &= ~GI_FLAG_MSI_USED;
1592 	}
1593 	mtx_unlock(&sc->gic_mbi_mtx);
1594 
1595 	return (0);
1596 }
1597 
1598 static int
1599 gic_v3_gic_alloc_msix(device_t dev, u_int mbi_start, u_int mbi_count,
1600     struct intr_irqsrc **isrcp)
1601 {
1602 	struct gic_v3_softc *sc;
1603 	int irq;
1604 
1605 	sc = device_get_softc(dev);
1606 
1607 	mtx_lock(&sc->gic_mbi_mtx);
1608 	/* Find an unused interrupt */
1609 	for (irq = mbi_start; irq < mbi_start + mbi_count; irq++) {
1610 		KASSERT((sc->gic_irqs[irq].gi_flags & GI_FLAG_MSI) != 0,
1611 		    ("%s: Non-MSI interrupt found", __func__));
1612 		if ((sc->gic_irqs[irq].gi_flags & GI_FLAG_MSI_USED) == 0)
1613 			break;
1614 	}
1615 	/* No free interrupt was found */
1616 	if (irq == mbi_start + mbi_count) {
1617 		mtx_unlock(&sc->gic_mbi_mtx);
1618 		return (ENXIO);
1619 	}
1620 
1621 	/* Mark the interrupt as used */
1622 	sc->gic_irqs[irq].gi_flags |= GI_FLAG_MSI_USED;
1623 	mtx_unlock(&sc->gic_mbi_mtx);
1624 
1625 	*isrcp = (struct intr_irqsrc *)&sc->gic_irqs[irq];
1626 
1627 	return (0);
1628 }
1629 
1630 static int
1631 gic_v3_gic_release_msix(device_t dev, struct intr_irqsrc *isrc)
1632 {
1633 	struct gic_v3_softc *sc;
1634 	struct gic_v3_irqsrc *gi;
1635 
1636 	sc = device_get_softc(dev);
1637 	gi = (struct gic_v3_irqsrc *)isrc;
1638 
1639 	KASSERT((gi->gi_flags & GI_FLAG_MSI_USED) == GI_FLAG_MSI_USED,
1640 	    ("%s: Trying to release an unused MSI-X interrupt", __func__));
1641 
1642 	mtx_lock(&sc->gic_mbi_mtx);
1643 	gi->gi_flags &= ~GI_FLAG_MSI_USED;
1644 	mtx_unlock(&sc->gic_mbi_mtx);
1645 
1646 	return (0);
1647 }
1648 
1649 static int
1650 gic_v3_alloc_msi(device_t dev, device_t child, int count, int maxcount,
1651     device_t *pic, struct intr_irqsrc **isrc)
1652 {
1653 	struct gic_v3_softc *sc;
1654 	int error;
1655 
1656 	sc = device_get_softc(dev);
1657 	error = gic_v3_gic_alloc_msi(dev, sc->gic_mbi_start,
1658 	    sc->gic_mbi_end - sc->gic_mbi_start, count, maxcount, isrc);
1659 	if (error != 0)
1660 		return (error);
1661 
1662 	*pic = dev;
1663 	return (0);
1664 }
1665 
1666 static int
1667 gic_v3_release_msi(device_t dev, device_t child, int count,
1668     struct intr_irqsrc **isrc)
1669 {
1670 	return (gic_v3_gic_release_msi(dev, count, isrc));
1671 }
1672 
1673 static int
1674 gic_v3_alloc_msix(device_t dev, device_t child, device_t *pic,
1675     struct intr_irqsrc **isrc)
1676 {
1677 	struct gic_v3_softc *sc;
1678 	int error;
1679 
1680 	sc = device_get_softc(dev);
1681 	error = gic_v3_gic_alloc_msix(dev, sc->gic_mbi_start,
1682 	    sc->gic_mbi_end - sc->gic_mbi_start, isrc);
1683 	if (error != 0)
1684 		return (error);
1685 
1686 	*pic = dev;
1687 
1688 	return (0);
1689 }
1690 
1691 static int
1692 gic_v3_release_msix(device_t dev, device_t child, struct intr_irqsrc *isrc)
1693 {
1694 	return (gic_v3_gic_release_msix(dev, isrc));
1695 }
1696 
1697 static int
1698 gic_v3_map_msi(device_t dev, device_t child, struct intr_irqsrc *isrc,
1699     uint64_t *addr, uint32_t *data)
1700 {
1701 	struct gic_v3_softc *sc = device_get_softc(dev);
1702 	struct gic_v3_irqsrc *gi = (struct gic_v3_irqsrc *)isrc;
1703 
1704 	*addr = vtophys(rman_get_virtual(sc->gic_dist)) + GICD_SETSPI_NSR;
1705 	*data = gi->gi_irq;
1706 
1707 	return (0);
1708 }
1709