xref: /freebsd-13-stable/sys/dev/pci/pci_pci.c (revision 00c8c5e2c35862d61ddb2618d5ecd08db1e9fb89)
1 /*-
2  * SPDX-License-Identifier: BSD-3-Clause
3  *
4  * Copyright (c) 1994,1995 Stefan Esser, Wolfgang StanglMeier
5  * Copyright (c) 2000 Michael Smith <msmith@freebsd.org>
6  * Copyright (c) 2000 BSDi
7  * All rights reserved.
8  *
9  * Redistribution and use in source and binary forms, with or without
10  * modification, are permitted provided that the following conditions
11  * are met:
12  * 1. Redistributions of source code must retain the above copyright
13  *    notice, this list of conditions and the following disclaimer.
14  * 2. Redistributions in binary form must reproduce the above copyright
15  *    notice, this list of conditions and the following disclaimer in the
16  *    documentation and/or other materials provided with the distribution.
17  * 3. The name of the author may not be used to endorse or promote products
18  *    derived from this software without specific prior written permission.
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 <sys/cdefs.h>
34 /*
35  * PCI:PCI bridge support.
36  */
37 
38 #include "opt_pci.h"
39 
40 #include <sys/param.h>
41 #include <sys/bus.h>
42 #include <sys/kernel.h>
43 #include <sys/lock.h>
44 #include <sys/malloc.h>
45 #include <sys/module.h>
46 #include <sys/mutex.h>
47 #include <sys/pciio.h>
48 #include <sys/rman.h>
49 #include <sys/sysctl.h>
50 #include <sys/systm.h>
51 #include <sys/taskqueue.h>
52 
53 #include <dev/pci/pcivar.h>
54 #include <dev/pci/pcireg.h>
55 #include <dev/pci/pci_private.h>
56 #include <dev/pci/pcib_private.h>
57 
58 #include "pcib_if.h"
59 
60 static int		pcib_probe(device_t dev);
61 static int		pcib_suspend(device_t dev);
62 static int		pcib_resume(device_t dev);
63 
64 static bus_child_present_t	pcib_child_present;
65 static bus_alloc_resource_t	pcib_alloc_resource;
66 #ifdef NEW_PCIB
67 static bus_adjust_resource_t	pcib_adjust_resource;
68 static bus_release_resource_t	pcib_release_resource;
69 #endif
70 static int		pcib_reset_child(device_t dev, device_t child, int flags);
71 
72 static int		pcib_power_for_sleep(device_t pcib, device_t dev,
73 			    int *pstate);
74 static int		pcib_ari_get_id(device_t pcib, device_t dev,
75     enum pci_id_type type, uintptr_t *id);
76 static uint32_t		pcib_read_config(device_t dev, u_int b, u_int s,
77     u_int f, u_int reg, int width);
78 static void		pcib_write_config(device_t dev, u_int b, u_int s,
79     u_int f, u_int reg, uint32_t val, int width);
80 static int		pcib_ari_maxslots(device_t dev);
81 static int		pcib_ari_maxfuncs(device_t dev);
82 static int		pcib_try_enable_ari(device_t pcib, device_t dev);
83 static int		pcib_ari_enabled(device_t pcib);
84 static void		pcib_ari_decode_rid(device_t pcib, uint16_t rid,
85 			    int *bus, int *slot, int *func);
86 #ifdef PCI_HP
87 static void		pcib_pcie_ab_timeout(void *arg, int pending);
88 static void		pcib_pcie_cc_timeout(void *arg, int pending);
89 static void		pcib_pcie_dll_timeout(void *arg, int pending);
90 #endif
91 static int		pcib_request_feature_default(device_t pcib, device_t dev,
92 			    enum pci_feature feature);
93 
94 static device_method_t pcib_methods[] = {
95     /* Device interface */
96     DEVMETHOD(device_probe,		pcib_probe),
97     DEVMETHOD(device_attach,		pcib_attach),
98     DEVMETHOD(device_detach,		pcib_detach),
99     DEVMETHOD(device_shutdown,		bus_generic_shutdown),
100     DEVMETHOD(device_suspend,		pcib_suspend),
101     DEVMETHOD(device_resume,		pcib_resume),
102 
103     /* Bus interface */
104     DEVMETHOD(bus_child_present,	pcib_child_present),
105     DEVMETHOD(bus_read_ivar,		pcib_read_ivar),
106     DEVMETHOD(bus_write_ivar,		pcib_write_ivar),
107     DEVMETHOD(bus_alloc_resource,	pcib_alloc_resource),
108 #ifdef NEW_PCIB
109     DEVMETHOD(bus_adjust_resource,	pcib_adjust_resource),
110     DEVMETHOD(bus_release_resource,	pcib_release_resource),
111 #else
112     DEVMETHOD(bus_adjust_resource,	bus_generic_adjust_resource),
113     DEVMETHOD(bus_release_resource,	bus_generic_release_resource),
114 #endif
115     DEVMETHOD(bus_activate_resource,	bus_generic_activate_resource),
116     DEVMETHOD(bus_deactivate_resource,	bus_generic_deactivate_resource),
117     DEVMETHOD(bus_setup_intr,		bus_generic_setup_intr),
118     DEVMETHOD(bus_teardown_intr,	bus_generic_teardown_intr),
119     DEVMETHOD(bus_reset_child,		pcib_reset_child),
120 
121     /* pcib interface */
122     DEVMETHOD(pcib_maxslots,		pcib_ari_maxslots),
123     DEVMETHOD(pcib_maxfuncs,		pcib_ari_maxfuncs),
124     DEVMETHOD(pcib_read_config,		pcib_read_config),
125     DEVMETHOD(pcib_write_config,	pcib_write_config),
126     DEVMETHOD(pcib_route_interrupt,	pcib_route_interrupt),
127     DEVMETHOD(pcib_alloc_msi,		pcib_alloc_msi),
128     DEVMETHOD(pcib_release_msi,		pcib_release_msi),
129     DEVMETHOD(pcib_alloc_msix,		pcib_alloc_msix),
130     DEVMETHOD(pcib_release_msix,	pcib_release_msix),
131     DEVMETHOD(pcib_map_msi,		pcib_map_msi),
132     DEVMETHOD(pcib_power_for_sleep,	pcib_power_for_sleep),
133     DEVMETHOD(pcib_get_id,		pcib_ari_get_id),
134     DEVMETHOD(pcib_try_enable_ari,	pcib_try_enable_ari),
135     DEVMETHOD(pcib_ari_enabled,		pcib_ari_enabled),
136     DEVMETHOD(pcib_decode_rid,		pcib_ari_decode_rid),
137     DEVMETHOD(pcib_request_feature,	pcib_request_feature_default),
138 
139     DEVMETHOD_END
140 };
141 
142 static devclass_t pcib_devclass;
143 
144 DEFINE_CLASS_0(pcib, pcib_driver, pcib_methods, sizeof(struct pcib_softc));
145 EARLY_DRIVER_MODULE(pcib, pci, pcib_driver, pcib_devclass, NULL, NULL,
146     BUS_PASS_BUS);
147 
148 #if defined(NEW_PCIB) || defined(PCI_HP)
149 SYSCTL_DECL(_hw_pci);
150 #endif
151 
152 #ifdef NEW_PCIB
153 static int pci_clear_pcib;
154 SYSCTL_INT(_hw_pci, OID_AUTO, clear_pcib, CTLFLAG_RDTUN, &pci_clear_pcib, 0,
155     "Clear firmware-assigned resources for PCI-PCI bridge I/O windows.");
156 
157 /*
158  * Get the corresponding window if this resource from a child device was
159  * sub-allocated from one of our window resource managers.
160  */
161 static struct pcib_window *
pcib_get_resource_window(struct pcib_softc * sc,int type,struct resource * r)162 pcib_get_resource_window(struct pcib_softc *sc, int type, struct resource *r)
163 {
164 	switch (type) {
165 	case SYS_RES_IOPORT:
166 		if (rman_is_region_manager(r, &sc->io.rman))
167 			return (&sc->io);
168 		break;
169 	case SYS_RES_MEMORY:
170 		/* Prefetchable resources may live in either memory rman. */
171 		if (rman_get_flags(r) & RF_PREFETCHABLE &&
172 		    rman_is_region_manager(r, &sc->pmem.rman))
173 			return (&sc->pmem);
174 		if (rman_is_region_manager(r, &sc->mem.rman))
175 			return (&sc->mem);
176 		break;
177 	}
178 	return (NULL);
179 }
180 
181 /*
182  * Is a resource from a child device sub-allocated from one of our
183  * resource managers?
184  */
185 static int
pcib_is_resource_managed(struct pcib_softc * sc,int type,struct resource * r)186 pcib_is_resource_managed(struct pcib_softc *sc, int type, struct resource *r)
187 {
188 
189 #ifdef PCI_RES_BUS
190 	if (type == PCI_RES_BUS)
191 		return (rman_is_region_manager(r, &sc->bus.rman));
192 #endif
193 	return (pcib_get_resource_window(sc, type, r) != NULL);
194 }
195 
196 static int
pcib_is_window_open(struct pcib_window * pw)197 pcib_is_window_open(struct pcib_window *pw)
198 {
199 
200 	return (pw->valid && pw->base < pw->limit);
201 }
202 
203 /*
204  * XXX: If RF_ACTIVE did not also imply allocating a bus space tag and
205  * handle for the resource, we could pass RF_ACTIVE up to the PCI bus
206  * when allocating the resource windows and rely on the PCI bus driver
207  * to do this for us.
208  */
209 static void
pcib_activate_window(struct pcib_softc * sc,int type)210 pcib_activate_window(struct pcib_softc *sc, int type)
211 {
212 
213 	PCI_ENABLE_IO(device_get_parent(sc->dev), sc->dev, type);
214 }
215 
216 static void
pcib_write_windows(struct pcib_softc * sc,int mask)217 pcib_write_windows(struct pcib_softc *sc, int mask)
218 {
219 	device_t dev;
220 	uint32_t val;
221 
222 	dev = sc->dev;
223 	if (sc->io.valid && mask & WIN_IO) {
224 		val = pci_read_config(dev, PCIR_IOBASEL_1, 1);
225 		if ((val & PCIM_BRIO_MASK) == PCIM_BRIO_32) {
226 			pci_write_config(dev, PCIR_IOBASEH_1,
227 			    sc->io.base >> 16, 2);
228 			pci_write_config(dev, PCIR_IOLIMITH_1,
229 			    sc->io.limit >> 16, 2);
230 		}
231 		pci_write_config(dev, PCIR_IOBASEL_1, sc->io.base >> 8, 1);
232 		pci_write_config(dev, PCIR_IOLIMITL_1, sc->io.limit >> 8, 1);
233 	}
234 
235 	if (mask & WIN_MEM) {
236 		pci_write_config(dev, PCIR_MEMBASE_1, sc->mem.base >> 16, 2);
237 		pci_write_config(dev, PCIR_MEMLIMIT_1, sc->mem.limit >> 16, 2);
238 	}
239 
240 	if (sc->pmem.valid && mask & WIN_PMEM) {
241 		val = pci_read_config(dev, PCIR_PMBASEL_1, 2);
242 		if ((val & PCIM_BRPM_MASK) == PCIM_BRPM_64) {
243 			pci_write_config(dev, PCIR_PMBASEH_1,
244 			    sc->pmem.base >> 32, 4);
245 			pci_write_config(dev, PCIR_PMLIMITH_1,
246 			    sc->pmem.limit >> 32, 4);
247 		}
248 		pci_write_config(dev, PCIR_PMBASEL_1, sc->pmem.base >> 16, 2);
249 		pci_write_config(dev, PCIR_PMLIMITL_1, sc->pmem.limit >> 16, 2);
250 	}
251 }
252 
253 /*
254  * This is used to reject I/O port allocations that conflict with an
255  * ISA alias range.
256  */
257 static int
pcib_is_isa_range(struct pcib_softc * sc,rman_res_t start,rman_res_t end,rman_res_t count)258 pcib_is_isa_range(struct pcib_softc *sc, rman_res_t start, rman_res_t end,
259     rman_res_t count)
260 {
261 	rman_res_t next_alias;
262 
263 	if (!(sc->bridgectl & PCIB_BCR_ISA_ENABLE))
264 		return (0);
265 
266 	/* Only check fixed ranges for overlap. */
267 	if (start + count - 1 != end)
268 		return (0);
269 
270 	/* ISA aliases are only in the lower 64KB of I/O space. */
271 	if (start >= 65536)
272 		return (0);
273 
274 	/* Check for overlap with 0x000 - 0x0ff as a special case. */
275 	if (start < 0x100)
276 		goto alias;
277 
278 	/*
279 	 * If the start address is an alias, the range is an alias.
280 	 * Otherwise, compute the start of the next alias range and
281 	 * check if it is before the end of the candidate range.
282 	 */
283 	if ((start & 0x300) != 0)
284 		goto alias;
285 	next_alias = (start & ~0x3fful) | 0x100;
286 	if (next_alias <= end)
287 		goto alias;
288 	return (0);
289 
290 alias:
291 	if (bootverbose)
292 		device_printf(sc->dev,
293 		    "I/O range %#jx-%#jx overlaps with an ISA alias\n", start,
294 		    end);
295 	return (1);
296 }
297 
298 static void
pcib_add_window_resources(struct pcib_window * w,struct resource ** res,int count)299 pcib_add_window_resources(struct pcib_window *w, struct resource **res,
300     int count)
301 {
302 	struct resource **newarray;
303 	int error, i;
304 
305 	newarray = malloc(sizeof(struct resource *) * (w->count + count),
306 	    M_DEVBUF, M_WAITOK);
307 	if (w->res != NULL)
308 		bcopy(w->res, newarray, sizeof(struct resource *) * w->count);
309 	bcopy(res, newarray + w->count, sizeof(struct resource *) * count);
310 	free(w->res, M_DEVBUF);
311 	w->res = newarray;
312 	w->count += count;
313 
314 	for (i = 0; i < count; i++) {
315 		error = rman_manage_region(&w->rman, rman_get_start(res[i]),
316 		    rman_get_end(res[i]));
317 		if (error)
318 			panic("Failed to add resource to rman");
319 	}
320 }
321 
322 typedef void (nonisa_callback)(rman_res_t start, rman_res_t end, void *arg);
323 
324 static void
pcib_walk_nonisa_ranges(rman_res_t start,rman_res_t end,nonisa_callback * cb,void * arg)325 pcib_walk_nonisa_ranges(rman_res_t start, rman_res_t end, nonisa_callback *cb,
326     void *arg)
327 {
328 	rman_res_t next_end;
329 
330 	/*
331 	 * If start is within an ISA alias range, move up to the start
332 	 * of the next non-alias range.  As a special case, addresses
333 	 * in the range 0x000 - 0x0ff should also be skipped since
334 	 * those are used for various system I/O devices in ISA
335 	 * systems.
336 	 */
337 	if (start <= 65535) {
338 		if (start < 0x100 || (start & 0x300) != 0) {
339 			start &= ~0x3ff;
340 			start += 0x400;
341 		}
342 	}
343 
344 	/* ISA aliases are only in the lower 64KB of I/O space. */
345 	while (start <= MIN(end, 65535)) {
346 		next_end = MIN(start | 0xff, end);
347 		cb(start, next_end, arg);
348 		start += 0x400;
349 	}
350 
351 	if (start <= end)
352 		cb(start, end, arg);
353 }
354 
355 static void
count_ranges(rman_res_t start,rman_res_t end,void * arg)356 count_ranges(rman_res_t start, rman_res_t end, void *arg)
357 {
358 	int *countp;
359 
360 	countp = arg;
361 	(*countp)++;
362 }
363 
364 struct alloc_state {
365 	struct resource **res;
366 	struct pcib_softc *sc;
367 	int count, error;
368 };
369 
370 static void
alloc_ranges(rman_res_t start,rman_res_t end,void * arg)371 alloc_ranges(rman_res_t start, rman_res_t end, void *arg)
372 {
373 	struct alloc_state *as;
374 	struct pcib_window *w;
375 	int rid;
376 
377 	as = arg;
378 	if (as->error != 0)
379 		return;
380 
381 	w = &as->sc->io;
382 	rid = w->reg;
383 	if (bootverbose)
384 		device_printf(as->sc->dev,
385 		    "allocating non-ISA range %#jx-%#jx\n", start, end);
386 	as->res[as->count] = bus_alloc_resource(as->sc->dev, SYS_RES_IOPORT,
387 	    &rid, start, end, end - start + 1, 0);
388 	if (as->res[as->count] == NULL)
389 		as->error = ENXIO;
390 	else
391 		as->count++;
392 }
393 
394 static int
pcib_alloc_nonisa_ranges(struct pcib_softc * sc,rman_res_t start,rman_res_t end)395 pcib_alloc_nonisa_ranges(struct pcib_softc *sc, rman_res_t start, rman_res_t end)
396 {
397 	struct alloc_state as;
398 	int i, new_count;
399 
400 	/* First, see how many ranges we need. */
401 	new_count = 0;
402 	pcib_walk_nonisa_ranges(start, end, count_ranges, &new_count);
403 
404 	/* Second, allocate the ranges. */
405 	as.res = malloc(sizeof(struct resource *) * new_count, M_DEVBUF,
406 	    M_WAITOK);
407 	as.sc = sc;
408 	as.count = 0;
409 	as.error = 0;
410 	pcib_walk_nonisa_ranges(start, end, alloc_ranges, &as);
411 	if (as.error != 0) {
412 		for (i = 0; i < as.count; i++)
413 			bus_release_resource(sc->dev, SYS_RES_IOPORT,
414 			    sc->io.reg, as.res[i]);
415 		free(as.res, M_DEVBUF);
416 		return (as.error);
417 	}
418 	KASSERT(as.count == new_count, ("%s: count mismatch", __func__));
419 
420 	/* Third, add the ranges to the window. */
421 	pcib_add_window_resources(&sc->io, as.res, as.count);
422 	free(as.res, M_DEVBUF);
423 	return (0);
424 }
425 
426 static void
pcib_alloc_window(struct pcib_softc * sc,struct pcib_window * w,int type,int flags,pci_addr_t max_address)427 pcib_alloc_window(struct pcib_softc *sc, struct pcib_window *w, int type,
428     int flags, pci_addr_t max_address)
429 {
430 	struct resource *res;
431 	char buf[64];
432 	int error, rid;
433 
434 	if (max_address != (rman_res_t)max_address)
435 		max_address = ~0;
436 	w->rman.rm_start = 0;
437 	w->rman.rm_end = max_address;
438 	w->rman.rm_type = RMAN_ARRAY;
439 	snprintf(buf, sizeof(buf), "%s %s window",
440 	    device_get_nameunit(sc->dev), w->name);
441 	w->rman.rm_descr = strdup(buf, M_DEVBUF);
442 	error = rman_init(&w->rman);
443 	if (error)
444 		panic("Failed to initialize %s %s rman",
445 		    device_get_nameunit(sc->dev), w->name);
446 
447 	if (!pcib_is_window_open(w))
448 		return;
449 
450 	if (w->base > max_address || w->limit > max_address) {
451 		device_printf(sc->dev,
452 		    "initial %s window has too many bits, ignoring\n", w->name);
453 		return;
454 	}
455 	if (type == SYS_RES_IOPORT && sc->bridgectl & PCIB_BCR_ISA_ENABLE)
456 		(void)pcib_alloc_nonisa_ranges(sc, w->base, w->limit);
457 	else {
458 		rid = w->reg;
459 		res = bus_alloc_resource(sc->dev, type, &rid, w->base, w->limit,
460 		    w->limit - w->base + 1, flags);
461 		if (res != NULL)
462 			pcib_add_window_resources(w, &res, 1);
463 	}
464 	if (w->res == NULL) {
465 		device_printf(sc->dev,
466 		    "failed to allocate initial %s window: %#jx-%#jx\n",
467 		    w->name, (uintmax_t)w->base, (uintmax_t)w->limit);
468 		w->base = max_address;
469 		w->limit = 0;
470 		pcib_write_windows(sc, w->mask);
471 		return;
472 	}
473 	pcib_activate_window(sc, type);
474 }
475 
476 /*
477  * Initialize I/O windows.
478  */
479 static void
pcib_probe_windows(struct pcib_softc * sc)480 pcib_probe_windows(struct pcib_softc *sc)
481 {
482 	pci_addr_t max;
483 	device_t dev;
484 	uint32_t val;
485 
486 	dev = sc->dev;
487 
488 	if (pci_clear_pcib) {
489 		pcib_bridge_init(dev);
490 	}
491 
492 	/* Determine if the I/O port window is implemented. */
493 	val = pci_read_config(dev, PCIR_IOBASEL_1, 1);
494 	if (val == 0) {
495 		/*
496 		 * If 'val' is zero, then only 16-bits of I/O space
497 		 * are supported.
498 		 */
499 		pci_write_config(dev, PCIR_IOBASEL_1, 0xff, 1);
500 		if (pci_read_config(dev, PCIR_IOBASEL_1, 1) != 0) {
501 			sc->io.valid = 1;
502 			pci_write_config(dev, PCIR_IOBASEL_1, 0, 1);
503 		}
504 	} else
505 		sc->io.valid = 1;
506 
507 	/* Read the existing I/O port window. */
508 	if (sc->io.valid) {
509 		sc->io.reg = PCIR_IOBASEL_1;
510 		sc->io.step = 12;
511 		sc->io.mask = WIN_IO;
512 		sc->io.name = "I/O port";
513 		if ((val & PCIM_BRIO_MASK) == PCIM_BRIO_32) {
514 			sc->io.base = PCI_PPBIOBASE(
515 			    pci_read_config(dev, PCIR_IOBASEH_1, 2), val);
516 			sc->io.limit = PCI_PPBIOLIMIT(
517 			    pci_read_config(dev, PCIR_IOLIMITH_1, 2),
518 			    pci_read_config(dev, PCIR_IOLIMITL_1, 1));
519 			max = 0xffffffff;
520 		} else {
521 			sc->io.base = PCI_PPBIOBASE(0, val);
522 			sc->io.limit = PCI_PPBIOLIMIT(0,
523 			    pci_read_config(dev, PCIR_IOLIMITL_1, 1));
524 			max = 0xffff;
525 		}
526 		pcib_alloc_window(sc, &sc->io, SYS_RES_IOPORT, 0, max);
527 	}
528 
529 	/* Read the existing memory window. */
530 	sc->mem.valid = 1;
531 	sc->mem.reg = PCIR_MEMBASE_1;
532 	sc->mem.step = 20;
533 	sc->mem.mask = WIN_MEM;
534 	sc->mem.name = "memory";
535 	sc->mem.base = PCI_PPBMEMBASE(0,
536 	    pci_read_config(dev, PCIR_MEMBASE_1, 2));
537 	sc->mem.limit = PCI_PPBMEMLIMIT(0,
538 	    pci_read_config(dev, PCIR_MEMLIMIT_1, 2));
539 	pcib_alloc_window(sc, &sc->mem, SYS_RES_MEMORY, 0, 0xffffffff);
540 
541 	/* Determine if the prefetchable memory window is implemented. */
542 	val = pci_read_config(dev, PCIR_PMBASEL_1, 2);
543 	if (val == 0) {
544 		/*
545 		 * If 'val' is zero, then only 32-bits of memory space
546 		 * are supported.
547 		 */
548 		pci_write_config(dev, PCIR_PMBASEL_1, 0xffff, 2);
549 		if (pci_read_config(dev, PCIR_PMBASEL_1, 2) != 0) {
550 			sc->pmem.valid = 1;
551 			pci_write_config(dev, PCIR_PMBASEL_1, 0, 2);
552 		}
553 	} else
554 		sc->pmem.valid = 1;
555 
556 	/* Read the existing prefetchable memory window. */
557 	if (sc->pmem.valid) {
558 		sc->pmem.reg = PCIR_PMBASEL_1;
559 		sc->pmem.step = 20;
560 		sc->pmem.mask = WIN_PMEM;
561 		sc->pmem.name = "prefetch";
562 		if ((val & PCIM_BRPM_MASK) == PCIM_BRPM_64) {
563 			sc->pmem.base = PCI_PPBMEMBASE(
564 			    pci_read_config(dev, PCIR_PMBASEH_1, 4), val);
565 			sc->pmem.limit = PCI_PPBMEMLIMIT(
566 			    pci_read_config(dev, PCIR_PMLIMITH_1, 4),
567 			    pci_read_config(dev, PCIR_PMLIMITL_1, 2));
568 			max = 0xffffffffffffffff;
569 		} else {
570 			sc->pmem.base = PCI_PPBMEMBASE(0, val);
571 			sc->pmem.limit = PCI_PPBMEMLIMIT(0,
572 			    pci_read_config(dev, PCIR_PMLIMITL_1, 2));
573 			max = 0xffffffff;
574 		}
575 		pcib_alloc_window(sc, &sc->pmem, SYS_RES_MEMORY,
576 		    RF_PREFETCHABLE, max);
577 	}
578 }
579 
580 static void
pcib_release_window(struct pcib_softc * sc,struct pcib_window * w,int type)581 pcib_release_window(struct pcib_softc *sc, struct pcib_window *w, int type)
582 {
583 	device_t dev;
584 	int error, i;
585 
586 	if (!w->valid)
587 		return;
588 
589 	dev = sc->dev;
590 	error = rman_fini(&w->rman);
591 	if (error) {
592 		device_printf(dev, "failed to release %s rman\n", w->name);
593 		return;
594 	}
595 	free(__DECONST(char *, w->rman.rm_descr), M_DEVBUF);
596 
597 	for (i = 0; i < w->count; i++) {
598 		error = bus_free_resource(dev, type, w->res[i]);
599 		if (error)
600 			device_printf(dev,
601 			    "failed to release %s resource: %d\n", w->name,
602 			    error);
603 	}
604 	free(w->res, M_DEVBUF);
605 }
606 
607 static void
pcib_free_windows(struct pcib_softc * sc)608 pcib_free_windows(struct pcib_softc *sc)
609 {
610 
611 	pcib_release_window(sc, &sc->pmem, SYS_RES_MEMORY);
612 	pcib_release_window(sc, &sc->mem, SYS_RES_MEMORY);
613 	pcib_release_window(sc, &sc->io, SYS_RES_IOPORT);
614 }
615 
616 #ifdef PCI_RES_BUS
617 /*
618  * Allocate a suitable secondary bus for this bridge if needed and
619  * initialize the resource manager for the secondary bus range.  Note
620  * that the minimum count is a desired value and this may allocate a
621  * smaller range.
622  */
623 void
pcib_setup_secbus(device_t dev,struct pcib_secbus * bus,int min_count)624 pcib_setup_secbus(device_t dev, struct pcib_secbus *bus, int min_count)
625 {
626 	char buf[64];
627 	int error, rid, sec_reg;
628 
629 	switch (pci_read_config(dev, PCIR_HDRTYPE, 1) & PCIM_HDRTYPE) {
630 	case PCIM_HDRTYPE_BRIDGE:
631 		sec_reg = PCIR_SECBUS_1;
632 		bus->sub_reg = PCIR_SUBBUS_1;
633 		break;
634 	case PCIM_HDRTYPE_CARDBUS:
635 		sec_reg = PCIR_SECBUS_2;
636 		bus->sub_reg = PCIR_SUBBUS_2;
637 		break;
638 	default:
639 		panic("not a PCI bridge");
640 	}
641 	bus->sec = pci_read_config(dev, sec_reg, 1);
642 	bus->sub = pci_read_config(dev, bus->sub_reg, 1);
643 	bus->dev = dev;
644 	bus->rman.rm_start = 0;
645 	bus->rman.rm_end = PCI_BUSMAX;
646 	bus->rman.rm_type = RMAN_ARRAY;
647 	snprintf(buf, sizeof(buf), "%s bus numbers", device_get_nameunit(dev));
648 	bus->rman.rm_descr = strdup(buf, M_DEVBUF);
649 	error = rman_init(&bus->rman);
650 	if (error)
651 		panic("Failed to initialize %s bus number rman",
652 		    device_get_nameunit(dev));
653 
654 	/*
655 	 * Allocate a bus range.  This will return an existing bus range
656 	 * if one exists, or a new bus range if one does not.
657 	 */
658 	rid = 0;
659 	bus->res = bus_alloc_resource_anywhere(dev, PCI_RES_BUS, &rid,
660 	    min_count, 0);
661 	if (bus->res == NULL) {
662 		/*
663 		 * Fall back to just allocating a range of a single bus
664 		 * number.
665 		 */
666 		bus->res = bus_alloc_resource_anywhere(dev, PCI_RES_BUS, &rid,
667 		    1, 0);
668 	} else if (rman_get_size(bus->res) < min_count)
669 		/*
670 		 * Attempt to grow the existing range to satisfy the
671 		 * minimum desired count.
672 		 */
673 		(void)bus_adjust_resource(dev, PCI_RES_BUS, bus->res,
674 		    rman_get_start(bus->res), rman_get_start(bus->res) +
675 		    min_count - 1);
676 
677 	/*
678 	 * Add the initial resource to the rman.
679 	 */
680 	if (bus->res != NULL) {
681 		error = rman_manage_region(&bus->rman, rman_get_start(bus->res),
682 		    rman_get_end(bus->res));
683 		if (error)
684 			panic("Failed to add resource to rman");
685 		bus->sec = rman_get_start(bus->res);
686 		bus->sub = rman_get_end(bus->res);
687 	}
688 }
689 
690 void
pcib_free_secbus(device_t dev,struct pcib_secbus * bus)691 pcib_free_secbus(device_t dev, struct pcib_secbus *bus)
692 {
693 	int error;
694 
695 	error = rman_fini(&bus->rman);
696 	if (error) {
697 		device_printf(dev, "failed to release bus number rman\n");
698 		return;
699 	}
700 	free(__DECONST(char *, bus->rman.rm_descr), M_DEVBUF);
701 
702 	error = bus_free_resource(dev, PCI_RES_BUS, bus->res);
703 	if (error)
704 		device_printf(dev,
705 		    "failed to release bus numbers resource: %d\n", error);
706 }
707 
708 static struct resource *
pcib_suballoc_bus(struct pcib_secbus * bus,device_t child,int * rid,rman_res_t start,rman_res_t end,rman_res_t count,u_int flags)709 pcib_suballoc_bus(struct pcib_secbus *bus, device_t child, int *rid,
710     rman_res_t start, rman_res_t end, rman_res_t count, u_int flags)
711 {
712 	struct resource *res;
713 
714 	res = rman_reserve_resource(&bus->rman, start, end, count, flags,
715 	    child);
716 	if (res == NULL)
717 		return (NULL);
718 
719 	if (bootverbose)
720 		device_printf(bus->dev,
721 		    "allocated bus range (%ju-%ju) for rid %d of %s\n",
722 		    rman_get_start(res), rman_get_end(res), *rid,
723 		    pcib_child_name(child));
724 	rman_set_rid(res, *rid);
725 	return (res);
726 }
727 
728 /*
729  * Attempt to grow the secondary bus range.  This is much simpler than
730  * for I/O windows as the range can only be grown by increasing
731  * subbus.
732  */
733 static int
pcib_grow_subbus(struct pcib_secbus * bus,rman_res_t new_end)734 pcib_grow_subbus(struct pcib_secbus *bus, rman_res_t new_end)
735 {
736 	rman_res_t old_end;
737 	int error;
738 
739 	old_end = rman_get_end(bus->res);
740 	KASSERT(new_end > old_end, ("attempt to shrink subbus"));
741 	error = bus_adjust_resource(bus->dev, PCI_RES_BUS, bus->res,
742 	    rman_get_start(bus->res), new_end);
743 	if (error)
744 		return (error);
745 	if (bootverbose)
746 		device_printf(bus->dev, "grew bus range to %ju-%ju\n",
747 		    rman_get_start(bus->res), rman_get_end(bus->res));
748 	error = rman_manage_region(&bus->rman, old_end + 1,
749 	    rman_get_end(bus->res));
750 	if (error)
751 		panic("Failed to add resource to rman");
752 	bus->sub = rman_get_end(bus->res);
753 	pci_write_config(bus->dev, bus->sub_reg, bus->sub, 1);
754 	return (0);
755 }
756 
757 struct resource *
pcib_alloc_subbus(struct pcib_secbus * bus,device_t child,int * rid,rman_res_t start,rman_res_t end,rman_res_t count,u_int flags)758 pcib_alloc_subbus(struct pcib_secbus *bus, device_t child, int *rid,
759     rman_res_t start, rman_res_t end, rman_res_t count, u_int flags)
760 {
761 	struct resource *res;
762 	rman_res_t start_free, end_free, new_end;
763 
764 	/*
765 	 * First, see if the request can be satisified by the existing
766 	 * bus range.
767 	 */
768 	res = pcib_suballoc_bus(bus, child, rid, start, end, count, flags);
769 	if (res != NULL)
770 		return (res);
771 
772 	/*
773 	 * Figure out a range to grow the bus range.  First, find the
774 	 * first bus number after the last allocated bus in the rman and
775 	 * enforce that as a minimum starting point for the range.
776 	 */
777 	if (rman_last_free_region(&bus->rman, &start_free, &end_free) != 0 ||
778 	    end_free != bus->sub)
779 		start_free = bus->sub + 1;
780 	if (start_free < start)
781 		start_free = start;
782 	new_end = start_free + count - 1;
783 
784 	/*
785 	 * See if this new range would satisfy the request if it
786 	 * succeeds.
787 	 */
788 	if (new_end > end)
789 		return (NULL);
790 
791 	/* Finally, attempt to grow the existing resource. */
792 	if (bootverbose) {
793 		device_printf(bus->dev,
794 		    "attempting to grow bus range for %ju buses\n", count);
795 		printf("\tback candidate range: %ju-%ju\n", start_free,
796 		    new_end);
797 	}
798 	if (pcib_grow_subbus(bus, new_end) == 0)
799 		return (pcib_suballoc_bus(bus, child, rid, start, end, count,
800 		    flags));
801 	return (NULL);
802 }
803 #endif
804 
805 #else
806 
807 /*
808  * Is the prefetch window open (eg, can we allocate memory in it?)
809  */
810 static int
pcib_is_prefetch_open(struct pcib_softc * sc)811 pcib_is_prefetch_open(struct pcib_softc *sc)
812 {
813 	return (sc->pmembase > 0 && sc->pmembase < sc->pmemlimit);
814 }
815 
816 /*
817  * Is the nonprefetch window open (eg, can we allocate memory in it?)
818  */
819 static int
pcib_is_nonprefetch_open(struct pcib_softc * sc)820 pcib_is_nonprefetch_open(struct pcib_softc *sc)
821 {
822 	return (sc->membase > 0 && sc->membase < sc->memlimit);
823 }
824 
825 /*
826  * Is the io window open (eg, can we allocate ports in it?)
827  */
828 static int
pcib_is_io_open(struct pcib_softc * sc)829 pcib_is_io_open(struct pcib_softc *sc)
830 {
831 	return (sc->iobase > 0 && sc->iobase < sc->iolimit);
832 }
833 
834 /*
835  * Get current I/O decode.
836  */
837 static void
pcib_get_io_decode(struct pcib_softc * sc)838 pcib_get_io_decode(struct pcib_softc *sc)
839 {
840 	device_t	dev;
841 	uint32_t	iolow;
842 
843 	dev = sc->dev;
844 
845 	iolow = pci_read_config(dev, PCIR_IOBASEL_1, 1);
846 	if ((iolow & PCIM_BRIO_MASK) == PCIM_BRIO_32)
847 		sc->iobase = PCI_PPBIOBASE(
848 		    pci_read_config(dev, PCIR_IOBASEH_1, 2), iolow);
849 	else
850 		sc->iobase = PCI_PPBIOBASE(0, iolow);
851 
852 	iolow = pci_read_config(dev, PCIR_IOLIMITL_1, 1);
853 	if ((iolow & PCIM_BRIO_MASK) == PCIM_BRIO_32)
854 		sc->iolimit = PCI_PPBIOLIMIT(
855 		    pci_read_config(dev, PCIR_IOLIMITH_1, 2), iolow);
856 	else
857 		sc->iolimit = PCI_PPBIOLIMIT(0, iolow);
858 }
859 
860 /*
861  * Get current memory decode.
862  */
863 static void
pcib_get_mem_decode(struct pcib_softc * sc)864 pcib_get_mem_decode(struct pcib_softc *sc)
865 {
866 	device_t	dev;
867 	pci_addr_t	pmemlow;
868 
869 	dev = sc->dev;
870 
871 	sc->membase = PCI_PPBMEMBASE(0,
872 	    pci_read_config(dev, PCIR_MEMBASE_1, 2));
873 	sc->memlimit = PCI_PPBMEMLIMIT(0,
874 	    pci_read_config(dev, PCIR_MEMLIMIT_1, 2));
875 
876 	pmemlow = pci_read_config(dev, PCIR_PMBASEL_1, 2);
877 	if ((pmemlow & PCIM_BRPM_MASK) == PCIM_BRPM_64)
878 		sc->pmembase = PCI_PPBMEMBASE(
879 		    pci_read_config(dev, PCIR_PMBASEH_1, 4), pmemlow);
880 	else
881 		sc->pmembase = PCI_PPBMEMBASE(0, pmemlow);
882 
883 	pmemlow = pci_read_config(dev, PCIR_PMLIMITL_1, 2);
884 	if ((pmemlow & PCIM_BRPM_MASK) == PCIM_BRPM_64)
885 		sc->pmemlimit = PCI_PPBMEMLIMIT(
886 		    pci_read_config(dev, PCIR_PMLIMITH_1, 4), pmemlow);
887 	else
888 		sc->pmemlimit = PCI_PPBMEMLIMIT(0, pmemlow);
889 }
890 
891 /*
892  * Restore previous I/O decode.
893  */
894 static void
pcib_set_io_decode(struct pcib_softc * sc)895 pcib_set_io_decode(struct pcib_softc *sc)
896 {
897 	device_t	dev;
898 	uint32_t	iohi;
899 
900 	dev = sc->dev;
901 
902 	iohi = sc->iobase >> 16;
903 	if (iohi > 0)
904 		pci_write_config(dev, PCIR_IOBASEH_1, iohi, 2);
905 	pci_write_config(dev, PCIR_IOBASEL_1, sc->iobase >> 8, 1);
906 
907 	iohi = sc->iolimit >> 16;
908 	if (iohi > 0)
909 		pci_write_config(dev, PCIR_IOLIMITH_1, iohi, 2);
910 	pci_write_config(dev, PCIR_IOLIMITL_1, sc->iolimit >> 8, 1);
911 }
912 
913 /*
914  * Restore previous memory decode.
915  */
916 static void
pcib_set_mem_decode(struct pcib_softc * sc)917 pcib_set_mem_decode(struct pcib_softc *sc)
918 {
919 	device_t	dev;
920 	pci_addr_t	pmemhi;
921 
922 	dev = sc->dev;
923 
924 	pci_write_config(dev, PCIR_MEMBASE_1, sc->membase >> 16, 2);
925 	pci_write_config(dev, PCIR_MEMLIMIT_1, sc->memlimit >> 16, 2);
926 
927 	pmemhi = sc->pmembase >> 32;
928 	if (pmemhi > 0)
929 		pci_write_config(dev, PCIR_PMBASEH_1, pmemhi, 4);
930 	pci_write_config(dev, PCIR_PMBASEL_1, sc->pmembase >> 16, 2);
931 
932 	pmemhi = sc->pmemlimit >> 32;
933 	if (pmemhi > 0)
934 		pci_write_config(dev, PCIR_PMLIMITH_1, pmemhi, 4);
935 	pci_write_config(dev, PCIR_PMLIMITL_1, sc->pmemlimit >> 16, 2);
936 }
937 #endif
938 
939 #ifdef PCI_HP
940 /*
941  * PCI-express HotPlug support.
942  */
943 static int pci_enable_pcie_hp = 1;
944 SYSCTL_INT(_hw_pci, OID_AUTO, enable_pcie_hp, CTLFLAG_RDTUN,
945     &pci_enable_pcie_hp, 0,
946     "Enable support for native PCI-express HotPlug.");
947 
948 TASKQUEUE_DEFINE_THREAD(pci_hp);
949 
950 static void
pcib_probe_hotplug(struct pcib_softc * sc)951 pcib_probe_hotplug(struct pcib_softc *sc)
952 {
953 	device_t dev;
954 	uint32_t link_cap;
955 	uint16_t link_sta, slot_sta;
956 
957 	if (!pci_enable_pcie_hp)
958 		return;
959 
960 	dev = sc->dev;
961 	if (pci_find_cap(dev, PCIY_EXPRESS, NULL) != 0)
962 		return;
963 
964 	if (!(pcie_read_config(dev, PCIER_FLAGS, 2) & PCIEM_FLAGS_SLOT))
965 		return;
966 
967 	sc->pcie_slot_cap = pcie_read_config(dev, PCIER_SLOT_CAP, 4);
968 
969 	if ((sc->pcie_slot_cap & PCIEM_SLOT_CAP_HPC) == 0)
970 		return;
971 	link_cap = pcie_read_config(dev, PCIER_LINK_CAP, 4);
972 	if ((link_cap & PCIEM_LINK_CAP_DL_ACTIVE) == 0)
973 		return;
974 
975 	/*
976 	 * Some devices report that they have an MRL when they actually
977 	 * do not.  Since they always report that the MRL is open, child
978 	 * devices would be ignored.  Try to detect these devices and
979 	 * ignore their claim of HotPlug support.
980 	 *
981 	 * If there is an open MRL but the Data Link Layer is active,
982 	 * the MRL is not real.
983 	 */
984 	if ((sc->pcie_slot_cap & PCIEM_SLOT_CAP_MRLSP) != 0) {
985 		link_sta = pcie_read_config(dev, PCIER_LINK_STA, 2);
986 		slot_sta = pcie_read_config(dev, PCIER_SLOT_STA, 2);
987 		if ((slot_sta & PCIEM_SLOT_STA_MRLSS) != 0 &&
988 		    (link_sta & PCIEM_LINK_STA_DL_ACTIVE) != 0) {
989 			return;
990 		}
991 	}
992 
993 	/*
994 	 * Now that we're sure we want to do hot plug, ask the
995 	 * firmware, if any, if that's OK.
996 	 */
997 	if (pcib_request_feature(dev, PCI_FEATURE_HP) != 0) {
998 		if (bootverbose)
999 			device_printf(dev, "Unable to activate hot plug feature.\n");
1000 		return;
1001 	}
1002 
1003 	sc->flags |= PCIB_HOTPLUG;
1004 }
1005 
1006 /*
1007  * Send a HotPlug command to the slot control register.  If this slot
1008  * uses command completion interrupts and a previous command is still
1009  * in progress, then the command is dropped.  Once the previous
1010  * command completes or times out, pcib_pcie_hotplug_update() will be
1011  * invoked to post a new command based on the slot's state at that
1012  * time.
1013  */
1014 static void
pcib_pcie_hotplug_command(struct pcib_softc * sc,uint16_t val,uint16_t mask)1015 pcib_pcie_hotplug_command(struct pcib_softc *sc, uint16_t val, uint16_t mask)
1016 {
1017 	device_t dev;
1018 	uint16_t ctl, new;
1019 
1020 	dev = sc->dev;
1021 
1022 	if (sc->flags & PCIB_HOTPLUG_CMD_PENDING)
1023 		return;
1024 
1025 	ctl = pcie_read_config(dev, PCIER_SLOT_CTL, 2);
1026 	new = (ctl & ~mask) | val;
1027 	if (new == ctl)
1028 		return;
1029 	if (bootverbose)
1030 		device_printf(dev, "HotPlug command: %04x -> %04x\n", ctl, new);
1031 	pcie_write_config(dev, PCIER_SLOT_CTL, new, 2);
1032 	if (!(sc->pcie_slot_cap & PCIEM_SLOT_CAP_NCCS) &&
1033 	    (ctl & new) & PCIEM_SLOT_CTL_CCIE) {
1034 		sc->flags |= PCIB_HOTPLUG_CMD_PENDING;
1035 		if (!cold)
1036 			taskqueue_enqueue_timeout(taskqueue_pci_hp,
1037 			    &sc->pcie_cc_task, hz);
1038 	}
1039 }
1040 
1041 static void
pcib_pcie_hotplug_command_completed(struct pcib_softc * sc)1042 pcib_pcie_hotplug_command_completed(struct pcib_softc *sc)
1043 {
1044 	device_t dev;
1045 
1046 	dev = sc->dev;
1047 
1048 	if (bootverbose)
1049 		device_printf(dev, "Command Completed\n");
1050 	if (!(sc->flags & PCIB_HOTPLUG_CMD_PENDING))
1051 		return;
1052 	taskqueue_cancel_timeout(taskqueue_pci_hp, &sc->pcie_cc_task, NULL);
1053 	sc->flags &= ~PCIB_HOTPLUG_CMD_PENDING;
1054 	wakeup(sc);
1055 }
1056 
1057 /*
1058  * Returns true if a card is fully inserted from the user's
1059  * perspective.  It may not yet be ready for access, but the driver
1060  * can now start enabling access if necessary.
1061  */
1062 static bool
pcib_hotplug_inserted(struct pcib_softc * sc)1063 pcib_hotplug_inserted(struct pcib_softc *sc)
1064 {
1065 
1066 	/* Pretend the card isn't present if a detach is forced. */
1067 	if (sc->flags & PCIB_DETACHING)
1068 		return (false);
1069 
1070 	/* Card must be present in the slot. */
1071 	if ((sc->pcie_slot_sta & PCIEM_SLOT_STA_PDS) == 0)
1072 		return (false);
1073 
1074 	/* A power fault implicitly turns off power to the slot. */
1075 	if (sc->pcie_slot_cap & PCIEM_SLOT_CAP_PCP &&
1076 	    sc->pcie_slot_sta & PCIEM_SLOT_STA_PFD)
1077 		return (false);
1078 
1079 	/* If the MRL is disengaged, the slot is powered off. */
1080 	if (sc->pcie_slot_cap & PCIEM_SLOT_CAP_MRLSP &&
1081 	    (sc->pcie_slot_sta & PCIEM_SLOT_STA_MRLSS) != 0)
1082 		return (false);
1083 
1084 	return (true);
1085 }
1086 
1087 /*
1088  * Returns -1 if the card is fully inserted, powered, and ready for
1089  * access.  Otherwise, returns 0.
1090  */
1091 static int
pcib_hotplug_present(struct pcib_softc * sc)1092 pcib_hotplug_present(struct pcib_softc *sc)
1093 {
1094 
1095 	/* Card must be inserted. */
1096 	if (!pcib_hotplug_inserted(sc))
1097 		return (0);
1098 
1099 	/* Require the Data Link Layer to be active. */
1100 	if (!(sc->pcie_link_sta & PCIEM_LINK_STA_DL_ACTIVE))
1101 		return (0);
1102 
1103 	return (-1);
1104 }
1105 
1106 static int pci_enable_pcie_ei = 0;
1107 SYSCTL_INT(_hw_pci, OID_AUTO, enable_pcie_ei, CTLFLAG_RWTUN,
1108     &pci_enable_pcie_ei, 0,
1109     "Enable support for PCI-express Electromechanical Interlock.");
1110 
1111 static void
pcib_pcie_hotplug_update(struct pcib_softc * sc,uint16_t val,uint16_t mask,bool schedule_task)1112 pcib_pcie_hotplug_update(struct pcib_softc *sc, uint16_t val, uint16_t mask,
1113     bool schedule_task)
1114 {
1115 	bool card_inserted, ei_engaged;
1116 
1117 	/* Clear DETACHING if Presence Detect has cleared. */
1118 	if ((sc->pcie_slot_sta & (PCIEM_SLOT_STA_PDC | PCIEM_SLOT_STA_PDS)) ==
1119 	    PCIEM_SLOT_STA_PDC)
1120 		sc->flags &= ~PCIB_DETACHING;
1121 
1122 	card_inserted = pcib_hotplug_inserted(sc);
1123 
1124 	/* Turn the power indicator on if a card is inserted. */
1125 	if (sc->pcie_slot_cap & PCIEM_SLOT_CAP_PIP) {
1126 		mask |= PCIEM_SLOT_CTL_PIC;
1127 		if (card_inserted)
1128 			val |= PCIEM_SLOT_CTL_PI_ON;
1129 		else if (sc->flags & PCIB_DETACH_PENDING)
1130 			val |= PCIEM_SLOT_CTL_PI_BLINK;
1131 		else
1132 			val |= PCIEM_SLOT_CTL_PI_OFF;
1133 	}
1134 
1135 	/* Turn the power on via the Power Controller if a card is inserted. */
1136 	if (sc->pcie_slot_cap & PCIEM_SLOT_CAP_PCP) {
1137 		mask |= PCIEM_SLOT_CTL_PCC;
1138 		if (card_inserted)
1139 			val |= PCIEM_SLOT_CTL_PC_ON;
1140 		else
1141 			val |= PCIEM_SLOT_CTL_PC_OFF;
1142 	}
1143 
1144 	/*
1145 	 * If a card is inserted, enable the Electromechanical
1146 	 * Interlock.  If a card is not inserted (or we are in the
1147 	 * process of detaching), disable the Electromechanical
1148 	 * Interlock.
1149 	 */
1150 	if ((sc->pcie_slot_cap & PCIEM_SLOT_CAP_EIP) &&
1151 	    pci_enable_pcie_ei) {
1152 		mask |= PCIEM_SLOT_CTL_EIC;
1153 		ei_engaged = (sc->pcie_slot_sta & PCIEM_SLOT_STA_EIS) != 0;
1154 		if (card_inserted != ei_engaged)
1155 			val |= PCIEM_SLOT_CTL_EIC;
1156 	}
1157 
1158 	/*
1159 	 * Start a timer to see if the Data Link Layer times out.
1160 	 * Note that we only start the timer if Presence Detect or MRL Sensor
1161 	 * changed on this interrupt.  Stop any scheduled timer if
1162 	 * the Data Link Layer is active.
1163 	 */
1164 	if (card_inserted &&
1165 	    !(sc->pcie_link_sta & PCIEM_LINK_STA_DL_ACTIVE) &&
1166 	    sc->pcie_slot_sta &
1167 	    (PCIEM_SLOT_STA_MRLSC | PCIEM_SLOT_STA_PDC)) {
1168 		if (cold)
1169 			device_printf(sc->dev,
1170 			    "Data Link Layer inactive\n");
1171 		else
1172 			taskqueue_enqueue_timeout(taskqueue_pci_hp,
1173 			    &sc->pcie_dll_task, hz);
1174 	} else if (sc->pcie_link_sta & PCIEM_LINK_STA_DL_ACTIVE)
1175 		taskqueue_cancel_timeout(taskqueue_pci_hp, &sc->pcie_dll_task,
1176 		    NULL);
1177 
1178 	pcib_pcie_hotplug_command(sc, val, mask);
1179 
1180 	/*
1181 	 * During attach the child "pci" device is added synchronously;
1182 	 * otherwise, the task is scheduled to manage the child
1183 	 * device.
1184 	 */
1185 	if (schedule_task &&
1186 	    (pcib_hotplug_present(sc) != 0) != (sc->child != NULL))
1187 		taskqueue_enqueue(taskqueue_pci_hp, &sc->pcie_hp_task);
1188 }
1189 
1190 static void
pcib_pcie_intr_hotplug(void * arg)1191 pcib_pcie_intr_hotplug(void *arg)
1192 {
1193 	struct pcib_softc *sc;
1194 	device_t dev;
1195 	uint16_t old_slot_sta;
1196 
1197 	sc = arg;
1198 	dev = sc->dev;
1199 	PCIB_HP_LOCK(sc);
1200 	old_slot_sta = sc->pcie_slot_sta;
1201 	sc->pcie_slot_sta = pcie_read_config(dev, PCIER_SLOT_STA, 2);
1202 
1203 	/* Clear the events just reported. */
1204 	pcie_write_config(dev, PCIER_SLOT_STA, sc->pcie_slot_sta, 2);
1205 
1206 	if (bootverbose)
1207 		device_printf(dev, "HotPlug interrupt: %#x\n",
1208 		    sc->pcie_slot_sta);
1209 
1210 	if (sc->pcie_slot_sta & PCIEM_SLOT_STA_ABP) {
1211 		if (sc->flags & PCIB_DETACH_PENDING) {
1212 			device_printf(dev,
1213 			    "Attention Button Pressed: Detach Cancelled\n");
1214 			sc->flags &= ~PCIB_DETACH_PENDING;
1215 			taskqueue_cancel_timeout(taskqueue_pci_hp,
1216 			    &sc->pcie_ab_task, NULL);
1217 		} else if (old_slot_sta & PCIEM_SLOT_STA_PDS) {
1218 			/* Only initiate detach sequence if device present. */
1219 			device_printf(dev,
1220 		    "Attention Button Pressed: Detaching in 5 seconds\n");
1221 			sc->flags |= PCIB_DETACH_PENDING;
1222 			taskqueue_enqueue_timeout(taskqueue_pci_hp,
1223 			    &sc->pcie_ab_task, 5 * hz);
1224 		}
1225 	}
1226 	if (sc->pcie_slot_sta & PCIEM_SLOT_STA_PFD)
1227 		device_printf(dev, "Power Fault Detected\n");
1228 	if (sc->pcie_slot_sta & PCIEM_SLOT_STA_MRLSC)
1229 		device_printf(dev, "MRL Sensor Changed to %s\n",
1230 		    sc->pcie_slot_sta & PCIEM_SLOT_STA_MRLSS ? "open" :
1231 		    "closed");
1232 	if (bootverbose && sc->pcie_slot_sta & PCIEM_SLOT_STA_PDC)
1233 		device_printf(dev, "Presence Detect Changed to %s\n",
1234 		    sc->pcie_slot_sta & PCIEM_SLOT_STA_PDS ? "card present" :
1235 		    "empty");
1236 	if (sc->pcie_slot_sta & PCIEM_SLOT_STA_CC)
1237 		pcib_pcie_hotplug_command_completed(sc);
1238 	if (sc->pcie_slot_sta & PCIEM_SLOT_STA_DLLSC) {
1239 		sc->pcie_link_sta = pcie_read_config(dev, PCIER_LINK_STA, 2);
1240 		if (bootverbose)
1241 			device_printf(dev,
1242 			    "Data Link Layer State Changed to %s\n",
1243 			    sc->pcie_link_sta & PCIEM_LINK_STA_DL_ACTIVE ?
1244 			    "active" : "inactive");
1245 	}
1246 
1247 	pcib_pcie_hotplug_update(sc, 0, 0, true);
1248 	PCIB_HP_UNLOCK(sc);
1249 }
1250 
1251 static void
pcib_pcie_hotplug_task(void * context,int pending)1252 pcib_pcie_hotplug_task(void *context, int pending)
1253 {
1254 	struct pcib_softc *sc;
1255 	device_t dev;
1256 
1257 	sc = context;
1258 	PCIB_HP_LOCK(sc);
1259 	dev = sc->dev;
1260 	if (pcib_hotplug_present(sc) != 0) {
1261 		if (sc->child == NULL) {
1262 			sc->child = device_add_child(dev, "pci", -1);
1263 			bus_generic_attach(dev);
1264 		}
1265 	} else {
1266 		if (sc->child != NULL) {
1267 			if (device_delete_child(dev, sc->child) == 0)
1268 				sc->child = NULL;
1269 		}
1270 	}
1271 	PCIB_HP_UNLOCK(sc);
1272 }
1273 
1274 static void
pcib_pcie_ab_timeout(void * arg,int pending)1275 pcib_pcie_ab_timeout(void *arg, int pending)
1276 {
1277 	struct pcib_softc *sc = arg;
1278 
1279 	PCIB_HP_LOCK(sc);
1280 	if (sc->flags & PCIB_DETACH_PENDING) {
1281 		sc->flags |= PCIB_DETACHING;
1282 		sc->flags &= ~PCIB_DETACH_PENDING;
1283 		pcib_pcie_hotplug_update(sc, 0, 0, true);
1284 	}
1285 	PCIB_HP_UNLOCK(sc);
1286 }
1287 
1288 static void
pcib_pcie_cc_timeout(void * arg,int pending)1289 pcib_pcie_cc_timeout(void *arg, int pending)
1290 {
1291 	struct pcib_softc *sc = arg;
1292 	device_t dev = sc->dev;
1293 	uint16_t sta;
1294 
1295 	PCIB_HP_LOCK(sc);
1296 	sta = pcie_read_config(dev, PCIER_SLOT_STA, 2);
1297 	if (!(sta & PCIEM_SLOT_STA_CC)) {
1298 		device_printf(dev, "HotPlug Command Timed Out\n");
1299 		sc->flags &= ~PCIB_HOTPLUG_CMD_PENDING;
1300 	} else {
1301 		device_printf(dev,
1302 	    "Missed HotPlug interrupt waiting for Command Completion\n");
1303 		pcib_pcie_intr_hotplug(sc);
1304 	}
1305 	PCIB_HP_UNLOCK(sc);
1306 }
1307 
1308 static void
pcib_pcie_dll_timeout(void * arg,int pending)1309 pcib_pcie_dll_timeout(void *arg, int pending)
1310 {
1311 	struct pcib_softc *sc = arg;
1312 	device_t dev = sc->dev;
1313 	uint16_t sta;
1314 
1315 	PCIB_HP_LOCK(sc);
1316 	sta = pcie_read_config(dev, PCIER_LINK_STA, 2);
1317 	if (!(sta & PCIEM_LINK_STA_DL_ACTIVE)) {
1318 		device_printf(dev,
1319 		    "Timed out waiting for Data Link Layer Active\n");
1320 		sc->flags |= PCIB_DETACHING;
1321 		pcib_pcie_hotplug_update(sc, 0, 0, true);
1322 	} else if (sta != sc->pcie_link_sta) {
1323 		device_printf(dev,
1324 		    "Missed HotPlug interrupt waiting for DLL Active\n");
1325 		pcib_pcie_intr_hotplug(sc);
1326 	}
1327 	PCIB_HP_UNLOCK(sc);
1328 }
1329 
1330 static int
pcib_alloc_pcie_irq(struct pcib_softc * sc)1331 pcib_alloc_pcie_irq(struct pcib_softc *sc)
1332 {
1333 	device_t dev;
1334 	int count, error, mem_rid, rid;
1335 
1336 	rid = -1;
1337 	dev = sc->dev;
1338 
1339 	/*
1340 	 * For simplicity, only use MSI-X if there is a single message.
1341 	 * To support a device with multiple messages we would have to
1342 	 * use remap intr if the MSI number is not 0.
1343 	 */
1344 	count = pci_msix_count(dev);
1345 	if (count == 1) {
1346 		mem_rid = pci_msix_table_bar(dev);
1347 		sc->pcie_mem = bus_alloc_resource_any(dev, SYS_RES_MEMORY,
1348 		    &mem_rid, RF_ACTIVE);
1349 		if (sc->pcie_mem == NULL) {
1350 			device_printf(dev,
1351 			    "Failed to allocate BAR for MSI-X table\n");
1352 		} else {
1353 			error = pci_alloc_msix(dev, &count);
1354 			if (error == 0)
1355 				rid = 1;
1356 		}
1357 	}
1358 
1359 	if (rid < 0 && pci_msi_count(dev) > 0) {
1360 		count = 1;
1361 		error = pci_alloc_msi(dev, &count);
1362 		if (error == 0)
1363 			rid = 1;
1364 	}
1365 
1366 	if (rid < 0)
1367 		rid = 0;
1368 
1369 	sc->pcie_irq = bus_alloc_resource_any(dev, SYS_RES_IRQ, &rid,
1370 	    RF_ACTIVE | RF_SHAREABLE);
1371 	if (sc->pcie_irq == NULL) {
1372 		device_printf(dev,
1373 		    "Failed to allocate interrupt for PCI-e events\n");
1374 		if (rid > 0)
1375 			pci_release_msi(dev);
1376 		return (ENXIO);
1377 	}
1378 
1379 	error = bus_setup_intr(dev, sc->pcie_irq, INTR_TYPE_MISC|INTR_MPSAFE,
1380 	    NULL, pcib_pcie_intr_hotplug, sc, &sc->pcie_ihand);
1381 	if (error) {
1382 		device_printf(dev, "Failed to setup PCI-e interrupt handler\n");
1383 		bus_release_resource(dev, SYS_RES_IRQ, rid, sc->pcie_irq);
1384 		if (rid > 0)
1385 			pci_release_msi(dev);
1386 		return (error);
1387 	}
1388 	return (0);
1389 }
1390 
1391 static int
pcib_release_pcie_irq(struct pcib_softc * sc)1392 pcib_release_pcie_irq(struct pcib_softc *sc)
1393 {
1394 	device_t dev;
1395 	int error;
1396 
1397 	dev = sc->dev;
1398 	error = bus_teardown_intr(dev, sc->pcie_irq, sc->pcie_ihand);
1399 	if (error)
1400 		return (error);
1401 	error = bus_free_resource(dev, SYS_RES_IRQ, sc->pcie_irq);
1402 	if (error)
1403 		return (error);
1404 	error = pci_release_msi(dev);
1405 	if (error)
1406 		return (error);
1407 	if (sc->pcie_mem != NULL)
1408 		error = bus_free_resource(dev, SYS_RES_MEMORY, sc->pcie_mem);
1409 	return (error);
1410 }
1411 
1412 static void
pcib_setup_hotplug(struct pcib_softc * sc)1413 pcib_setup_hotplug(struct pcib_softc *sc)
1414 {
1415 	device_t dev;
1416 	uint16_t mask, val;
1417 
1418 	dev = sc->dev;
1419 	TASK_INIT(&sc->pcie_hp_task, 0, pcib_pcie_hotplug_task, sc);
1420 	TIMEOUT_TASK_INIT(taskqueue_pci_hp, &sc->pcie_ab_task, 0,
1421 	    pcib_pcie_ab_timeout, sc);
1422 	TIMEOUT_TASK_INIT(taskqueue_pci_hp, &sc->pcie_cc_task, 0,
1423 	    pcib_pcie_cc_timeout, sc);
1424 	TIMEOUT_TASK_INIT(taskqueue_pci_hp, &sc->pcie_dll_task, 0,
1425 	    pcib_pcie_dll_timeout, sc);
1426 	sc->pcie_hp_lock = bus_topo_mtx();
1427 
1428 	/* Allocate IRQ. */
1429 	if (pcib_alloc_pcie_irq(sc) != 0)
1430 		return;
1431 
1432 	sc->pcie_link_sta = pcie_read_config(dev, PCIER_LINK_STA, 2);
1433 	sc->pcie_slot_sta = pcie_read_config(dev, PCIER_SLOT_STA, 2);
1434 
1435 	/* Clear any events previously pending. */
1436 	pcie_write_config(dev, PCIER_SLOT_STA, sc->pcie_slot_sta, 2);
1437 	sc->pcie_slot_sta = pcie_read_config(dev, PCIER_SLOT_STA, 2);
1438 
1439 	/* Enable HotPlug events. */
1440 	mask = PCIEM_SLOT_CTL_DLLSCE | PCIEM_SLOT_CTL_HPIE |
1441 	    PCIEM_SLOT_CTL_CCIE | PCIEM_SLOT_CTL_PDCE | PCIEM_SLOT_CTL_MRLSCE |
1442 	    PCIEM_SLOT_CTL_PFDE | PCIEM_SLOT_CTL_ABPE;
1443 	val = PCIEM_SLOT_CTL_DLLSCE | PCIEM_SLOT_CTL_HPIE | PCIEM_SLOT_CTL_PDCE;
1444 	if (sc->pcie_slot_cap & PCIEM_SLOT_CAP_APB)
1445 		val |= PCIEM_SLOT_CTL_ABPE;
1446 	if (sc->pcie_slot_cap & PCIEM_SLOT_CAP_PCP)
1447 		val |= PCIEM_SLOT_CTL_PFDE;
1448 	if (sc->pcie_slot_cap & PCIEM_SLOT_CAP_MRLSP)
1449 		val |= PCIEM_SLOT_CTL_MRLSCE;
1450 	if (!(sc->pcie_slot_cap & PCIEM_SLOT_CAP_NCCS))
1451 		val |= PCIEM_SLOT_CTL_CCIE;
1452 
1453 	/* Turn the attention indicator off. */
1454 	if (sc->pcie_slot_cap & PCIEM_SLOT_CAP_AIP) {
1455 		mask |= PCIEM_SLOT_CTL_AIC;
1456 		val |= PCIEM_SLOT_CTL_AI_OFF;
1457 	}
1458 
1459 	pcib_pcie_hotplug_update(sc, val, mask, false);
1460 }
1461 
1462 static int
pcib_detach_hotplug(struct pcib_softc * sc)1463 pcib_detach_hotplug(struct pcib_softc *sc)
1464 {
1465 	uint16_t mask, val;
1466 	int error;
1467 
1468 	/* Disable the card in the slot and force it to detach. */
1469 	if (sc->flags & PCIB_DETACH_PENDING) {
1470 		sc->flags &= ~PCIB_DETACH_PENDING;
1471 		taskqueue_cancel_timeout(taskqueue_pci_hp, &sc->pcie_ab_task,
1472 		    NULL);
1473 	}
1474 	sc->flags |= PCIB_DETACHING;
1475 
1476 	if (sc->flags & PCIB_HOTPLUG_CMD_PENDING) {
1477 		taskqueue_cancel_timeout(taskqueue_pci_hp, &sc->pcie_cc_task,
1478 		    NULL);
1479 		tsleep(sc, 0, "hpcmd", hz);
1480 		sc->flags &= ~PCIB_HOTPLUG_CMD_PENDING;
1481 	}
1482 
1483 	/* Disable HotPlug events. */
1484 	mask = PCIEM_SLOT_CTL_DLLSCE | PCIEM_SLOT_CTL_HPIE |
1485 	    PCIEM_SLOT_CTL_CCIE | PCIEM_SLOT_CTL_PDCE | PCIEM_SLOT_CTL_MRLSCE |
1486 	    PCIEM_SLOT_CTL_PFDE | PCIEM_SLOT_CTL_ABPE;
1487 	val = 0;
1488 
1489 	/* Turn the attention indicator off. */
1490 	if (sc->pcie_slot_cap & PCIEM_SLOT_CAP_AIP) {
1491 		mask |= PCIEM_SLOT_CTL_AIC;
1492 		val |= PCIEM_SLOT_CTL_AI_OFF;
1493 	}
1494 
1495 	pcib_pcie_hotplug_update(sc, val, mask, false);
1496 
1497 	error = pcib_release_pcie_irq(sc);
1498 	if (error)
1499 		return (error);
1500 	taskqueue_drain(taskqueue_pci_hp, &sc->pcie_hp_task);
1501 	taskqueue_drain_timeout(taskqueue_pci_hp, &sc->pcie_ab_task);
1502 	taskqueue_drain_timeout(taskqueue_pci_hp, &sc->pcie_cc_task);
1503 	taskqueue_drain_timeout(taskqueue_pci_hp, &sc->pcie_dll_task);
1504 	return (0);
1505 }
1506 #endif
1507 
1508 /*
1509  * Get current bridge configuration.
1510  */
1511 static void
pcib_cfg_save(struct pcib_softc * sc)1512 pcib_cfg_save(struct pcib_softc *sc)
1513 {
1514 #ifndef NEW_PCIB
1515 	device_t	dev;
1516 	uint16_t command;
1517 
1518 	dev = sc->dev;
1519 
1520 	command = pci_read_config(dev, PCIR_COMMAND, 2);
1521 	if (command & PCIM_CMD_PORTEN)
1522 		pcib_get_io_decode(sc);
1523 	if (command & PCIM_CMD_MEMEN)
1524 		pcib_get_mem_decode(sc);
1525 #endif
1526 }
1527 
1528 /*
1529  * Restore previous bridge configuration.
1530  */
1531 static void
pcib_cfg_restore(struct pcib_softc * sc)1532 pcib_cfg_restore(struct pcib_softc *sc)
1533 {
1534 #ifndef NEW_PCIB
1535 	uint16_t command;
1536 #endif
1537 
1538 #ifdef NEW_PCIB
1539 	pcib_write_windows(sc, WIN_IO | WIN_MEM | WIN_PMEM);
1540 #else
1541 	command = pci_read_config(sc->dev, PCIR_COMMAND, 2);
1542 	if (command & PCIM_CMD_PORTEN)
1543 		pcib_set_io_decode(sc);
1544 	if (command & PCIM_CMD_MEMEN)
1545 		pcib_set_mem_decode(sc);
1546 #endif
1547 }
1548 
1549 /*
1550  * Generic device interface
1551  */
1552 static int
pcib_probe(device_t dev)1553 pcib_probe(device_t dev)
1554 {
1555     if ((pci_get_class(dev) == PCIC_BRIDGE) &&
1556 	(pci_get_subclass(dev) == PCIS_BRIDGE_PCI)) {
1557 	device_set_desc(dev, "PCI-PCI bridge");
1558 	return(-10000);
1559     }
1560     return(ENXIO);
1561 }
1562 
1563 void
pcib_attach_common(device_t dev)1564 pcib_attach_common(device_t dev)
1565 {
1566     struct pcib_softc	*sc;
1567     struct sysctl_ctx_list *sctx;
1568     struct sysctl_oid	*soid;
1569     int comma;
1570 
1571     sc = device_get_softc(dev);
1572     sc->dev = dev;
1573 
1574     /*
1575      * Get current bridge configuration.
1576      */
1577     sc->domain = pci_get_domain(dev);
1578 #if !(defined(NEW_PCIB) && defined(PCI_RES_BUS))
1579     sc->bus.sec = pci_read_config(dev, PCIR_SECBUS_1, 1);
1580     sc->bus.sub = pci_read_config(dev, PCIR_SUBBUS_1, 1);
1581 #endif
1582     sc->bridgectl = pci_read_config(dev, PCIR_BRIDGECTL_1, 2);
1583     pcib_cfg_save(sc);
1584 
1585     /*
1586      * The primary bus register should always be the bus of the
1587      * parent.
1588      */
1589     sc->pribus = pci_get_bus(dev);
1590     pci_write_config(dev, PCIR_PRIBUS_1, sc->pribus, 1);
1591 
1592     /*
1593      * Setup sysctl reporting nodes
1594      */
1595     sctx = device_get_sysctl_ctx(dev);
1596     soid = device_get_sysctl_tree(dev);
1597     SYSCTL_ADD_UINT(sctx, SYSCTL_CHILDREN(soid), OID_AUTO, "domain",
1598       CTLFLAG_RD, &sc->domain, 0, "Domain number");
1599     SYSCTL_ADD_UINT(sctx, SYSCTL_CHILDREN(soid), OID_AUTO, "pribus",
1600       CTLFLAG_RD, &sc->pribus, 0, "Primary bus number");
1601     SYSCTL_ADD_UINT(sctx, SYSCTL_CHILDREN(soid), OID_AUTO, "secbus",
1602       CTLFLAG_RD, &sc->bus.sec, 0, "Secondary bus number");
1603     SYSCTL_ADD_UINT(sctx, SYSCTL_CHILDREN(soid), OID_AUTO, "subbus",
1604       CTLFLAG_RD, &sc->bus.sub, 0, "Subordinate bus number");
1605 
1606     /*
1607      * Quirk handling.
1608      */
1609     switch (pci_get_devid(dev)) {
1610 #if !(defined(NEW_PCIB) && defined(PCI_RES_BUS))
1611     case 0x12258086:		/* Intel 82454KX/GX (Orion) */
1612 	{
1613 	    uint8_t	supbus;
1614 
1615 	    supbus = pci_read_config(dev, 0x41, 1);
1616 	    if (supbus != 0xff) {
1617 		sc->bus.sec = supbus + 1;
1618 		sc->bus.sub = supbus + 1;
1619 	    }
1620 	    break;
1621 	}
1622 #endif
1623 
1624     /*
1625      * The i82380FB mobile docking controller is a PCI-PCI bridge,
1626      * and it is a subtractive bridge.  However, the ProgIf is wrong
1627      * so the normal setting of PCIB_SUBTRACTIVE bit doesn't
1628      * happen.  There are also Toshiba and Cavium ThunderX bridges
1629      * that behave this way.
1630      */
1631     case 0xa002177d:		/* Cavium ThunderX */
1632     case 0x124b8086:		/* Intel 82380FB Mobile */
1633     case 0x060513d7:		/* Toshiba ???? */
1634 	sc->flags |= PCIB_SUBTRACTIVE;
1635 	break;
1636 
1637 #if !(defined(NEW_PCIB) && defined(PCI_RES_BUS))
1638     /* Compaq R3000 BIOS sets wrong subordinate bus number. */
1639     case 0x00dd10de:
1640 	{
1641 	    char *cp;
1642 
1643 	    if ((cp = kern_getenv("smbios.planar.maker")) == NULL)
1644 		break;
1645 	    if (strncmp(cp, "Compal", 6) != 0) {
1646 		freeenv(cp);
1647 		break;
1648 	    }
1649 	    freeenv(cp);
1650 	    if ((cp = kern_getenv("smbios.planar.product")) == NULL)
1651 		break;
1652 	    if (strncmp(cp, "08A0", 4) != 0) {
1653 		freeenv(cp);
1654 		break;
1655 	    }
1656 	    freeenv(cp);
1657 	    if (sc->bus.sub < 0xa) {
1658 		pci_write_config(dev, PCIR_SUBBUS_1, 0xa, 1);
1659 		sc->bus.sub = pci_read_config(dev, PCIR_SUBBUS_1, 1);
1660 	    }
1661 	    break;
1662 	}
1663 #endif
1664     }
1665 
1666     if (pci_msi_device_blacklisted(dev))
1667 	sc->flags |= PCIB_DISABLE_MSI;
1668 
1669     if (pci_msix_device_blacklisted(dev))
1670 	sc->flags |= PCIB_DISABLE_MSIX;
1671 
1672     /*
1673      * Intel 815, 845 and other chipsets say they are PCI-PCI bridges,
1674      * but have a ProgIF of 0x80.  The 82801 family (AA, AB, BAM/CAM,
1675      * BA/CA/DB and E) PCI bridges are HUB-PCI bridges, in Intelese.
1676      * This means they act as if they were subtractively decoding
1677      * bridges and pass all transactions.  Mark them and real ProgIf 1
1678      * parts as subtractive.
1679      */
1680     if ((pci_get_devid(dev) & 0xff00ffff) == 0x24008086 ||
1681       pci_read_config(dev, PCIR_PROGIF, 1) == PCIP_BRIDGE_PCI_SUBTRACTIVE)
1682 	sc->flags |= PCIB_SUBTRACTIVE;
1683 
1684 #ifdef PCI_HP
1685     pcib_probe_hotplug(sc);
1686 #endif
1687 #ifdef NEW_PCIB
1688 #ifdef PCI_RES_BUS
1689     pcib_setup_secbus(dev, &sc->bus, 1);
1690 #endif
1691     pcib_probe_windows(sc);
1692 #endif
1693 #ifdef PCI_HP
1694     if (sc->flags & PCIB_HOTPLUG)
1695 	    pcib_setup_hotplug(sc);
1696 #endif
1697     if (bootverbose) {
1698 	device_printf(dev, "  domain            %d\n", sc->domain);
1699 	device_printf(dev, "  secondary bus     %d\n", sc->bus.sec);
1700 	device_printf(dev, "  subordinate bus   %d\n", sc->bus.sub);
1701 #ifdef NEW_PCIB
1702 	if (pcib_is_window_open(&sc->io))
1703 	    device_printf(dev, "  I/O decode        0x%jx-0x%jx\n",
1704 	      (uintmax_t)sc->io.base, (uintmax_t)sc->io.limit);
1705 	if (pcib_is_window_open(&sc->mem))
1706 	    device_printf(dev, "  memory decode     0x%jx-0x%jx\n",
1707 	      (uintmax_t)sc->mem.base, (uintmax_t)sc->mem.limit);
1708 	if (pcib_is_window_open(&sc->pmem))
1709 	    device_printf(dev, "  prefetched decode 0x%jx-0x%jx\n",
1710 	      (uintmax_t)sc->pmem.base, (uintmax_t)sc->pmem.limit);
1711 #else
1712 	if (pcib_is_io_open(sc))
1713 	    device_printf(dev, "  I/O decode        0x%x-0x%x\n",
1714 	      sc->iobase, sc->iolimit);
1715 	if (pcib_is_nonprefetch_open(sc))
1716 	    device_printf(dev, "  memory decode     0x%jx-0x%jx\n",
1717 	      (uintmax_t)sc->membase, (uintmax_t)sc->memlimit);
1718 	if (pcib_is_prefetch_open(sc))
1719 	    device_printf(dev, "  prefetched decode 0x%jx-0x%jx\n",
1720 	      (uintmax_t)sc->pmembase, (uintmax_t)sc->pmemlimit);
1721 #endif
1722 	if (sc->bridgectl & (PCIB_BCR_ISA_ENABLE | PCIB_BCR_VGA_ENABLE) ||
1723 	    sc->flags & PCIB_SUBTRACTIVE) {
1724 		device_printf(dev, "  special decode    ");
1725 		comma = 0;
1726 		if (sc->bridgectl & PCIB_BCR_ISA_ENABLE) {
1727 			printf("ISA");
1728 			comma = 1;
1729 		}
1730 		if (sc->bridgectl & PCIB_BCR_VGA_ENABLE) {
1731 			printf("%sVGA", comma ? ", " : "");
1732 			comma = 1;
1733 		}
1734 		if (sc->flags & PCIB_SUBTRACTIVE)
1735 			printf("%ssubtractive", comma ? ", " : "");
1736 		printf("\n");
1737 	}
1738     }
1739 
1740     /*
1741      * Always enable busmastering on bridges so that transactions
1742      * initiated on the secondary bus are passed through to the
1743      * primary bus.
1744      */
1745     pci_enable_busmaster(dev);
1746 }
1747 
1748 #ifdef PCI_HP
1749 static int
pcib_present(struct pcib_softc * sc)1750 pcib_present(struct pcib_softc *sc)
1751 {
1752 
1753 	if (sc->flags & PCIB_HOTPLUG)
1754 		return (pcib_hotplug_present(sc) != 0);
1755 	return (1);
1756 }
1757 #endif
1758 
1759 int
pcib_attach_child(device_t dev)1760 pcib_attach_child(device_t dev)
1761 {
1762 	struct pcib_softc *sc;
1763 
1764 	sc = device_get_softc(dev);
1765 	if (sc->bus.sec == 0) {
1766 		/* no secondary bus; we should have fixed this */
1767 		return(0);
1768 	}
1769 
1770 #ifdef PCI_HP
1771 	if (!pcib_present(sc)) {
1772 		/* An empty HotPlug slot, so don't add a PCI bus yet. */
1773 		return (0);
1774 	}
1775 #endif
1776 
1777 	sc->child = device_add_child(dev, "pci", -1);
1778 	return (bus_generic_attach(dev));
1779 }
1780 
1781 int
pcib_attach(device_t dev)1782 pcib_attach(device_t dev)
1783 {
1784 
1785     pcib_attach_common(dev);
1786     return (pcib_attach_child(dev));
1787 }
1788 
1789 int
pcib_detach(device_t dev)1790 pcib_detach(device_t dev)
1791 {
1792 #if defined(PCI_HP) || defined(NEW_PCIB)
1793 	struct pcib_softc *sc;
1794 #endif
1795 	int error;
1796 
1797 #if defined(PCI_HP) || defined(NEW_PCIB)
1798 	sc = device_get_softc(dev);
1799 #endif
1800 	error = bus_generic_detach(dev);
1801 	if (error)
1802 		return (error);
1803 #ifdef PCI_HP
1804 	if (sc->flags & PCIB_HOTPLUG) {
1805 		error = pcib_detach_hotplug(sc);
1806 		if (error)
1807 			return (error);
1808 	}
1809 #endif
1810 	error = device_delete_children(dev);
1811 	if (error)
1812 		return (error);
1813 #ifdef NEW_PCIB
1814 	pcib_free_windows(sc);
1815 #ifdef PCI_RES_BUS
1816 	pcib_free_secbus(dev, &sc->bus);
1817 #endif
1818 #endif
1819 	return (0);
1820 }
1821 
1822 int
pcib_suspend(device_t dev)1823 pcib_suspend(device_t dev)
1824 {
1825 
1826 	pcib_cfg_save(device_get_softc(dev));
1827 	return (bus_generic_suspend(dev));
1828 }
1829 
1830 int
pcib_resume(device_t dev)1831 pcib_resume(device_t dev)
1832 {
1833 
1834 	pcib_cfg_restore(device_get_softc(dev));
1835 
1836 	/*
1837 	 * Restore the Command register only after restoring the windows.
1838 	 * The bridge should not be claiming random windows.
1839 	 */
1840 	pci_write_config(dev, PCIR_COMMAND, pci_get_cmdreg(dev), 2);
1841 	return (bus_generic_resume(dev));
1842 }
1843 
1844 void
pcib_bridge_init(device_t dev)1845 pcib_bridge_init(device_t dev)
1846 {
1847 	pci_write_config(dev, PCIR_IOBASEL_1, 0xff, 1);
1848 	pci_write_config(dev, PCIR_IOBASEH_1, 0xffff, 2);
1849 	pci_write_config(dev, PCIR_IOLIMITL_1, 0, 1);
1850 	pci_write_config(dev, PCIR_IOLIMITH_1, 0, 2);
1851 	pci_write_config(dev, PCIR_MEMBASE_1, 0xffff, 2);
1852 	pci_write_config(dev, PCIR_MEMLIMIT_1, 0, 2);
1853 	pci_write_config(dev, PCIR_PMBASEL_1, 0xffff, 2);
1854 	pci_write_config(dev, PCIR_PMBASEH_1, 0xffffffff, 4);
1855 	pci_write_config(dev, PCIR_PMLIMITL_1, 0, 2);
1856 	pci_write_config(dev, PCIR_PMLIMITH_1, 0, 4);
1857 }
1858 
1859 int
pcib_child_present(device_t dev,device_t child)1860 pcib_child_present(device_t dev, device_t child)
1861 {
1862 #ifdef PCI_HP
1863 	struct pcib_softc *sc = device_get_softc(dev);
1864 	int retval;
1865 
1866 	retval = bus_child_present(dev);
1867 	if (retval != 0 && sc->flags & PCIB_HOTPLUG)
1868 		retval = pcib_hotplug_present(sc);
1869 	return (retval);
1870 #else
1871 	return (bus_child_present(dev));
1872 #endif
1873 }
1874 
1875 int
pcib_read_ivar(device_t dev,device_t child,int which,uintptr_t * result)1876 pcib_read_ivar(device_t dev, device_t child, int which, uintptr_t *result)
1877 {
1878     struct pcib_softc	*sc = device_get_softc(dev);
1879 
1880     switch (which) {
1881     case PCIB_IVAR_DOMAIN:
1882 	*result = sc->domain;
1883 	return(0);
1884     case PCIB_IVAR_BUS:
1885 	*result = sc->bus.sec;
1886 	return(0);
1887     }
1888     return(ENOENT);
1889 }
1890 
1891 int
pcib_write_ivar(device_t dev,device_t child,int which,uintptr_t value)1892 pcib_write_ivar(device_t dev, device_t child, int which, uintptr_t value)
1893 {
1894 
1895     switch (which) {
1896     case PCIB_IVAR_DOMAIN:
1897 	return(EINVAL);
1898     case PCIB_IVAR_BUS:
1899 	return(EINVAL);
1900     }
1901     return(ENOENT);
1902 }
1903 
1904 #ifdef NEW_PCIB
1905 /*
1906  * Attempt to allocate a resource from the existing resources assigned
1907  * to a window.
1908  */
1909 static struct resource *
pcib_suballoc_resource(struct pcib_softc * sc,struct pcib_window * w,device_t child,int type,int * rid,rman_res_t start,rman_res_t end,rman_res_t count,u_int flags)1910 pcib_suballoc_resource(struct pcib_softc *sc, struct pcib_window *w,
1911     device_t child, int type, int *rid, rman_res_t start, rman_res_t end,
1912     rman_res_t count, u_int flags)
1913 {
1914 	struct resource *res;
1915 
1916 	if (!pcib_is_window_open(w))
1917 		return (NULL);
1918 
1919 	res = rman_reserve_resource(&w->rman, start, end, count,
1920 	    flags & ~RF_ACTIVE, child);
1921 	if (res == NULL)
1922 		return (NULL);
1923 
1924 	if (bootverbose)
1925 		device_printf(sc->dev,
1926 		    "allocated %s range (%#jx-%#jx) for rid %x of %s\n",
1927 		    w->name, rman_get_start(res), rman_get_end(res), *rid,
1928 		    pcib_child_name(child));
1929 	rman_set_rid(res, *rid);
1930 
1931 	/*
1932 	 * If the resource should be active, pass that request up the
1933 	 * tree.  This assumes the parent drivers can handle
1934 	 * activating sub-allocated resources.
1935 	 */
1936 	if (flags & RF_ACTIVE) {
1937 		if (bus_activate_resource(child, type, *rid, res) != 0) {
1938 			rman_release_resource(res);
1939 			return (NULL);
1940 		}
1941 	}
1942 
1943 	return (res);
1944 }
1945 
1946 /* Allocate a fresh resource range for an unconfigured window. */
1947 static int
pcib_alloc_new_window(struct pcib_softc * sc,struct pcib_window * w,int type,rman_res_t start,rman_res_t end,rman_res_t count,u_int flags)1948 pcib_alloc_new_window(struct pcib_softc *sc, struct pcib_window *w, int type,
1949     rman_res_t start, rman_res_t end, rman_res_t count, u_int flags)
1950 {
1951 	struct resource *res;
1952 	rman_res_t base, limit, wmask;
1953 	int rid;
1954 
1955 	/*
1956 	 * If this is an I/O window on a bridge with ISA enable set
1957 	 * and the start address is below 64k, then try to allocate an
1958 	 * initial window of 0x1000 bytes long starting at address
1959 	 * 0xf000 and walking down.  Note that if the original request
1960 	 * was larger than the non-aliased range size of 0x100 our
1961 	 * caller would have raised the start address up to 64k
1962 	 * already.
1963 	 */
1964 	if (type == SYS_RES_IOPORT && sc->bridgectl & PCIB_BCR_ISA_ENABLE &&
1965 	    start < 65536) {
1966 		for (base = 0xf000; (long)base >= 0; base -= 0x1000) {
1967 			limit = base + 0xfff;
1968 
1969 			/*
1970 			 * Skip ranges that wouldn't work for the
1971 			 * original request.  Note that the actual
1972 			 * window that overlaps are the non-alias
1973 			 * ranges within [base, limit], so this isn't
1974 			 * quite a simple comparison.
1975 			 */
1976 			if (start + count > limit - 0x400)
1977 				continue;
1978 			if (base == 0) {
1979 				/*
1980 				 * The first open region for the window at
1981 				 * 0 is 0x400-0x4ff.
1982 				 */
1983 				if (end - count + 1 < 0x400)
1984 					continue;
1985 			} else {
1986 				if (end - count + 1 < base)
1987 					continue;
1988 			}
1989 
1990 			if (pcib_alloc_nonisa_ranges(sc, base, limit) == 0) {
1991 				w->base = base;
1992 				w->limit = limit;
1993 				return (0);
1994 			}
1995 		}
1996 		return (ENOSPC);
1997 	}
1998 
1999 	wmask = ((rman_res_t)1 << w->step) - 1;
2000 	if (RF_ALIGNMENT(flags) < w->step) {
2001 		flags &= ~RF_ALIGNMENT_MASK;
2002 		flags |= RF_ALIGNMENT_LOG2(w->step);
2003 	}
2004 	start &= ~wmask;
2005 	end |= wmask;
2006 	count = roundup2(count, (rman_res_t)1 << w->step);
2007 	rid = w->reg;
2008 	res = bus_alloc_resource(sc->dev, type, &rid, start, end, count,
2009 	    flags & ~RF_ACTIVE);
2010 	if (res == NULL)
2011 		return (ENOSPC);
2012 	pcib_add_window_resources(w, &res, 1);
2013 	pcib_activate_window(sc, type);
2014 	w->base = rman_get_start(res);
2015 	w->limit = rman_get_end(res);
2016 	return (0);
2017 }
2018 
2019 /* Try to expand an existing window to the requested base and limit. */
2020 static int
pcib_expand_window(struct pcib_softc * sc,struct pcib_window * w,int type,rman_res_t base,rman_res_t limit)2021 pcib_expand_window(struct pcib_softc *sc, struct pcib_window *w, int type,
2022     rman_res_t base, rman_res_t limit)
2023 {
2024 	struct resource *res;
2025 	int error, i, force_64k_base;
2026 
2027 	KASSERT(base <= w->base && limit >= w->limit,
2028 	    ("attempting to shrink window"));
2029 
2030 	/*
2031 	 * XXX: pcib_grow_window() doesn't try to do this anyway and
2032 	 * the error handling for all the edge cases would be tedious.
2033 	 */
2034 	KASSERT(limit == w->limit || base == w->base,
2035 	    ("attempting to grow both ends of a window"));
2036 
2037 	/*
2038 	 * Yet more special handling for requests to expand an I/O
2039 	 * window behind an ISA-enabled bridge.  Since I/O windows
2040 	 * have to grow in 0x1000 increments and the end of the 0xffff
2041 	 * range is an alias, growing a window below 64k will always
2042 	 * result in allocating new resources and never adjusting an
2043 	 * existing resource.
2044 	 */
2045 	if (type == SYS_RES_IOPORT && sc->bridgectl & PCIB_BCR_ISA_ENABLE &&
2046 	    (limit <= 65535 || (base <= 65535 && base != w->base))) {
2047 		KASSERT(limit == w->limit || limit <= 65535,
2048 		    ("attempting to grow both ends across 64k ISA alias"));
2049 
2050 		if (base != w->base)
2051 			error = pcib_alloc_nonisa_ranges(sc, base, w->base - 1);
2052 		else
2053 			error = pcib_alloc_nonisa_ranges(sc, w->limit + 1,
2054 			    limit);
2055 		if (error == 0) {
2056 			w->base = base;
2057 			w->limit = limit;
2058 		}
2059 		return (error);
2060 	}
2061 
2062 	/*
2063 	 * Find the existing resource to adjust.  Usually there is only one,
2064 	 * but for an ISA-enabled bridge we might be growing the I/O window
2065 	 * above 64k and need to find the existing resource that maps all
2066 	 * of the area above 64k.
2067 	 */
2068 	for (i = 0; i < w->count; i++) {
2069 		if (rman_get_end(w->res[i]) == w->limit)
2070 			break;
2071 	}
2072 	KASSERT(i != w->count, ("did not find existing resource"));
2073 	res = w->res[i];
2074 
2075 	/*
2076 	 * Usually the resource we found should match the window's
2077 	 * existing range.  The one exception is the ISA-enabled case
2078 	 * mentioned above in which case the resource should start at
2079 	 * 64k.
2080 	 */
2081 	if (type == SYS_RES_IOPORT && sc->bridgectl & PCIB_BCR_ISA_ENABLE &&
2082 	    w->base <= 65535) {
2083 		KASSERT(rman_get_start(res) == 65536,
2084 		    ("existing resource mismatch"));
2085 		force_64k_base = 1;
2086 	} else {
2087 		KASSERT(w->base == rman_get_start(res),
2088 		    ("existing resource mismatch"));
2089 		force_64k_base = 0;
2090 	}
2091 
2092 	error = bus_adjust_resource(sc->dev, type, res, force_64k_base ?
2093 	    rman_get_start(res) : base, limit);
2094 	if (error)
2095 		return (error);
2096 
2097 	/* Add the newly allocated region to the resource manager. */
2098 	if (w->base != base) {
2099 		error = rman_manage_region(&w->rman, base, w->base - 1);
2100 		w->base = base;
2101 	} else {
2102 		error = rman_manage_region(&w->rman, w->limit + 1, limit);
2103 		w->limit = limit;
2104 	}
2105 	if (error) {
2106 		if (bootverbose)
2107 			device_printf(sc->dev,
2108 			    "failed to expand %s resource manager\n", w->name);
2109 		(void)bus_adjust_resource(sc->dev, type, res, force_64k_base ?
2110 		    rman_get_start(res) : w->base, w->limit);
2111 	}
2112 	return (error);
2113 }
2114 
2115 /*
2116  * Attempt to grow a window to make room for a given resource request.
2117  */
2118 static int
pcib_grow_window(struct pcib_softc * sc,struct pcib_window * w,int type,rman_res_t start,rman_res_t end,rman_res_t count,u_int flags)2119 pcib_grow_window(struct pcib_softc *sc, struct pcib_window *w, int type,
2120     rman_res_t start, rman_res_t end, rman_res_t count, u_int flags)
2121 {
2122 	rman_res_t align, start_free, end_free, front, back, wmask;
2123 	int error;
2124 
2125 	/*
2126 	 * Clamp the desired resource range to the maximum address
2127 	 * this window supports.  Reject impossible requests.
2128 	 *
2129 	 * For I/O port requests behind a bridge with the ISA enable
2130 	 * bit set, force large allocations to start above 64k.
2131 	 */
2132 	if (!w->valid)
2133 		return (EINVAL);
2134 	if (sc->bridgectl & PCIB_BCR_ISA_ENABLE && count > 0x100 &&
2135 	    start < 65536)
2136 		start = 65536;
2137 	if (end > w->rman.rm_end)
2138 		end = w->rman.rm_end;
2139 	if (start + count - 1 > end || start + count < start)
2140 		return (EINVAL);
2141 	wmask = ((rman_res_t)1 << w->step) - 1;
2142 
2143 	/*
2144 	 * If there is no resource at all, just try to allocate enough
2145 	 * aligned space for this resource.
2146 	 */
2147 	if (w->res == NULL) {
2148 		error = pcib_alloc_new_window(sc, w, type, start, end, count,
2149 		    flags);
2150 		if (error) {
2151 			if (bootverbose)
2152 				device_printf(sc->dev,
2153 		    "failed to allocate initial %s window (%#jx-%#jx,%#jx)\n",
2154 				    w->name, start, end, count);
2155 			return (error);
2156 		}
2157 		if (bootverbose)
2158 			device_printf(sc->dev,
2159 			    "allocated initial %s window of %#jx-%#jx\n",
2160 			    w->name, (uintmax_t)w->base, (uintmax_t)w->limit);
2161 		goto updatewin;
2162 	}
2163 
2164 	/*
2165 	 * See if growing the window would help.  Compute the minimum
2166 	 * amount of address space needed on both the front and back
2167 	 * ends of the existing window to satisfy the allocation.
2168 	 *
2169 	 * For each end, build a candidate region adjusting for the
2170 	 * required alignment, etc.  If there is a free region at the
2171 	 * edge of the window, grow from the inner edge of the free
2172 	 * region.  Otherwise grow from the window boundary.
2173 	 *
2174 	 * Growing an I/O window below 64k for a bridge with the ISA
2175 	 * enable bit doesn't require any special magic as the step
2176 	 * size of an I/O window (1k) always includes multiple
2177 	 * non-alias ranges when it is grown in either direction.
2178 	 *
2179 	 * XXX: Special case: if w->res is completely empty and the
2180 	 * request size is larger than w->res, we should find the
2181 	 * optimal aligned buffer containing w->res and allocate that.
2182 	 */
2183 	if (bootverbose)
2184 		device_printf(sc->dev,
2185 		    "attempting to grow %s window for (%#jx-%#jx,%#jx)\n",
2186 		    w->name, start, end, count);
2187 	align = (rman_res_t)1 << RF_ALIGNMENT(flags);
2188 	if (start < w->base) {
2189 		if (rman_first_free_region(&w->rman, &start_free, &end_free) !=
2190 		    0 || start_free != w->base)
2191 			end_free = w->base;
2192 		if (end_free > end)
2193 			end_free = end + 1;
2194 
2195 		/* Move end_free down until it is properly aligned. */
2196 		end_free &= ~(align - 1);
2197 		end_free--;
2198 		front = end_free - (count - 1);
2199 
2200 		/*
2201 		 * The resource would now be allocated at (front,
2202 		 * end_free).  Ensure that fits in the (start, end)
2203 		 * bounds.  end_free is checked above.  If 'front' is
2204 		 * ok, ensure it is properly aligned for this window.
2205 		 * Also check for underflow.
2206 		 */
2207 		if (front >= start && front <= end_free) {
2208 			if (bootverbose)
2209 				printf("\tfront candidate range: %#jx-%#jx\n",
2210 				    front, end_free);
2211 			front &= ~wmask;
2212 			front = w->base - front;
2213 		} else
2214 			front = 0;
2215 	} else
2216 		front = 0;
2217 	if (end > w->limit) {
2218 		if (rman_last_free_region(&w->rman, &start_free, &end_free) !=
2219 		    0 || end_free != w->limit)
2220 			start_free = w->limit + 1;
2221 		if (start_free < start)
2222 			start_free = start;
2223 
2224 		/* Move start_free up until it is properly aligned. */
2225 		start_free = roundup2(start_free, align);
2226 		back = start_free + count - 1;
2227 
2228 		/*
2229 		 * The resource would now be allocated at (start_free,
2230 		 * back).  Ensure that fits in the (start, end)
2231 		 * bounds.  start_free is checked above.  If 'back' is
2232 		 * ok, ensure it is properly aligned for this window.
2233 		 * Also check for overflow.
2234 		 */
2235 		if (back <= end && start_free <= back) {
2236 			if (bootverbose)
2237 				printf("\tback candidate range: %#jx-%#jx\n",
2238 				    start_free, back);
2239 			back |= wmask;
2240 			back -= w->limit;
2241 		} else
2242 			back = 0;
2243 	} else
2244 		back = 0;
2245 
2246 	/*
2247 	 * Try to allocate the smallest needed region first.
2248 	 * If that fails, fall back to the other region.
2249 	 */
2250 	error = ENOSPC;
2251 	while (front != 0 || back != 0) {
2252 		if (front != 0 && (front <= back || back == 0)) {
2253 			error = pcib_expand_window(sc, w, type, w->base - front,
2254 			    w->limit);
2255 			if (error == 0)
2256 				break;
2257 			front = 0;
2258 		} else {
2259 			error = pcib_expand_window(sc, w, type, w->base,
2260 			    w->limit + back);
2261 			if (error == 0)
2262 				break;
2263 			back = 0;
2264 		}
2265 	}
2266 
2267 	if (error)
2268 		return (error);
2269 	if (bootverbose)
2270 		device_printf(sc->dev, "grew %s window to %#jx-%#jx\n",
2271 		    w->name, (uintmax_t)w->base, (uintmax_t)w->limit);
2272 
2273 updatewin:
2274 	/* Write the new window. */
2275 	KASSERT((w->base & wmask) == 0, ("start address is not aligned"));
2276 	KASSERT((w->limit & wmask) == wmask, ("end address is not aligned"));
2277 	pcib_write_windows(sc, w->mask);
2278 	return (0);
2279 }
2280 
2281 /*
2282  * We have to trap resource allocation requests and ensure that the bridge
2283  * is set up to, or capable of handling them.
2284  */
2285 static struct resource *
pcib_alloc_resource(device_t dev,device_t child,int type,int * rid,rman_res_t start,rman_res_t end,rman_res_t count,u_int flags)2286 pcib_alloc_resource(device_t dev, device_t child, int type, int *rid,
2287     rman_res_t start, rman_res_t end, rman_res_t count, u_int flags)
2288 {
2289 	struct pcib_softc *sc;
2290 	struct resource *r;
2291 
2292 	sc = device_get_softc(dev);
2293 
2294 	/*
2295 	 * VGA resources are decoded iff the VGA enable bit is set in
2296 	 * the bridge control register.  VGA resources do not fall into
2297 	 * the resource windows and are passed up to the parent.
2298 	 */
2299 	if ((type == SYS_RES_IOPORT && pci_is_vga_ioport_range(start, end)) ||
2300 	    (type == SYS_RES_MEMORY && pci_is_vga_memory_range(start, end))) {
2301 		if (sc->bridgectl & PCIB_BCR_VGA_ENABLE)
2302 			return (bus_generic_alloc_resource(dev, child, type,
2303 			    rid, start, end, count, flags));
2304 		else
2305 			return (NULL);
2306 	}
2307 
2308 	switch (type) {
2309 #ifdef PCI_RES_BUS
2310 	case PCI_RES_BUS:
2311 		return (pcib_alloc_subbus(&sc->bus, child, rid, start, end,
2312 		    count, flags));
2313 #endif
2314 	case SYS_RES_IOPORT:
2315 		if (pcib_is_isa_range(sc, start, end, count))
2316 			return (NULL);
2317 		r = pcib_suballoc_resource(sc, &sc->io, child, type, rid, start,
2318 		    end, count, flags);
2319 		if (r != NULL || (sc->flags & PCIB_SUBTRACTIVE) != 0)
2320 			break;
2321 		if (pcib_grow_window(sc, &sc->io, type, start, end, count,
2322 		    flags) == 0)
2323 			r = pcib_suballoc_resource(sc, &sc->io, child, type,
2324 			    rid, start, end, count, flags);
2325 		break;
2326 	case SYS_RES_MEMORY:
2327 		/*
2328 		 * For prefetchable resources, prefer the prefetchable
2329 		 * memory window, but fall back to the regular memory
2330 		 * window if that fails.  Try both windows before
2331 		 * attempting to grow a window in case the firmware
2332 		 * has used a range in the regular memory window to
2333 		 * map a prefetchable BAR.
2334 		 */
2335 		if (flags & RF_PREFETCHABLE) {
2336 			r = pcib_suballoc_resource(sc, &sc->pmem, child, type,
2337 			    rid, start, end, count, flags);
2338 			if (r != NULL)
2339 				break;
2340 		}
2341 		r = pcib_suballoc_resource(sc, &sc->mem, child, type, rid,
2342 		    start, end, count, flags);
2343 		if (r != NULL || (sc->flags & PCIB_SUBTRACTIVE) != 0)
2344 			break;
2345 		if (flags & RF_PREFETCHABLE) {
2346 			if (pcib_grow_window(sc, &sc->pmem, type, start, end,
2347 			    count, flags) == 0) {
2348 				r = pcib_suballoc_resource(sc, &sc->pmem, child,
2349 				    type, rid, start, end, count, flags);
2350 				if (r != NULL)
2351 					break;
2352 			}
2353 		}
2354 		if (pcib_grow_window(sc, &sc->mem, type, start, end, count,
2355 		    flags & ~RF_PREFETCHABLE) == 0)
2356 			r = pcib_suballoc_resource(sc, &sc->mem, child, type,
2357 			    rid, start, end, count, flags);
2358 		break;
2359 	default:
2360 		return (bus_generic_alloc_resource(dev, child, type, rid,
2361 		    start, end, count, flags));
2362 	}
2363 
2364 	/*
2365 	 * If attempts to suballocate from the window fail but this is a
2366 	 * subtractive bridge, pass the request up the tree.
2367 	 */
2368 	if (sc->flags & PCIB_SUBTRACTIVE && r == NULL)
2369 		return (bus_generic_alloc_resource(dev, child, type, rid,
2370 		    start, end, count, flags));
2371 	return (r);
2372 }
2373 
2374 static int
pcib_adjust_resource(device_t bus,device_t child,int type,struct resource * r,rman_res_t start,rman_res_t end)2375 pcib_adjust_resource(device_t bus, device_t child, int type, struct resource *r,
2376     rman_res_t start, rman_res_t end)
2377 {
2378 	struct pcib_softc *sc;
2379 	struct pcib_window *w;
2380 	rman_res_t wmask;
2381 	int error;
2382 
2383 	sc = device_get_softc(bus);
2384 
2385 	/*
2386 	 * If the resource wasn't sub-allocated from one of our region
2387 	 * managers then just pass the request up.
2388 	 */
2389 	if (!pcib_is_resource_managed(sc, type, r))
2390 		return (bus_generic_adjust_resource(bus, child, type, r,
2391 		    start, end));
2392 
2393 #ifdef PCI_RES_BUS
2394 	if (type == PCI_RES_BUS) {
2395 		/*
2396 		 * If our bus range isn't big enough to grow the sub-allocation
2397 		 * then we need to grow our bus range. Any request that would
2398 		 * require us to decrease the start of our own bus range is
2399 		 * invalid, we can only extend the end; ignore such requests
2400 		 * and let rman_adjust_resource fail below.
2401 		 */
2402 		if (start >= sc->bus.sec && end > sc->bus.sub) {
2403 			error = pcib_grow_subbus(&sc->bus, end);
2404 			if (error != 0)
2405 				return (error);
2406 		}
2407 	} else
2408 #endif
2409 	{
2410 		/*
2411 		 * Resource is managed and not a secondary bus number, must
2412 		 * be from one of our windows.
2413 		 */
2414 		w = pcib_get_resource_window(sc, type, r);
2415 		KASSERT(w != NULL,
2416 		    ("%s: no window for resource (%#jx-%#jx) type %d",
2417 		    __func__, rman_get_start(r), rman_get_end(r), type));
2418 
2419 		/*
2420 		 * If our window isn't big enough to grow the sub-allocation
2421 		 * then we need to expand the window.
2422 		 */
2423 		if (start < w->base || end > w->limit) {
2424 			wmask = ((rman_res_t)1 << w->step) - 1;
2425 			error = pcib_expand_window(sc, w, type,
2426 			    MIN(start & ~wmask, w->base),
2427 			    MAX(end | wmask, w->limit));
2428 			if (error != 0)
2429 				return (error);
2430 			if (bootverbose)
2431 				device_printf(sc->dev,
2432 				    "grew %s window to %#jx-%#jx\n",
2433 				    w->name, (uintmax_t)w->base,
2434 				    (uintmax_t)w->limit);
2435 			pcib_write_windows(sc, w->mask);
2436 		}
2437 	}
2438 
2439 	return (rman_adjust_resource(r, start, end));
2440 }
2441 
2442 static int
pcib_release_resource(device_t dev,device_t child,int type,int rid,struct resource * r)2443 pcib_release_resource(device_t dev, device_t child, int type, int rid,
2444     struct resource *r)
2445 {
2446 	struct pcib_softc *sc;
2447 	int error;
2448 
2449 	sc = device_get_softc(dev);
2450 	if (pcib_is_resource_managed(sc, type, r)) {
2451 		if (rman_get_flags(r) & RF_ACTIVE) {
2452 			error = bus_deactivate_resource(child, type, rid, r);
2453 			if (error)
2454 				return (error);
2455 		}
2456 		return (rman_release_resource(r));
2457 	}
2458 	return (bus_generic_release_resource(dev, child, type, rid, r));
2459 }
2460 #else
2461 /*
2462  * We have to trap resource allocation requests and ensure that the bridge
2463  * is set up to, or capable of handling them.
2464  */
2465 static struct resource *
pcib_alloc_resource(device_t dev,device_t child,int type,int * rid,rman_res_t start,rman_res_t end,rman_res_t count,u_int flags)2466 pcib_alloc_resource(device_t dev, device_t child, int type, int *rid,
2467     rman_res_t start, rman_res_t end, rman_res_t count, u_int flags)
2468 {
2469 	struct pcib_softc	*sc = device_get_softc(dev);
2470 	const char *name, *suffix;
2471 	int ok;
2472 
2473 	/*
2474 	 * Fail the allocation for this range if it's not supported.
2475 	 */
2476 	name = device_get_nameunit(child);
2477 	if (name == NULL) {
2478 		name = "";
2479 		suffix = "";
2480 	} else
2481 		suffix = " ";
2482 	switch (type) {
2483 	case SYS_RES_IOPORT:
2484 		ok = 0;
2485 		if (!pcib_is_io_open(sc))
2486 			break;
2487 		ok = (start >= sc->iobase && end <= sc->iolimit);
2488 
2489 		/*
2490 		 * Make sure we allow access to VGA I/O addresses when the
2491 		 * bridge has the "VGA Enable" bit set.
2492 		 */
2493 		if (!ok && pci_is_vga_ioport_range(start, end))
2494 			ok = (sc->bridgectl & PCIB_BCR_VGA_ENABLE) ? 1 : 0;
2495 
2496 		if ((sc->flags & PCIB_SUBTRACTIVE) == 0) {
2497 			if (!ok) {
2498 				if (start < sc->iobase)
2499 					start = sc->iobase;
2500 				if (end > sc->iolimit)
2501 					end = sc->iolimit;
2502 				if (start < end)
2503 					ok = 1;
2504 			}
2505 		} else {
2506 			ok = 1;
2507 #if 0
2508 			/*
2509 			 * If we overlap with the subtractive range, then
2510 			 * pick the upper range to use.
2511 			 */
2512 			if (start < sc->iolimit && end > sc->iobase)
2513 				start = sc->iolimit + 1;
2514 #endif
2515 		}
2516 		if (end < start) {
2517 			device_printf(dev, "ioport: end (%jx) < start (%jx)\n",
2518 			    end, start);
2519 			start = 0;
2520 			end = 0;
2521 			ok = 0;
2522 		}
2523 		if (!ok) {
2524 			device_printf(dev, "%s%srequested unsupported I/O "
2525 			    "range 0x%jx-0x%jx (decoding 0x%x-0x%x)\n",
2526 			    name, suffix, start, end, sc->iobase, sc->iolimit);
2527 			return (NULL);
2528 		}
2529 		if (bootverbose)
2530 			device_printf(dev,
2531 			    "%s%srequested I/O range 0x%jx-0x%jx: in range\n",
2532 			    name, suffix, start, end);
2533 		break;
2534 
2535 	case SYS_RES_MEMORY:
2536 		ok = 0;
2537 		if (pcib_is_nonprefetch_open(sc))
2538 			ok = ok || (start >= sc->membase && end <= sc->memlimit);
2539 		if (pcib_is_prefetch_open(sc))
2540 			ok = ok || (start >= sc->pmembase && end <= sc->pmemlimit);
2541 
2542 		/*
2543 		 * Make sure we allow access to VGA memory addresses when the
2544 		 * bridge has the "VGA Enable" bit set.
2545 		 */
2546 		if (!ok && pci_is_vga_memory_range(start, end))
2547 			ok = (sc->bridgectl & PCIB_BCR_VGA_ENABLE) ? 1 : 0;
2548 
2549 		if ((sc->flags & PCIB_SUBTRACTIVE) == 0) {
2550 			if (!ok) {
2551 				ok = 1;
2552 				if (flags & RF_PREFETCHABLE) {
2553 					if (pcib_is_prefetch_open(sc)) {
2554 						if (start < sc->pmembase)
2555 							start = sc->pmembase;
2556 						if (end > sc->pmemlimit)
2557 							end = sc->pmemlimit;
2558 					} else {
2559 						ok = 0;
2560 					}
2561 				} else {	/* non-prefetchable */
2562 					if (pcib_is_nonprefetch_open(sc)) {
2563 						if (start < sc->membase)
2564 							start = sc->membase;
2565 						if (end > sc->memlimit)
2566 							end = sc->memlimit;
2567 					} else {
2568 						ok = 0;
2569 					}
2570 				}
2571 			}
2572 		} else if (!ok) {
2573 			ok = 1;	/* subtractive bridge: always ok */
2574 #if 0
2575 			if (pcib_is_nonprefetch_open(sc)) {
2576 				if (start < sc->memlimit && end > sc->membase)
2577 					start = sc->memlimit + 1;
2578 			}
2579 			if (pcib_is_prefetch_open(sc)) {
2580 				if (start < sc->pmemlimit && end > sc->pmembase)
2581 					start = sc->pmemlimit + 1;
2582 			}
2583 #endif
2584 		}
2585 		if (end < start) {
2586 			device_printf(dev, "memory: end (%jx) < start (%jx)\n",
2587 			    end, start);
2588 			start = 0;
2589 			end = 0;
2590 			ok = 0;
2591 		}
2592 		if (!ok && bootverbose)
2593 			device_printf(dev,
2594 			    "%s%srequested unsupported memory range %#jx-%#jx "
2595 			    "(decoding %#jx-%#jx, %#jx-%#jx)\n",
2596 			    name, suffix, start, end,
2597 			    (uintmax_t)sc->membase, (uintmax_t)sc->memlimit,
2598 			    (uintmax_t)sc->pmembase, (uintmax_t)sc->pmemlimit);
2599 		if (!ok)
2600 			return (NULL);
2601 		if (bootverbose)
2602 			device_printf(dev,"%s%srequested memory range "
2603 			    "0x%jx-0x%jx: good\n",
2604 			    name, suffix, start, end);
2605 		break;
2606 
2607 	default:
2608 		break;
2609 	}
2610 	/*
2611 	 * Bridge is OK decoding this resource, so pass it up.
2612 	 */
2613 	return (bus_generic_alloc_resource(dev, child, type, rid, start, end,
2614 	    count, flags));
2615 }
2616 #endif
2617 
2618 /*
2619  * If ARI is enabled on this downstream port, translate the function number
2620  * to the non-ARI slot/function.  The downstream port will convert it back in
2621  * hardware.  If ARI is not enabled slot and func are not modified.
2622  */
2623 static __inline void
pcib_xlate_ari(device_t pcib,int bus,int * slot,int * func)2624 pcib_xlate_ari(device_t pcib, int bus, int *slot, int *func)
2625 {
2626 	struct pcib_softc *sc;
2627 	int ari_func;
2628 
2629 	sc = device_get_softc(pcib);
2630 	ari_func = *func;
2631 
2632 	if (sc->flags & PCIB_ENABLE_ARI) {
2633 		KASSERT(*slot == 0,
2634 		    ("Non-zero slot number with ARI enabled!"));
2635 		*slot = PCIE_ARI_SLOT(ari_func);
2636 		*func = PCIE_ARI_FUNC(ari_func);
2637 	}
2638 }
2639 
2640 static void
pcib_enable_ari(struct pcib_softc * sc,uint32_t pcie_pos)2641 pcib_enable_ari(struct pcib_softc *sc, uint32_t pcie_pos)
2642 {
2643 	uint32_t ctl2;
2644 
2645 	ctl2 = pci_read_config(sc->dev, pcie_pos + PCIER_DEVICE_CTL2, 4);
2646 	ctl2 |= PCIEM_CTL2_ARI;
2647 	pci_write_config(sc->dev, pcie_pos + PCIER_DEVICE_CTL2, ctl2, 4);
2648 
2649 	sc->flags |= PCIB_ENABLE_ARI;
2650 }
2651 
2652 /*
2653  * PCIB interface.
2654  */
2655 int
pcib_maxslots(device_t dev)2656 pcib_maxslots(device_t dev)
2657 {
2658 #if !defined(__amd64__) && !defined(__i386__)
2659 	uint32_t pcie_pos;
2660 	uint16_t val;
2661 
2662 	/*
2663 	 * If this is a PCIe rootport or downstream switch port, there's only
2664 	 * one slot permitted.
2665 	 */
2666 	if (pci_find_cap(dev, PCIY_EXPRESS, &pcie_pos) == 0) {
2667 		val = pci_read_config(dev, pcie_pos + PCIER_FLAGS, 2);
2668 		val &= PCIEM_FLAGS_TYPE;
2669 		if (val == PCIEM_TYPE_ROOT_PORT ||
2670 		    val == PCIEM_TYPE_DOWNSTREAM_PORT)
2671 			return (0);
2672 	}
2673 #endif
2674 	return (PCI_SLOTMAX);
2675 }
2676 
2677 static int
pcib_ari_maxslots(device_t dev)2678 pcib_ari_maxslots(device_t dev)
2679 {
2680 	struct pcib_softc *sc;
2681 
2682 	sc = device_get_softc(dev);
2683 
2684 	if (sc->flags & PCIB_ENABLE_ARI)
2685 		return (PCIE_ARI_SLOTMAX);
2686 	else
2687 		return (pcib_maxslots(dev));
2688 }
2689 
2690 static int
pcib_ari_maxfuncs(device_t dev)2691 pcib_ari_maxfuncs(device_t dev)
2692 {
2693 	struct pcib_softc *sc;
2694 
2695 	sc = device_get_softc(dev);
2696 
2697 	if (sc->flags & PCIB_ENABLE_ARI)
2698 		return (PCIE_ARI_FUNCMAX);
2699 	else
2700 		return (PCI_FUNCMAX);
2701 }
2702 
2703 static void
pcib_ari_decode_rid(device_t pcib,uint16_t rid,int * bus,int * slot,int * func)2704 pcib_ari_decode_rid(device_t pcib, uint16_t rid, int *bus, int *slot,
2705     int *func)
2706 {
2707 	struct pcib_softc *sc;
2708 
2709 	sc = device_get_softc(pcib);
2710 
2711 	*bus = PCI_RID2BUS(rid);
2712 	if (sc->flags & PCIB_ENABLE_ARI) {
2713 		*slot = PCIE_ARI_RID2SLOT(rid);
2714 		*func = PCIE_ARI_RID2FUNC(rid);
2715 	} else {
2716 		*slot = PCI_RID2SLOT(rid);
2717 		*func = PCI_RID2FUNC(rid);
2718 	}
2719 }
2720 
2721 /*
2722  * Since we are a child of a PCI bus, its parent must support the pcib interface.
2723  */
2724 static uint32_t
pcib_read_config(device_t dev,u_int b,u_int s,u_int f,u_int reg,int width)2725 pcib_read_config(device_t dev, u_int b, u_int s, u_int f, u_int reg, int width)
2726 {
2727 #ifdef PCI_HP
2728 	struct pcib_softc *sc;
2729 
2730 	sc = device_get_softc(dev);
2731 	if (!pcib_present(sc)) {
2732 		switch (width) {
2733 		case 2:
2734 			return (0xffff);
2735 		case 1:
2736 			return (0xff);
2737 		default:
2738 			return (0xffffffff);
2739 		}
2740 	}
2741 #endif
2742 	pcib_xlate_ari(dev, b, &s, &f);
2743 	return(PCIB_READ_CONFIG(device_get_parent(device_get_parent(dev)), b, s,
2744 	    f, reg, width));
2745 }
2746 
2747 static void
pcib_write_config(device_t dev,u_int b,u_int s,u_int f,u_int reg,uint32_t val,int width)2748 pcib_write_config(device_t dev, u_int b, u_int s, u_int f, u_int reg, uint32_t val, int width)
2749 {
2750 #ifdef PCI_HP
2751 	struct pcib_softc *sc;
2752 
2753 	sc = device_get_softc(dev);
2754 	if (!pcib_present(sc))
2755 		return;
2756 #endif
2757 	pcib_xlate_ari(dev, b, &s, &f);
2758 	PCIB_WRITE_CONFIG(device_get_parent(device_get_parent(dev)), b, s, f,
2759 	    reg, val, width);
2760 }
2761 
2762 /*
2763  * Route an interrupt across a PCI bridge.
2764  */
2765 int
pcib_route_interrupt(device_t pcib,device_t dev,int pin)2766 pcib_route_interrupt(device_t pcib, device_t dev, int pin)
2767 {
2768     device_t	bus;
2769     int		parent_intpin;
2770     int		intnum;
2771 
2772     /*
2773      *
2774      * The PCI standard defines a swizzle of the child-side device/intpin to
2775      * the parent-side intpin as follows.
2776      *
2777      * device = device on child bus
2778      * child_intpin = intpin on child bus slot (0-3)
2779      * parent_intpin = intpin on parent bus slot (0-3)
2780      *
2781      * parent_intpin = (device + child_intpin) % 4
2782      */
2783     parent_intpin = (pci_get_slot(dev) + (pin - 1)) % 4;
2784 
2785     /*
2786      * Our parent is a PCI bus.  Its parent must export the pcib interface
2787      * which includes the ability to route interrupts.
2788      */
2789     bus = device_get_parent(pcib);
2790     intnum = PCIB_ROUTE_INTERRUPT(device_get_parent(bus), pcib, parent_intpin + 1);
2791     if (PCI_INTERRUPT_VALID(intnum) && bootverbose) {
2792 	device_printf(pcib, "slot %d INT%c is routed to irq %d\n",
2793 	    pci_get_slot(dev), 'A' + pin - 1, intnum);
2794     }
2795     return(intnum);
2796 }
2797 
2798 /* Pass request to alloc MSI/MSI-X messages up to the parent bridge. */
2799 int
pcib_alloc_msi(device_t pcib,device_t dev,int count,int maxcount,int * irqs)2800 pcib_alloc_msi(device_t pcib, device_t dev, int count, int maxcount, int *irqs)
2801 {
2802 	struct pcib_softc *sc = device_get_softc(pcib);
2803 	device_t bus;
2804 
2805 	if (sc->flags & PCIB_DISABLE_MSI)
2806 		return (ENXIO);
2807 	bus = device_get_parent(pcib);
2808 	return (PCIB_ALLOC_MSI(device_get_parent(bus), dev, count, maxcount,
2809 	    irqs));
2810 }
2811 
2812 /* Pass request to release MSI/MSI-X messages up to the parent bridge. */
2813 int
pcib_release_msi(device_t pcib,device_t dev,int count,int * irqs)2814 pcib_release_msi(device_t pcib, device_t dev, int count, int *irqs)
2815 {
2816 	device_t bus;
2817 
2818 	bus = device_get_parent(pcib);
2819 	return (PCIB_RELEASE_MSI(device_get_parent(bus), dev, count, irqs));
2820 }
2821 
2822 /* Pass request to alloc an MSI-X message up to the parent bridge. */
2823 int
pcib_alloc_msix(device_t pcib,device_t dev,int * irq)2824 pcib_alloc_msix(device_t pcib, device_t dev, int *irq)
2825 {
2826 	struct pcib_softc *sc = device_get_softc(pcib);
2827 	device_t bus;
2828 
2829 	if (sc->flags & PCIB_DISABLE_MSIX)
2830 		return (ENXIO);
2831 	bus = device_get_parent(pcib);
2832 	return (PCIB_ALLOC_MSIX(device_get_parent(bus), dev, irq));
2833 }
2834 
2835 /* Pass request to release an MSI-X message up to the parent bridge. */
2836 int
pcib_release_msix(device_t pcib,device_t dev,int irq)2837 pcib_release_msix(device_t pcib, device_t dev, int irq)
2838 {
2839 	device_t bus;
2840 
2841 	bus = device_get_parent(pcib);
2842 	return (PCIB_RELEASE_MSIX(device_get_parent(bus), dev, irq));
2843 }
2844 
2845 /* Pass request to map MSI/MSI-X message up to parent bridge. */
2846 int
pcib_map_msi(device_t pcib,device_t dev,int irq,uint64_t * addr,uint32_t * data)2847 pcib_map_msi(device_t pcib, device_t dev, int irq, uint64_t *addr,
2848     uint32_t *data)
2849 {
2850 	device_t bus;
2851 	int error;
2852 
2853 	bus = device_get_parent(pcib);
2854 	error = PCIB_MAP_MSI(device_get_parent(bus), dev, irq, addr, data);
2855 	if (error)
2856 		return (error);
2857 
2858 	pci_ht_map_msi(pcib, *addr);
2859 	return (0);
2860 }
2861 
2862 /* Pass request for device power state up to parent bridge. */
2863 int
pcib_power_for_sleep(device_t pcib,device_t dev,int * pstate)2864 pcib_power_for_sleep(device_t pcib, device_t dev, int *pstate)
2865 {
2866 	device_t bus;
2867 
2868 	bus = device_get_parent(pcib);
2869 	return (PCIB_POWER_FOR_SLEEP(bus, dev, pstate));
2870 }
2871 
2872 static int
pcib_ari_enabled(device_t pcib)2873 pcib_ari_enabled(device_t pcib)
2874 {
2875 	struct pcib_softc *sc;
2876 
2877 	sc = device_get_softc(pcib);
2878 
2879 	return ((sc->flags & PCIB_ENABLE_ARI) != 0);
2880 }
2881 
2882 static int
pcib_ari_get_id(device_t pcib,device_t dev,enum pci_id_type type,uintptr_t * id)2883 pcib_ari_get_id(device_t pcib, device_t dev, enum pci_id_type type,
2884     uintptr_t *id)
2885 {
2886 	struct pcib_softc *sc;
2887 	device_t bus_dev;
2888 	uint8_t bus, slot, func;
2889 
2890 	if (type != PCI_ID_RID) {
2891 		bus_dev = device_get_parent(pcib);
2892 		return (PCIB_GET_ID(device_get_parent(bus_dev), dev, type, id));
2893 	}
2894 
2895 	sc = device_get_softc(pcib);
2896 
2897 	if (sc->flags & PCIB_ENABLE_ARI) {
2898 		bus = pci_get_bus(dev);
2899 		func = pci_get_function(dev);
2900 
2901 		*id = (PCI_ARI_RID(bus, func));
2902 	} else {
2903 		bus = pci_get_bus(dev);
2904 		slot = pci_get_slot(dev);
2905 		func = pci_get_function(dev);
2906 
2907 		*id = (PCI_RID(bus, slot, func));
2908 	}
2909 
2910 	return (0);
2911 }
2912 
2913 /*
2914  * Check that the downstream port (pcib) and the endpoint device (dev) both
2915  * support ARI.  If so, enable it and return 0, otherwise return an error.
2916  */
2917 static int
pcib_try_enable_ari(device_t pcib,device_t dev)2918 pcib_try_enable_ari(device_t pcib, device_t dev)
2919 {
2920 	struct pcib_softc *sc;
2921 	int error;
2922 	uint32_t cap2;
2923 	int ari_cap_off;
2924 	uint32_t ari_ver;
2925 	uint32_t pcie_pos;
2926 
2927 	sc = device_get_softc(pcib);
2928 
2929 	/*
2930 	 * ARI is controlled in a register in the PCIe capability structure.
2931 	 * If the downstream port does not have the PCIe capability structure
2932 	 * then it does not support ARI.
2933 	 */
2934 	error = pci_find_cap(pcib, PCIY_EXPRESS, &pcie_pos);
2935 	if (error != 0)
2936 		return (ENODEV);
2937 
2938 	/* Check that the PCIe port advertises ARI support. */
2939 	cap2 = pci_read_config(pcib, pcie_pos + PCIER_DEVICE_CAP2, 4);
2940 	if (!(cap2 & PCIEM_CAP2_ARI))
2941 		return (ENODEV);
2942 
2943 	/*
2944 	 * Check that the endpoint device advertises ARI support via the ARI
2945 	 * extended capability structure.
2946 	 */
2947 	error = pci_find_extcap(dev, PCIZ_ARI, &ari_cap_off);
2948 	if (error != 0)
2949 		return (ENODEV);
2950 
2951 	/*
2952 	 * Finally, check that the endpoint device supports the same version
2953 	 * of ARI that we do.
2954 	 */
2955 	ari_ver = pci_read_config(dev, ari_cap_off, 4);
2956 	if (PCI_EXTCAP_VER(ari_ver) != PCIB_SUPPORTED_ARI_VER) {
2957 		if (bootverbose)
2958 			device_printf(pcib,
2959 			    "Unsupported version of ARI (%d) detected\n",
2960 			    PCI_EXTCAP_VER(ari_ver));
2961 
2962 		return (ENXIO);
2963 	}
2964 
2965 	pcib_enable_ari(sc, pcie_pos);
2966 
2967 	return (0);
2968 }
2969 
2970 int
pcib_request_feature_allow(device_t pcib,device_t dev,enum pci_feature feature)2971 pcib_request_feature_allow(device_t pcib, device_t dev,
2972     enum pci_feature feature)
2973 {
2974 	/*
2975 	 * No host firmware we have to negotiate with, so we allow
2976 	 * every valid feature requested.
2977 	 */
2978 	switch (feature) {
2979 	case PCI_FEATURE_AER:
2980 	case PCI_FEATURE_HP:
2981 		break;
2982 	default:
2983 		return (EINVAL);
2984 	}
2985 
2986 	return (0);
2987 }
2988 
2989 int
pcib_request_feature(device_t dev,enum pci_feature feature)2990 pcib_request_feature(device_t dev, enum pci_feature feature)
2991 {
2992 
2993 	/*
2994 	 * Invoke PCIB_REQUEST_FEATURE of this bridge first in case
2995 	 * the firmware overrides the method of PCI-PCI bridges.
2996 	 */
2997 	return (PCIB_REQUEST_FEATURE(dev, dev, feature));
2998 }
2999 
3000 /*
3001  * Pass the request to use this PCI feature up the tree. Either there's a
3002  * firmware like ACPI that's using this feature that will approve (or deny) the
3003  * request to take it over, or the platform has no such firmware, in which case
3004  * the request will be approved. If the request is approved, the OS is expected
3005  * to make use of the feature or render it harmless.
3006  */
3007 static int
pcib_request_feature_default(device_t pcib,device_t dev,enum pci_feature feature)3008 pcib_request_feature_default(device_t pcib, device_t dev,
3009     enum pci_feature feature)
3010 {
3011 	device_t bus;
3012 
3013 	/*
3014 	 * Our parent is necessarily a pci bus. Its parent will either be
3015 	 * another pci bridge (which passes it up) or a host bridge that can
3016 	 * approve or reject the request.
3017 	 */
3018 	bus = device_get_parent(pcib);
3019 	return (PCIB_REQUEST_FEATURE(device_get_parent(bus), dev, feature));
3020 }
3021 
3022 static int
pcib_reset_child(device_t dev,device_t child,int flags)3023 pcib_reset_child(device_t dev, device_t child, int flags)
3024 {
3025 	struct pci_devinfo *pdinfo;
3026 	int error;
3027 
3028 	error = 0;
3029 	if (dev == NULL || device_get_parent(child) != dev)
3030 		goto out;
3031 	error = ENXIO;
3032 	if (device_get_devclass(child) != devclass_find("pci"))
3033 		goto out;
3034 	pdinfo = device_get_ivars(dev);
3035 	if (pdinfo->cfg.pcie.pcie_location != 0 &&
3036 	    (pdinfo->cfg.pcie.pcie_type == PCIEM_TYPE_DOWNSTREAM_PORT ||
3037 	    pdinfo->cfg.pcie.pcie_type == PCIEM_TYPE_ROOT_PORT)) {
3038 		error = bus_helper_reset_prepare(child, flags);
3039 		if (error == 0) {
3040 			error = pcie_link_reset(dev,
3041 			    pdinfo->cfg.pcie.pcie_location);
3042 			/* XXXKIB call _post even if error != 0 ? */
3043 			bus_helper_reset_post(child, flags);
3044 		}
3045 	}
3046 out:
3047 	return (error);
3048 }
3049