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