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