xref: /freebsd/sys/dev/pccbb/pccbb.c (revision 2357939bc239bd5334a169b62313806178dd8f30)
1 /*
2  * Copyright (c) 2002-2004 M. Warner Losh.
3  * Copyright (c) 2000-2001 Jonathan Chen.
4  * All rights reserved.
5  *
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions
8  * are met:
9  * 1. Redistributions of source code must retain the above copyright
10  *    notice, this list of conditions, and the following disclaimer,
11  *    without modification, immediately at the beginning of the file.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in
14  *    the documentation and/or other materials provided with the
15  *    distribution.
16  *
17  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
18  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20  * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR
21  * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
23  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
24  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
26  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
27  * SUCH DAMAGE.
28  */
29 
30 /*
31  * Copyright (c) 1998, 1999 and 2000
32  *      HAYAKAWA Koichi.  All rights reserved.
33  *
34  * Redistribution and use in source and binary forms, with or without
35  * modification, are permitted provided that the following conditions
36  * are met:
37  * 1. Redistributions of source code must retain the above copyright
38  *    notice, this list of conditions and the following disclaimer.
39  * 2. Redistributions in binary form must reproduce the above copyright
40  *    notice, this list of conditions and the following disclaimer in the
41  *    documentation and/or other materials provided with the distribution.
42  * 3. All advertising materials mentioning features or use of this software
43  *    must display the following acknowledgement:
44  *	This product includes software developed by HAYAKAWA Koichi.
45  * 4. The name of the author may not be used to endorse or promote products
46  *    derived from this software without specific prior written permission.
47  *
48  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
49  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
50  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
51  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
52  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
53  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
54  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
55  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
56  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
57  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
58  */
59 
60 /*
61  * Driver for PCI to CardBus Bridge chips
62  *
63  * References:
64  *  TI Datasheets:
65  *   http://www-s.ti.com/cgi-bin/sc/generic2.cgi?family=PCI+CARDBUS+CONTROLLERS
66  *
67  * Written by Jonathan Chen <jon@freebsd.org>
68  * The author would like to acknowledge:
69  *  * HAYAKAWA Koichi: Author of the NetBSD code for the same thing
70  *  * Warner Losh: Newbus/newcard guru and author of the pccard side of things
71  *  * YAMAMOTO Shigeru: Author of another FreeBSD cardbus driver
72  *  * David Cross: Author of the initial ugly hack for a specific cardbus card
73  */
74 
75 #include <sys/cdefs.h>
76 __FBSDID("$FreeBSD$");
77 
78 #include <sys/param.h>
79 #include <sys/systm.h>
80 #include <sys/proc.h>
81 #include <sys/condvar.h>
82 #include <sys/errno.h>
83 #include <sys/kernel.h>
84 #include <sys/lock.h>
85 #include <sys/malloc.h>
86 #include <sys/mutex.h>
87 #include <sys/sysctl.h>
88 #include <sys/kthread.h>
89 #include <sys/bus.h>
90 #include <machine/bus.h>
91 #include <sys/rman.h>
92 #include <machine/resource.h>
93 
94 #include <dev/pci/pcireg.h>
95 #include <dev/pci/pcivar.h>
96 #include <machine/clock.h>
97 
98 #include <dev/pccard/pccardreg.h>
99 #include <dev/pccard/pccardvar.h>
100 
101 #include <dev/exca/excareg.h>
102 #include <dev/exca/excavar.h>
103 
104 #include <dev/pccbb/pccbbreg.h>
105 #include <dev/pccbb/pccbbvar.h>
106 
107 #include "power_if.h"
108 #include "card_if.h"
109 #include "pcib_if.h"
110 
111 #define	DPRINTF(x) do { if (cbb_debug) printf x; } while (0)
112 #define	DEVPRINTF(x) do { if (cbb_debug) device_printf x; } while (0)
113 
114 #define	PCI_MASK_CONFIG(DEV,REG,MASK,SIZE)				\
115 	pci_write_config(DEV, REG, pci_read_config(DEV, REG, SIZE) MASK, SIZE)
116 #define	PCI_MASK2_CONFIG(DEV,REG,MASK1,MASK2,SIZE)			\
117 	pci_write_config(DEV, REG, (					\
118 		pci_read_config(DEV, REG, SIZE) MASK1) MASK2, SIZE)
119 
120 #define CBB_CARD_PRESENT(s) ((s & CBB_STATE_CD) == 0)
121 
122 #define CBB_START_MEM	0x88000000
123 #define CBB_START_32_IO 0x1000
124 #define CBB_START_16_IO 0x100
125 
126 struct yenta_chipinfo {
127 	uint32_t yc_id;
128 	const	char *yc_name;
129 	int	yc_chiptype;
130 } yc_chipsets[] = {
131 	/* Texas Instruments chips */
132 	{PCIC_ID_TI1031, "TI1031 PCI-PC Card Bridge", CB_TI113X},
133 	{PCIC_ID_TI1130, "TI1130 PCI-CardBus Bridge", CB_TI113X},
134 	{PCIC_ID_TI1131, "TI1131 PCI-CardBus Bridge", CB_TI113X},
135 
136 	{PCIC_ID_TI1210, "TI1210 PCI-CardBus Bridge", CB_TI12XX},
137 	{PCIC_ID_TI1211, "TI1211 PCI-CardBus Bridge", CB_TI12XX},
138 	{PCIC_ID_TI1220, "TI1220 PCI-CardBus Bridge", CB_TI12XX},
139 	{PCIC_ID_TI1221, "TI1221 PCI-CardBus Bridge", CB_TI12XX},
140 	{PCIC_ID_TI1225, "TI1225 PCI-CardBus Bridge", CB_TI12XX},
141 	{PCIC_ID_TI1250, "TI1250 PCI-CardBus Bridge", CB_TI125X},
142 	{PCIC_ID_TI1251, "TI1251 PCI-CardBus Bridge", CB_TI125X},
143 	{PCIC_ID_TI1251B,"TI1251B PCI-CardBus Bridge",CB_TI125X},
144 	{PCIC_ID_TI1260, "TI1260 PCI-CardBus Bridge", CB_TI12XX},
145 	{PCIC_ID_TI1260B,"TI1260B PCI-CardBus Bridge",CB_TI12XX},
146 	{PCIC_ID_TI1410, "TI1410 PCI-CardBus Bridge", CB_TI12XX},
147 	{PCIC_ID_TI1420, "TI1420 PCI-CardBus Bridge", CB_TI12XX},
148 	{PCIC_ID_TI1421, "TI1421 PCI-CardBus Bridge", CB_TI12XX},
149 	{PCIC_ID_TI1450, "TI1450 PCI-CardBus Bridge", CB_TI125X}, /*SIC!*/
150 	{PCIC_ID_TI1451, "TI1451 PCI-CardBus Bridge", CB_TI12XX},
151 	{PCIC_ID_TI1510, "TI1510 PCI-CardBus Bridge", CB_TI12XX},
152 	{PCIC_ID_TI1520, "TI1520 PCI-CardBus Bridge", CB_TI12XX},
153 	{PCIC_ID_TI4410, "TI4410 PCI-CardBus Bridge", CB_TI12XX},
154 	{PCIC_ID_TI4450, "TI4450 PCI-CardBus Bridge", CB_TI12XX},
155 	{PCIC_ID_TI4451, "TI4451 PCI-CardBus Bridge", CB_TI12XX},
156 	{PCIC_ID_TI4510, "TI4510 PCI-CardBus Bridge", CB_TI12XX},
157 
158 	/* ENE */
159 	{PCIC_ID_ENE_CB710, "ENE CB710 PCI-CardBus Bridge", CB_TI12XX},
160 	{PCIC_ID_ENE_CB720, "ENE CB720 PCI-CardBus Bridge", CB_TI12XX},
161 	{PCIC_ID_ENE_CB1211, "ENE CB1211 PCI-CardBus Bridge", CB_TI12XX},
162 	{PCIC_ID_ENE_CB1225, "ENE CB1225 PCI-CardBus Bridge", CB_TI12XX},
163 	{PCIC_ID_ENE_CB1410, "ENE CB1410 PCI-CardBus Bridge", CB_TI12XX},
164 	{PCIC_ID_ENE_CB1420, "ENE CB1420 PCI-CardBus Bridge", CB_TI12XX},
165 
166 	/* Ricoh chips */
167 	{PCIC_ID_RICOH_RL5C465, "RF5C465 PCI-CardBus Bridge", CB_RF5C46X},
168 	{PCIC_ID_RICOH_RL5C466, "RF5C466 PCI-CardBus Bridge", CB_RF5C46X},
169 	{PCIC_ID_RICOH_RL5C475, "RF5C475 PCI-CardBus Bridge", CB_RF5C47X},
170 	{PCIC_ID_RICOH_RL5C476, "RF5C476 PCI-CardBus Bridge", CB_RF5C47X},
171 	{PCIC_ID_RICOH_RL5C477, "RF5C477 PCI-CardBus Bridge", CB_RF5C47X},
172 	{PCIC_ID_RICOH_RL5C478, "RF5C478 PCI-CardBus Bridge", CB_RF5C47X},
173 
174 	/* Toshiba products */
175 	{PCIC_ID_TOPIC95, "ToPIC95 PCI-CardBus Bridge", CB_TOPIC95},
176 	{PCIC_ID_TOPIC95B, "ToPIC95B PCI-CardBus Bridge", CB_TOPIC95},
177 	{PCIC_ID_TOPIC97, "ToPIC97 PCI-CardBus Bridge", CB_TOPIC97},
178 	{PCIC_ID_TOPIC100, "ToPIC100 PCI-CardBus Bridge", CB_TOPIC97},
179 
180 	/* Cirrus Logic */
181 	{PCIC_ID_CLPD6832, "CLPD6832 PCI-CardBus Bridge", CB_CIRRUS},
182 	{PCIC_ID_CLPD6833, "CLPD6833 PCI-CardBus Bridge", CB_CIRRUS},
183 	{PCIC_ID_CLPD6834, "CLPD6834 PCI-CardBus Bridge", CB_CIRRUS},
184 
185 	/* 02Micro */
186 	{PCIC_ID_OZ6832, "O2Micro OZ6832/6833 PCI-CardBus Bridge", CB_O2MICRO},
187 	{PCIC_ID_OZ6860, "O2Micro OZ6836/6860 PCI-CardBus Bridge", CB_O2MICRO},
188 	{PCIC_ID_OZ6872, "O2Micro OZ6812/6872 PCI-CardBus Bridge", CB_O2MICRO},
189 	{PCIC_ID_OZ6912, "O2Micro OZ6912/6972 PCI-CardBus Bridge", CB_O2MICRO},
190 	{PCIC_ID_OZ6922, "O2Micro OZ6922 PCI-CardBus Bridge", CB_O2MICRO},
191 	{PCIC_ID_OZ6933, "O2Micro OZ6933 PCI-CardBus Bridge", CB_O2MICRO},
192 	{PCIC_ID_OZ711E1, "O2Micro OZ711E1 PCI-CardBus Bridge", CB_O2MICRO},
193 
194 	/* sentinel */
195 	{0 /* null id */, "unknown", CB_UNKNOWN},
196 };
197 
198 /* sysctl vars */
199 SYSCTL_NODE(_hw, OID_AUTO, cbb, CTLFLAG_RD, 0, "CBB parameters");
200 
201 /* There's no way to say TUNEABLE_LONG to get the right types */
202 u_long cbb_start_mem = CBB_START_MEM;
203 TUNABLE_INT("hw.cbb.start_memory", (int *)&cbb_start_mem);
204 SYSCTL_ULONG(_hw_cbb, OID_AUTO, start_memory, CTLFLAG_RW,
205     &cbb_start_mem, CBB_START_MEM,
206     "Starting address for memory allocations");
207 
208 u_long cbb_start_16_io = CBB_START_16_IO;
209 TUNABLE_INT("hw.cbb.start_16_io", (int *)&cbb_start_16_io);
210 SYSCTL_ULONG(_hw_cbb, OID_AUTO, start_16_io, CTLFLAG_RW,
211     &cbb_start_16_io, CBB_START_16_IO,
212     "Starting ioport for 16-bit cards");
213 
214 u_long cbb_start_32_io = CBB_START_32_IO;
215 TUNABLE_INT("hw.cbb.start_32_io", (int *)&cbb_start_32_io);
216 SYSCTL_ULONG(_hw_cbb, OID_AUTO, start_32_io, CTLFLAG_RW,
217     &cbb_start_32_io, CBB_START_32_IO,
218     "Starting ioport for 32-bit cards");
219 
220 int cbb_debug = 0;
221 TUNABLE_INT("hw.cbb.debug", &cbb_debug);
222 SYSCTL_ULONG(_hw_cbb, OID_AUTO, debug, CTLFLAG_RW, &cbb_debug, 0,
223     "Verbose cardbus bridge debugging");
224 
225 static int	cbb_chipset(uint32_t pci_id, const char **namep);
226 static int	cbb_probe(device_t brdev);
227 static void	cbb_chipinit(struct cbb_softc *sc);
228 static int	cbb_attach(device_t brdev);
229 static int	cbb_detach(device_t brdev);
230 static int	cbb_shutdown(device_t brdev);
231 static void	cbb_driver_added(device_t brdev, driver_t *driver);
232 static void	cbb_child_detached(device_t brdev, device_t child);
233 static void	cbb_event_thread(void *arg);
234 static void	cbb_insert(struct cbb_softc *sc);
235 static void	cbb_removal(struct cbb_softc *sc);
236 static void	cbb_intr(void *arg);
237 static int	cbb_detect_voltage(device_t brdev);
238 static int	cbb_power(device_t brdev, int volts);
239 static void	cbb_cardbus_reset(device_t brdev);
240 static int	cbb_cardbus_power_enable_socket(device_t brdev,
241 		    device_t child);
242 static void	cbb_cardbus_power_disable_socket(device_t brdev,
243 		    device_t child);
244 static int	cbb_cardbus_io_open(device_t brdev, int win, uint32_t start,
245 		    uint32_t end);
246 static int	cbb_cardbus_mem_open(device_t brdev, int win,
247 		    uint32_t start, uint32_t end);
248 static void	cbb_cardbus_auto_open(struct cbb_softc *sc, int type);
249 static int	cbb_cardbus_activate_resource(device_t brdev, device_t child,
250 		    int type, int rid, struct resource *res);
251 static int	cbb_cardbus_deactivate_resource(device_t brdev,
252 		    device_t child, int type, int rid, struct resource *res);
253 static struct resource	*cbb_cardbus_alloc_resource(device_t brdev,
254 		    device_t child, int type, int *rid, u_long start,
255 		    u_long end, u_long count, u_int flags);
256 static int	cbb_cardbus_release_resource(device_t brdev, device_t child,
257 		    int type, int rid, struct resource *res);
258 static int	cbb_power_enable_socket(device_t brdev, device_t child);
259 static void	cbb_power_disable_socket(device_t brdev, device_t child);
260 static int	cbb_activate_resource(device_t brdev, device_t child,
261 		    int type, int rid, struct resource *r);
262 static int	cbb_deactivate_resource(device_t brdev, device_t child,
263 		    int type, int rid, struct resource *r);
264 static struct resource	*cbb_alloc_resource(device_t brdev, device_t child,
265 		    int type, int *rid, u_long start, u_long end, u_long count,
266 		    u_int flags);
267 static int	cbb_release_resource(device_t brdev, device_t child,
268 		    int type, int rid, struct resource *r);
269 static int	cbb_read_ivar(device_t brdev, device_t child, int which,
270 		    uintptr_t *result);
271 static int	cbb_write_ivar(device_t brdev, device_t child, int which,
272 		    uintptr_t value);
273 static int	cbb_maxslots(device_t brdev);
274 static uint32_t cbb_read_config(device_t brdev, int b, int s, int f,
275 		    int reg, int width);
276 static void	cbb_write_config(device_t brdev, int b, int s, int f,
277 		    int reg, uint32_t val, int width);
278 
279 /*
280  */
281 static __inline void
282 cbb_set(struct cbb_softc *sc, uint32_t reg, uint32_t val)
283 {
284 	bus_space_write_4(sc->bst, sc->bsh, reg, val);
285 }
286 
287 static __inline uint32_t
288 cbb_get(struct cbb_softc *sc, uint32_t reg)
289 {
290 	return (bus_space_read_4(sc->bst, sc->bsh, reg));
291 }
292 
293 static __inline void
294 cbb_setb(struct cbb_softc *sc, uint32_t reg, uint32_t bits)
295 {
296 	cbb_set(sc, reg, cbb_get(sc, reg) | bits);
297 }
298 
299 static __inline void
300 cbb_clrb(struct cbb_softc *sc, uint32_t reg, uint32_t bits)
301 {
302 	cbb_set(sc, reg, cbb_get(sc, reg) & ~bits);
303 }
304 
305 static void
306 cbb_remove_res(struct cbb_softc *sc, struct resource *res)
307 {
308 	struct cbb_reslist *rle;
309 
310 	SLIST_FOREACH(rle, &sc->rl, link) {
311 		if (rle->res == res) {
312 			SLIST_REMOVE(&sc->rl, rle, cbb_reslist, link);
313 			free(rle, M_DEVBUF);
314 			return;
315 		}
316 	}
317 }
318 
319 static struct resource *
320 cbb_find_res(struct cbb_softc *sc, int type, int rid)
321 {
322 	struct cbb_reslist *rle;
323 
324 	SLIST_FOREACH(rle, &sc->rl, link)
325 		if (SYS_RES_MEMORY == rle->type && rid == rle->rid)
326 			return (rle->res);
327 	return (NULL);
328 }
329 
330 static void
331 cbb_insert_res(struct cbb_softc *sc, struct resource *res, int type,
332     int rid)
333 {
334 	struct cbb_reslist *rle;
335 
336 	/*
337 	 * Need to record allocated resource so we can iterate through
338 	 * it later.
339 	 */
340 	rle = malloc(sizeof(struct cbb_reslist), M_DEVBUF, M_NOWAIT);
341 	if (rle == NULL)
342 		panic("cbb_cardbus_alloc_resource: can't record entry!");
343 	rle->res = res;
344 	rle->type = type;
345 	rle->rid = rid;
346 	SLIST_INSERT_HEAD(&sc->rl, rle, link);
347 }
348 
349 static void
350 cbb_destroy_res(struct cbb_softc *sc)
351 {
352 	struct cbb_reslist *rle;
353 
354 	while ((rle = SLIST_FIRST(&sc->rl)) != NULL) {
355 		device_printf(sc->dev, "Danger Will Robinson: Resource "
356 		    "left allocated!  This is a bug... "
357 		    "(rid=%x, type=%d, addr=%lx)\n", rle->rid, rle->type,
358 		    rman_get_start(rle->res));
359 		SLIST_REMOVE_HEAD(&sc->rl, link);
360 		free(rle, M_DEVBUF);
361 	}
362 }
363 
364 /************************************************************************/
365 /* Probe/Attach								*/
366 /************************************************************************/
367 
368 static int
369 cbb_chipset(uint32_t pci_id, const char **namep)
370 {
371 	struct yenta_chipinfo *ycp;
372 
373 	for (ycp = yc_chipsets; ycp->yc_id != 0 && pci_id != ycp->yc_id; ++ycp)
374 	    continue;
375 	if (namep != NULL)
376 		*namep = ycp->yc_name;
377 	return (ycp->yc_chiptype);
378 }
379 
380 static int
381 cbb_probe(device_t brdev)
382 {
383 	const char *name;
384 	uint32_t progif;
385 	uint32_t subclass;
386 
387 	/*
388 	 * Do we know that we support the chipset?  If so, then we
389 	 * accept the device.
390 	 */
391 	if (cbb_chipset(pci_get_devid(brdev), &name) != CB_UNKNOWN) {
392 		device_set_desc(brdev, name);
393 		return (0);
394 	}
395 
396 	/*
397 	 * We do support generic CardBus bridges.  All that we've seen
398 	 * to date have progif 0 (the Yenta spec, and successors mandate
399 	 * this).  We do not support PCI PCMCIA bridges (with one exception)
400 	 * with this driver since they generally are I/O mapped.  Those
401 	 * are supported by the pcic driver.  This should help us be more
402 	 * future proof.
403 	 */
404 	subclass = pci_get_subclass(brdev);
405 	progif = pci_get_progif(brdev);
406 	if (subclass == PCIS_BRIDGE_CARDBUS && progif == 0) {
407 		device_set_desc(brdev, "PCI-CardBus Bridge");
408 		return (0);
409 	}
410 	return (ENXIO);
411 }
412 
413 
414 /*
415  * Disable function interrupts by telling the bridge to generate IRQ1
416  * interrupts.  These interrupts aren't really generated by the chip, since
417  * IRQ1 is reserved.  Some chipsets assert INTA# inappropriately during
418  * initialization, so this helps to work around the problem.
419  *
420  * XXX We can't do this workaround for all chipsets, because this
421  * XXX causes interference with the keyboard because somechipsets will
422  * XXX actually signal IRQ1 over their serial interrupt connections to
423  * XXX the south bridge.  Disable it it for now.
424  */
425 static void
426 cbb_disable_func_intr(struct cbb_softc *sc)
427 {
428 #if 0
429 	uint8_t reg;
430 
431 	reg = (exca_getb(&sc->exca, EXCA_INTR) & ~EXCA_INTR_IRQ_MASK) |
432 	    EXCA_INTR_IRQ_RESERVED1;
433 	exca_putb(&sc->exca, EXCA_INTR, reg);
434 #endif
435 }
436 
437 /*
438  * Enable function interrupts.  We turn on function interrupts when the card
439  * requests an interrupt.  The PCMCIA standard says that we should set
440  * the lower 4 bits to 0 to route via PCI.  Note: we call this for both
441  * CardBus and R2 (PC Card) cases, but it should have no effect on CardBus
442  * cards.
443  */
444 static void
445 cbb_enable_func_intr(struct cbb_softc *sc)
446 {
447 	uint8_t reg;
448 
449 	reg = (exca_getb(&sc->exca, EXCA_INTR) & ~EXCA_INTR_IRQ_MASK) |
450 	    EXCA_INTR_IRQ_NONE;
451 	exca_putb(&sc->exca, EXCA_INTR, reg);
452 }
453 
454 static void
455 cbb_chipinit(struct cbb_softc *sc)
456 {
457 	uint32_t mux, sysctrl, reg;
458 
459 	/* Set CardBus latency timer */
460 	if (pci_read_config(sc->dev, PCIR_SECLAT_1, 1) < 0x20)
461 		pci_write_config(sc->dev, PCIR_SECLAT_1, 0x20, 1);
462 
463 	/* Set PCI latency timer */
464 	if (pci_read_config(sc->dev, PCIR_LATTIMER, 1) < 0x20)
465 		pci_write_config(sc->dev, PCIR_LATTIMER, 0x20, 1);
466 
467 	/* Enable memory access */
468 	PCI_MASK_CONFIG(sc->dev, PCIR_COMMAND,
469 	    | PCIM_CMD_MEMEN
470 	    | PCIM_CMD_PORTEN
471 	    | PCIM_CMD_BUSMASTEREN, 2);
472 
473 	/* disable Legacy IO */
474 	switch (sc->chipset) {
475 	case CB_RF5C46X:
476 		PCI_MASK_CONFIG(sc->dev, CBBR_BRIDGECTRL,
477 		    & ~(CBBM_BRIDGECTRL_RL_3E0_EN |
478 		    CBBM_BRIDGECTRL_RL_3E2_EN), 2);
479 		break;
480 	default:
481 		pci_write_config(sc->dev, CBBR_LEGACY, 0x0, 4);
482 		break;
483 	}
484 
485 	/* Use PCI interrupt for interrupt routing */
486 	PCI_MASK2_CONFIG(sc->dev, CBBR_BRIDGECTRL,
487 	    & ~(CBBM_BRIDGECTRL_MASTER_ABORT |
488 	    CBBM_BRIDGECTRL_INTR_IREQ_EN),
489 	    | CBBM_BRIDGECTRL_WRITE_POST_EN,
490 	    2);
491 
492 	/*
493 	 * XXX this should be a function table, ala OLDCARD.  This means
494 	 * that we could more easily support ISA interrupts for pccard
495 	 * cards if we had to.
496 	 */
497 	switch (sc->chipset) {
498 	case CB_TI113X:
499 		/*
500 		 * The TI 1031, TI 1130 and TI 1131 all require another bit
501 		 * be set to enable PCI routing of interrupts, and then
502 		 * a bit for each of the CSC and Function interrupts we
503 		 * want routed.
504 		 */
505 		PCI_MASK_CONFIG(sc->dev, CBBR_CBCTRL,
506 		    | CBBM_CBCTRL_113X_PCI_INTR |
507 		    CBBM_CBCTRL_113X_PCI_CSC | CBBM_CBCTRL_113X_PCI_IRQ_EN,
508 		    1);
509 		PCI_MASK_CONFIG(sc->dev, CBBR_DEVCTRL,
510 		    & ~(CBBM_DEVCTRL_INT_SERIAL |
511 		    CBBM_DEVCTRL_INT_PCI), 1);
512 		break;
513 	case CB_TI12XX:
514 		/*
515 		 * Some TI 12xx (and [14][45]xx) based pci cards
516 		 * sometimes have issues with the MFUNC register not
517 		 * being initialized due to a bad EEPROM on board.
518 		 * Laptops that this matters on have this register
519 		 * properly initialized.
520 		 *
521 		 * The TI125X parts have a different register.
522 		 */
523 		mux = pci_read_config(sc->dev, CBBR_MFUNC, 4);
524 		sysctrl = pci_read_config(sc->dev, CBBR_SYSCTRL, 4);
525 		if (mux == 0) {
526 			mux = (mux & ~CBBM_MFUNC_PIN0) |
527 			    CBBM_MFUNC_PIN0_INTA;
528 			if ((sysctrl & CBBM_SYSCTRL_INTRTIE) == 0)
529 				mux = (mux & ~CBBM_MFUNC_PIN1) |
530 				    CBBM_MFUNC_PIN1_INTB;
531 			pci_write_config(sc->dev, CBBR_MFUNC, mux, 4);
532 		}
533 		/*FALLTHROUGH*/
534 	case CB_TI125X:
535 		/*
536 		 * Disable zoom video.  Some machines initialize this
537 		 * improperly and exerpience has shown that this helps
538 		 * prevent strange behavior.
539 		 */
540 		pci_write_config(sc->dev, CBBR_MMCTRL, 0, 4);
541 		break;
542 	case CB_O2MICRO:
543 		/*
544 		 * Issue #1: INT# generated at the same time as
545 		 * selected ISA IRQ.  When IREQ# or STSCHG# is active,
546 		 * in addition to the ISA IRQ being generated, INT#
547 		 * will also be generated at the same time.
548 		 *
549 		 * Some of the older controllers have an issue in
550 		 * which the slot's PCI INT# will be asserted whenever
551 		 * IREQ# or STSCGH# is asserted even if ExCA registers
552 		 * 03h or 05h have an ISA IRQ selected.
553 		 *
554 		 * The fix for this issue, which will work for any
555 		 * controller (old or new), is to set ExCA registers
556 		 * 3Ah (slot 0) & 7Ah (slot 1) bits 7:4 = 1010b.
557 		 * These bits are undocumented.  By setting this
558 		 * register (of each slot) to '1010xxxxb' a routing of
559 		 * IREQ# to INTC# and STSCHG# to INTC# is selected.
560 		 * Since INTC# isn't connected there will be no
561 		 * unexpected PCI INT when IREQ# or STSCHG# is active.
562 		 * However, INTA# (slot 0) or INTB# (slot 1) will
563 		 * still be correctly generated if NO ISA IRQ is
564 		 * selected (ExCA regs 03h or 05h are cleared).
565 		 */
566 		reg = exca_getb(&sc->exca, EXCA_O2MICRO_CTRL_C);
567 		reg = (reg & 0x0f) |
568 		    EXCA_O2CC_IREQ_INTC | EXCA_O2CC_STSCHG_INTC;
569 		exca_putb(&sc->exca, EXCA_O2MICRO_CTRL_C, reg);
570 
571 		break;
572 	case CB_TOPIC97:
573 		/*
574 		 * Disable Zoom Video, ToPIC 97, 100.
575 		 */
576 		pci_write_config(sc->dev, CBBR_TOPIC_ZV_CONTROL, 0, 1);
577 		/*
578 		 * ToPIC 97, 100
579 		 * At offset 0xa1: INTERRUPT CONTROL register
580 		 * 0x1: Turn on INT interrupts.
581 		 */
582 		PCI_MASK_CONFIG(sc->dev, CBBR_TOPIC_INTCTRL,
583 		    | CBBM_TOPIC_INTCTRL_INTIRQSEL, 1);
584 		goto topic_common;
585 	case CB_TOPIC95:
586 		/*
587 		 * SOCKETCTRL appears to be TOPIC 95/B specific
588 		 */
589 		PCI_MASK_CONFIG(sc->dev, CBBR_TOPIC_SOCKETCTRL,
590 		    | CBBM_TOPIC_SOCKETCTRL_SCR_IRQSEL, 4);
591 
592 	topic_common:;
593 		/*
594 		 * At offset 0xa0: SLOT CONTROL
595 		 * 0x80 Enable CardBus Functionality
596 		 * 0x40 Enable CardBus and PC Card registers
597 		 * 0x20 Lock ID in exca regs
598 		 * 0x10 Write protect ID in config regs
599 		 * Clear the rest of the bits, which defaults the slot
600 		 * in legacy mode to 0x3e0 and offset 0. (legacy
601 		 * mode is determined elsewhere)
602 		 */
603 		pci_write_config(sc->dev, CBBR_TOPIC_SLOTCTRL,
604 		    CBBM_TOPIC_SLOTCTRL_SLOTON |
605 		    CBBM_TOPIC_SLOTCTRL_SLOTEN |
606 		    CBBM_TOPIC_SLOTCTRL_ID_LOCK |
607 		    CBBM_TOPIC_SLOTCTRL_ID_WP, 1);
608 
609 		/*
610 		 * At offset 0xa3 Card Detect Control Register
611 		 * 0x80 CARDBUS enbale
612 		 * 0x01 Cleared for hardware change detect
613 		 */
614 		PCI_MASK2_CONFIG(sc->dev, CBBR_TOPIC_CDC,
615 		    | CBBM_TOPIC_CDC_CARDBUS,
616 		    & ~CBBM_TOPIC_CDC_SWDETECT, 4);
617 		break;
618 	}
619 
620 	/*
621 	 * Need to tell ExCA registers to CSC interrupts route via PCI
622 	 * interrupts.  There are two ways to do this.  Once is to set
623 	 * INTR_ENABLE and the other is to set CSC to 0.  Since both
624 	 * methods are mutually compatible, we do both.
625 	 */
626 	exca_putb(&sc->exca, EXCA_INTR, EXCA_INTR_ENABLE);
627 	exca_putb(&sc->exca, EXCA_CSC_INTR, 0);
628 
629 	cbb_disable_func_intr(sc);
630 
631 	/* close all memory and io windows */
632 	pci_write_config(sc->dev, CBBR_MEMBASE0, 0xffffffff, 4);
633 	pci_write_config(sc->dev, CBBR_MEMLIMIT0, 0, 4);
634 	pci_write_config(sc->dev, CBBR_MEMBASE1, 0xffffffff, 4);
635 	pci_write_config(sc->dev, CBBR_MEMLIMIT1, 0, 4);
636 	pci_write_config(sc->dev, CBBR_IOBASE0, 0xffffffff, 4);
637 	pci_write_config(sc->dev, CBBR_IOLIMIT0, 0, 4);
638 	pci_write_config(sc->dev, CBBR_IOBASE1, 0xffffffff, 4);
639 	pci_write_config(sc->dev, CBBR_IOLIMIT1, 0, 4);
640 }
641 
642 #ifndef BURN_BRIDGES
643 static void
644 cbb_powerstate_d0(device_t dev)
645 {
646 	u_int32_t membase, irq;
647 
648 	if (pci_get_powerstate(dev) != PCI_POWERSTATE_D0) {
649 		/* Save important PCI config data. */
650 		membase = pci_read_config(dev, CBBR_SOCKBASE, 4);
651 		irq = pci_read_config(dev, PCIR_INTLINE, 4);
652 
653 		/* Reset the power state. */
654 		device_printf(dev, "chip is in D%d power mode "
655 		    "-- setting to D0\n", pci_get_powerstate(dev));
656 
657 		pci_set_powerstate(dev, PCI_POWERSTATE_D0);
658 
659 		/* Restore PCI config data. */
660 		pci_write_config(dev, CBBR_SOCKBASE, membase, 4);
661 		pci_write_config(dev, PCIR_INTLINE, irq, 4);
662 	}
663 }
664 #endif
665 
666 /*
667  * Print out the config space
668  */
669 static void
670 cbb_print_config(device_t dev)
671 {
672 	int i;
673 
674 	device_printf(dev, "PCI Configuration space:");
675 	for (i = 0; i < 256; i += 4) {
676 		if (i % 16 == 0)
677 			printf("\n  0x%02x: ", i);
678 		printf("0x%08x ", pci_read_config(dev, i, 4));
679 	}
680 	printf("\n");
681 }
682 
683 static int
684 cbb_attach(device_t brdev)
685 {
686 	static int curr_bus_number = 1; /* XXX EVILE BAD (see below) */
687 	struct cbb_softc *sc = (struct cbb_softc *)device_get_softc(brdev);
688 	int rid, bus, pribus;
689 	device_t parent;
690 
691 	parent = device_get_parent(brdev);
692 	mtx_init(&sc->mtx, device_get_nameunit(brdev), "cbb", MTX_DEF);
693 	cv_init(&sc->cv, "cbb cv");
694 	sc->chipset = cbb_chipset(pci_get_devid(brdev), NULL);
695 	sc->dev = brdev;
696 	sc->cbdev = NULL;
697 	sc->exca.pccarddev = NULL;
698 	sc->secbus = pci_read_config(brdev, PCIR_SECBUS_2, 1);
699 	sc->subbus = pci_read_config(brdev, PCIR_SUBBUS_2, 1);
700 	SLIST_INIT(&sc->rl);
701 	STAILQ_INIT(&sc->intr_handlers);
702 #ifndef	BURN_BRIDGES
703 	cbb_powerstate_d0(brdev);
704 
705 	/*
706 	 * The PCI bus code should assign us memory in the absense
707 	 * of the BIOS doing so.  However, 'should' isn't 'is,' so we kludge
708 	 * up something here until the PCI/acpi code properly assigns the
709 	 * resource.
710 	 */
711 #endif
712 	rid = CBBR_SOCKBASE;
713 	sc->base_res = bus_alloc_resource_any(brdev, SYS_RES_MEMORY, &rid,
714 	    RF_ACTIVE);
715 	if (!sc->base_res) {
716 #ifdef BURN_BRIDGES
717 		device_printf(brdev, "Could not map register memory\n");
718 		mtx_destroy(&sc->mtx);
719 		cv_destroy(&sc->cv);
720 		return (ENOMEM);
721 #else
722 		uint32_t sockbase;
723 		/*
724 		 * Generally, the BIOS will assign this memory for us.
725 		 * However, newer BIOSes do not because the MS design
726 		 * documents have mandated that this is for the OS
727 		 * to assign rather than the BIOS.  This driver shouldn't
728 		 * be doing this, but until the pci bus code (or acpi)
729 		 * does this, we allow CardBus bridges to work on more
730 		 * machines.
731 		 */
732 		pci_write_config(brdev, rid, 0xfffffffful, 4);
733 		sockbase = pci_read_config(brdev, rid, 4);
734 		sockbase = (sockbase & 0xfffffff0ul) &
735 		    -(sockbase & 0xfffffff0ul);
736 		sc->base_res = bus_generic_alloc_resource(
737 		    device_get_parent(brdev), brdev, SYS_RES_MEMORY,
738 		    &rid, cbb_start_mem, ~0, sockbase,
739 		    RF_ACTIVE | rman_make_alignment_flags(sockbase));
740 		if (!sc->base_res) {
741 			device_printf(brdev,
742 			    "Could not grab register memory\n");
743 			mtx_destroy(&sc->mtx);
744 			cv_destroy(&sc->cv);
745 			return (ENOMEM);
746 		}
747 		sc->flags |= CBB_KLUDGE_ALLOC;
748 		pci_write_config(brdev, CBBR_SOCKBASE,
749 		    rman_get_start(sc->base_res), 4);
750 		DEVPRINTF((brdev, "PCI Memory allocated: %08lx\n",
751 		    rman_get_start(sc->base_res)));
752 #endif
753 	} else {
754 		DEVPRINTF((brdev, "Found memory at %08lx\n",
755 		    rman_get_start(sc->base_res)));
756 	}
757 
758 	sc->bst = rman_get_bustag(sc->base_res);
759 	sc->bsh = rman_get_bushandle(sc->base_res);
760 	exca_init(&sc->exca, brdev, sc->bst, sc->bsh, CBB_EXCA_OFFSET);
761 	sc->exca.flags |= EXCA_HAS_MEMREG_WIN;
762 	sc->exca.chipset = EXCA_CARDBUS;
763 	cbb_chipinit(sc);
764 
765 	/*
766 	 * This is a gross hack.  We should be scanning the entire pci
767 	 * tree, assigning bus numbers in a way such that we (1) can
768 	 * reserve 1 extra bus just in case and (2) all sub busses
769 	 * are in an appropriate range.
770 	 */
771 	bus = pci_read_config(brdev, PCIR_SECBUS_2, 1);
772 	pribus = pcib_get_bus(parent);
773 	DEVPRINTF((brdev, "Secondary bus is %d\n", bus));
774 	if (bus == 0) {
775 		if (curr_bus_number < pribus)
776 			curr_bus_number = pribus + 1;
777 		if (pci_read_config(brdev, PCIR_PRIBUS_2, 1) != pribus) {
778 			DEVPRINTF((brdev, "Setting primary bus to %d\n", pribus));
779 			pci_write_config(brdev, PCIR_PRIBUS_2, pribus, 1);
780 		}
781 		bus = curr_bus_number;
782 		DEVPRINTF((brdev, "Secondary bus set to %d subbus %d\n", bus,
783 		    bus + 1));
784 		sc->secbus = bus;
785 		sc->subbus = bus + 1;
786 		pci_write_config(brdev, PCIR_SECBUS_2, bus, 1);
787 		pci_write_config(brdev, PCIR_SUBBUS_2, bus + 1, 1);
788 		curr_bus_number += 2;
789 	}
790 
791 	/* attach children */
792 	sc->cbdev = device_add_child(brdev, "cardbus", -1);
793 	if (sc->cbdev == NULL)
794 		DEVPRINTF((brdev, "WARNING: cannot add cardbus bus.\n"));
795 	else if (device_probe_and_attach(sc->cbdev) != 0) {
796 		DEVPRINTF((brdev, "WARNING: cannot attach cardbus bus!\n"));
797 		sc->cbdev = NULL;
798 	}
799 
800 	sc->exca.pccarddev = device_add_child(brdev, "pccard", -1);
801 	if (sc->exca.pccarddev == NULL)
802 		DEVPRINTF((brdev, "WARNING: cannot add pccard bus.\n"));
803 	else if (device_probe_and_attach(sc->exca.pccarddev) != 0) {
804 		DEVPRINTF((brdev, "WARNING: cannot attach pccard bus.\n"));
805 		sc->exca.pccarddev = NULL;
806 	}
807 
808 	/* Map and establish the interrupt. */
809 	rid = 0;
810 	sc->irq_res = bus_alloc_resource_any(brdev, SYS_RES_IRQ, &rid,
811 	    RF_SHAREABLE | RF_ACTIVE);
812 	if (sc->irq_res == NULL) {
813 		printf("cbb: Unable to map IRQ...\n");
814 		goto err;
815 	}
816 
817 	if (bus_setup_intr(brdev, sc->irq_res, INTR_TYPE_AV | INTR_MPSAFE,
818 	    cbb_intr, sc, &sc->intrhand)) {
819 		device_printf(brdev, "couldn't establish interrupt");
820 		goto err;
821 	}
822 
823 	/* reset 16-bit pcmcia bus */
824 	exca_clrb(&sc->exca, EXCA_INTR, EXCA_INTR_RESET);
825 
826 	/* turn off power */
827 	cbb_power(brdev, CARD_OFF);
828 
829 	/* CSC Interrupt: Card detect interrupt on */
830 	cbb_setb(sc, CBB_SOCKET_MASK, CBB_SOCKET_MASK_CD);
831 
832 	/* reset interrupt */
833 	cbb_set(sc, CBB_SOCKET_EVENT, cbb_get(sc, CBB_SOCKET_EVENT));
834 
835 	if (bootverbose)
836 		cbb_print_config(brdev);
837 
838 	/* Start the thread */
839 	if (kthread_create(cbb_event_thread, sc, &sc->event_thread, 0, 0,
840 	    "%s", device_get_nameunit(brdev))) {
841 		device_printf(brdev, "unable to create event thread.\n");
842 		panic("cbb_create_event_thread");
843 	}
844 
845 	return (0);
846 err:
847 	if (sc->irq_res)
848 		bus_release_resource(brdev, SYS_RES_IRQ, 0, sc->irq_res);
849 	if (sc->base_res) {
850 		if (sc->flags & CBB_KLUDGE_ALLOC)
851 			bus_generic_release_resource(device_get_parent(brdev),
852 			    brdev, SYS_RES_MEMORY, CBBR_SOCKBASE,
853 			    sc->base_res);
854 		else
855 			bus_release_resource(brdev, SYS_RES_MEMORY,
856 			    CBBR_SOCKBASE, sc->base_res);
857 	}
858 	mtx_destroy(&sc->mtx);
859 	cv_destroy(&sc->cv);
860 	return (ENOMEM);
861 }
862 
863 static int
864 cbb_detach(device_t brdev)
865 {
866 	struct cbb_softc *sc = device_get_softc(brdev);
867 	int numdevs;
868 	device_t *devlist;
869 	int tmp;
870 	int error;
871 
872 	device_get_children(brdev, &devlist, &numdevs);
873 
874 	error = 0;
875 	for (tmp = 0; tmp < numdevs; tmp++) {
876 		if (device_detach(devlist[tmp]) == 0)
877 			device_delete_child(brdev, devlist[tmp]);
878 		else
879 			error++;
880 	}
881 	free(devlist, M_TEMP);
882 	if (error > 0)
883 		return (ENXIO);
884 
885 	mtx_lock(&sc->mtx);
886 	bus_teardown_intr(brdev, sc->irq_res, sc->intrhand);
887 	sc->flags |= CBB_KTHREAD_DONE;
888 	if (sc->flags & CBB_KTHREAD_RUNNING) {
889 		cv_broadcast(&sc->cv);
890 		msleep(sc->event_thread, &sc->mtx, PWAIT, "cbbun", 0);
891 	}
892 	mtx_unlock(&sc->mtx);
893 
894 	bus_release_resource(brdev, SYS_RES_IRQ, 0, sc->irq_res);
895 	if (sc->flags & CBB_KLUDGE_ALLOC)
896 		bus_generic_release_resource(device_get_parent(brdev),
897 		    brdev, SYS_RES_MEMORY, CBBR_SOCKBASE, sc->base_res);
898 	else
899 		bus_release_resource(brdev, SYS_RES_MEMORY,
900 		    CBBR_SOCKBASE, sc->base_res);
901 	mtx_destroy(&sc->mtx);
902 	cv_destroy(&sc->cv);
903 	return (0);
904 }
905 
906 static int
907 cbb_shutdown(device_t brdev)
908 {
909 	struct cbb_softc *sc = (struct cbb_softc *)device_get_softc(brdev);
910 	/* properly reset everything at shutdown */
911 
912 	PCI_MASK_CONFIG(brdev, CBBR_BRIDGECTRL, |CBBM_BRIDGECTRL_RESET, 2);
913 	exca_clrb(&sc->exca, EXCA_INTR, EXCA_INTR_RESET);
914 
915 	cbb_set(sc, CBB_SOCKET_MASK, 0);
916 
917 	cbb_power(brdev, CARD_OFF);
918 
919 	exca_putb(&sc->exca, EXCA_ADDRWIN_ENABLE, 0);
920 	pci_write_config(brdev, CBBR_MEMBASE0, 0, 4);
921 	pci_write_config(brdev, CBBR_MEMLIMIT0, 0, 4);
922 	pci_write_config(brdev, CBBR_MEMBASE1, 0, 4);
923 	pci_write_config(brdev, CBBR_MEMLIMIT1, 0, 4);
924 	pci_write_config(brdev, CBBR_IOBASE0, 0, 4);
925 	pci_write_config(brdev, CBBR_IOLIMIT0, 0, 4);
926 	pci_write_config(brdev, CBBR_IOBASE1, 0, 4);
927 	pci_write_config(brdev, CBBR_IOLIMIT1, 0, 4);
928 	pci_write_config(brdev, PCIR_COMMAND, 0, 2);
929 	return (0);
930 }
931 
932 static int
933 cbb_setup_intr(device_t dev, device_t child, struct resource *irq,
934   int flags, driver_intr_t *intr, void *arg, void **cookiep)
935 {
936 	struct cbb_intrhand *ih;
937 	struct cbb_softc *sc = device_get_softc(dev);
938 
939 	/*
940 	 * You aren't allowed to have fast interrupts for pccard/cardbus
941 	 * things since those interrupts are PCI and shared.  Since we use
942 	 * the PCI interrupt for the status change interrupts, it can't be
943 	 * free for use by the driver.  Fast interrupts must not be shared.
944 	 */
945 	if ((flags & INTR_FAST) != 0)
946 		return (EINVAL);
947 	ih = malloc(sizeof(struct cbb_intrhand), M_DEVBUF, M_NOWAIT);
948 	if (ih == NULL)
949 		return (ENOMEM);
950 	*cookiep = ih;
951 	ih->intr = intr;
952 	ih->arg = arg;
953 	ih->flags = flags & INTR_MPSAFE;
954 	STAILQ_INSERT_TAIL(&sc->intr_handlers, ih, entries);
955 	cbb_enable_func_intr(sc);
956 	/*
957 	 * XXX need to turn on ISA interrupts, if we ever support them, but
958 	 * XXX for now that's all we need to do.
959 	 */
960 	return (0);
961 }
962 
963 static int
964 cbb_teardown_intr(device_t dev, device_t child, struct resource *irq,
965     void *cookie)
966 {
967 	struct cbb_intrhand *ih;
968 	struct cbb_softc *sc = device_get_softc(dev);
969 
970 	/* XXX Need to do different things for ISA interrupts. */
971 	ih = (struct cbb_intrhand *) cookie;
972 	STAILQ_REMOVE(&sc->intr_handlers, ih, cbb_intrhand, entries);
973 	free(ih, M_DEVBUF);
974 	return (0);
975 }
976 
977 
978 static void
979 cbb_driver_added(device_t brdev, driver_t *driver)
980 {
981 	struct cbb_softc *sc = device_get_softc(brdev);
982 	device_t *devlist;
983 	device_t dev;
984 	int tmp;
985 	int numdevs;
986 	int wake = 0;
987 
988 	DEVICE_IDENTIFY(driver, brdev);
989 	device_get_children(brdev, &devlist, &numdevs);
990 	for (tmp = 0; tmp < numdevs; tmp++) {
991 		dev = devlist[tmp];
992 		if (device_get_state(dev) == DS_NOTPRESENT &&
993 		    device_probe_and_attach(dev) == 0)
994 			wake++;
995 	}
996 	free(devlist, M_TEMP);
997 
998 	if (wake > 0) {
999 		mtx_lock(&sc->mtx);
1000 		cv_signal(&sc->cv);
1001 		mtx_unlock(&sc->mtx);
1002 	}
1003 }
1004 
1005 static void
1006 cbb_child_detached(device_t brdev, device_t child)
1007 {
1008 	struct cbb_softc *sc = device_get_softc(brdev);
1009 
1010 	if (child != sc->cbdev && child != sc->exca.pccarddev)
1011 		device_printf(brdev, "Unknown child detached: %s\n",
1012 		    device_get_nameunit(child));
1013 }
1014 
1015 /************************************************************************/
1016 /* Kthreads								*/
1017 /************************************************************************/
1018 
1019 static void
1020 cbb_event_thread(void *arg)
1021 {
1022 	struct cbb_softc *sc = arg;
1023 	uint32_t status;
1024 	int err;
1025 	int not_a_card = 0;
1026 
1027 	sc->flags |= CBB_KTHREAD_RUNNING;
1028 	while ((sc->flags & CBB_KTHREAD_DONE) == 0) {
1029 		/*
1030 		 * We take out Giant here because we need it deep,
1031 		 * down in the bowels of the vm system for mapping the
1032 		 * memory we need to read the CIS.  In addition, since
1033 		 * we are adding/deleting devices from the dev tree,
1034 		 * and that code isn't MP safe, we have to hold Giant.
1035 		 */
1036 		mtx_lock(&Giant);
1037 		status = cbb_get(sc, CBB_SOCKET_STATE);
1038 		DPRINTF(("Status is 0x%x\n", status));
1039 		if (!CBB_CARD_PRESENT(status)) {
1040 			not_a_card = 0;		/* We know card type */
1041 			cbb_removal(sc);
1042 		} else if (status & CBB_STATE_NOT_A_CARD) {
1043 			/*
1044 			 * Up to 20 times, try to rescan the card when we
1045 			 * see NOT_A_CARD.
1046 			 */
1047 			if (not_a_card++ < 20) {
1048 				DEVPRINTF((sc->dev,
1049 				    "Not a card bit set, rescanning\n"));
1050 				cbb_setb(sc, CBB_SOCKET_FORCE, CBB_FORCE_CV_TEST);
1051 			} else {
1052 				device_printf(sc->dev,
1053 				    "Can't determine card type\n");
1054 			}
1055 		} else {
1056 			not_a_card = 0;		/* We know card type */
1057 			cbb_insert(sc);
1058 		}
1059 		mtx_unlock(&Giant);
1060 
1061 		/*
1062 		 * Wait until it has been 1s since the last time we
1063 		 * get an interrupt.  We handle the rest of the interrupt
1064 		 * at the top of the loop.  Although we clear the bit in the
1065 		 * ISR, we signal sc->cv from the detach path after we've
1066 		 * set the CBB_KTHREAD_DONE bit, so we can't do a simple
1067 		 * 1s sleep here.
1068 		 *
1069 		 * In our ISR, we turn off the card changed interrupt.  Turn
1070 		 * them back on here before we wait for them to happen.  We
1071 		 * turn them on/off so that we can tolerate a large latency
1072 		 * between the time we signal cbb_event_thread and it gets
1073 		 * a chance to run.
1074 		 */
1075 		mtx_lock(&sc->mtx);
1076 		cbb_setb(sc, CBB_SOCKET_MASK, CBB_SOCKET_MASK_CD);
1077 		cv_wait(&sc->cv, &sc->mtx);
1078 		err = 0;
1079 		while (err != EWOULDBLOCK &&
1080 		    (sc->flags & CBB_KTHREAD_DONE) == 0)
1081 			err = cv_timedwait(&sc->cv, &sc->mtx, 1 * hz);
1082 		mtx_unlock(&sc->mtx);
1083 	}
1084 	sc->flags &= ~CBB_KTHREAD_RUNNING;
1085 	kthread_exit(0);
1086 }
1087 
1088 /************************************************************************/
1089 /* Insert/removal							*/
1090 /************************************************************************/
1091 
1092 static void
1093 cbb_insert(struct cbb_softc *sc)
1094 {
1095 	uint32_t sockevent, sockstate;
1096 
1097 	sockevent = cbb_get(sc, CBB_SOCKET_EVENT);
1098 	sockstate = cbb_get(sc, CBB_SOCKET_STATE);
1099 
1100 	DEVPRINTF((sc->dev, "card inserted: event=0x%08x, state=%08x\n",
1101 	    sockevent, sockstate));
1102 
1103 	if (sockstate & CBB_STATE_R2_CARD) {
1104 		if (sc->exca.pccarddev)
1105 			sc->flags |= CBB_16BIT_CARD | CBB_CARD_OK;
1106 		exca_insert(&sc->exca);
1107 	} else if (sockstate & CBB_STATE_CB_CARD) {
1108 		if (sc->cbdev != NULL) {
1109 			sc->flags &= ~CBB_16BIT_CARD;
1110 			sc->flags |= CBB_CARD_OK;
1111 			if (CARD_ATTACH_CARD(sc->cbdev) != 0)
1112 				device_printf(sc->dev,
1113 				    "CardBus card activation failed\n");
1114 		} else {
1115 			device_printf(sc->dev,
1116 			    "CardBus card inserted, but no cardbus bus.\n");
1117 		}
1118 	} else {
1119 		/*
1120 		 * We should power the card down, and try again a couple of
1121 		 * times if this happens. XXX
1122 		 */
1123 		device_printf(sc->dev, "Unsupported card type detected\n");
1124 	}
1125 }
1126 
1127 static void
1128 cbb_removal(struct cbb_softc *sc)
1129 {
1130 	if (sc->flags & CBB_16BIT_CARD) {
1131 		exca_removal(&sc->exca);
1132 	} else {
1133 		if (sc->cbdev != NULL)
1134 			CARD_DETACH_CARD(sc->cbdev);
1135 	}
1136 	cbb_destroy_res(sc);
1137 }
1138 
1139 /************************************************************************/
1140 /* Interrupt Handler							*/
1141 /************************************************************************/
1142 
1143 static void
1144 cbb_intr(void *arg)
1145 {
1146 	struct cbb_softc *sc = arg;
1147 	uint32_t sockevent;
1148 	struct cbb_intrhand *ih;
1149 
1150 	/*
1151 	 * This ISR needs work XXX
1152 	 */
1153 	sockevent = cbb_get(sc, CBB_SOCKET_EVENT);
1154 	if (sockevent != 0) {
1155 		/* ack the interrupt */
1156 		cbb_setb(sc, CBB_SOCKET_EVENT, sockevent);
1157 
1158 		/*
1159 		 * If anything has happened to the socket, we assume that
1160 		 * the card is no longer OK, and we shouldn't call its
1161 		 * ISR.  We set CARD_OK as soon as we've attached the
1162 		 * card.  This helps in a noisy eject, which happens
1163 		 * all too often when users are ejecting their PC Cards.
1164 		 *
1165 		 * We use this method in preference to checking to see if
1166 		 * the card is still there because the check suffers from
1167 		 * a race condition in the bouncing case.  Prior versions
1168 		 * of the pccard software used a similar trick and achieved
1169 		 * excellent results.
1170 		 */
1171 		if (sockevent & CBB_SOCKET_EVENT_CD) {
1172 			mtx_lock(&sc->mtx);
1173 			cbb_setb(sc, CBB_SOCKET_MASK, CBB_SOCKET_MASK_CD);
1174 			sc->flags &= ~CBB_CARD_OK;
1175 			cbb_disable_func_intr(sc);
1176 			cv_signal(&sc->cv);
1177 			mtx_unlock(&sc->mtx);
1178 		}
1179 	}
1180 	/*
1181 	 * Some chips also require us to read the old ExCA registe for
1182 	 * card status change when we route CSC vis PCI.  This isn't supposed
1183 	 * to be required, but it clears the interrupt state on some chipsets.
1184 	 * Maybe there's a setting that would obviate its need.  Maybe we
1185 	 * should test the status bits and deal with them, but so far we've
1186 	 * not found any machines that don't also give us the socket status
1187 	 * indication above.
1188 	 *
1189 	 * We have to call this unconditionally because some bridges deliver
1190 	 * the even independent of the CBB_SOCKET_EVENT_CD above.
1191 	 */
1192 	exca_getb(&sc->exca, EXCA_CSC);
1193 
1194 	/*
1195 	 * If the card is OK, call all the interrupt handlers.
1196  	 */
1197 	if (sc->flags & CBB_CARD_OK) {
1198 		STAILQ_FOREACH(ih, &sc->intr_handlers, entries) {
1199 			if ((ih->flags & INTR_MPSAFE) == 0)
1200 				mtx_lock(&Giant);
1201 			(*ih->intr)(ih->arg);
1202 			if ((ih->flags & INTR_MPSAFE) == 0)
1203 				mtx_unlock(&Giant);
1204 		}
1205 	}
1206 }
1207 
1208 /************************************************************************/
1209 /* Generic Power functions						*/
1210 /************************************************************************/
1211 
1212 static int
1213 cbb_detect_voltage(device_t brdev)
1214 {
1215 	struct cbb_softc *sc = device_get_softc(brdev);
1216 	uint32_t psr;
1217 	int vol = CARD_UKN_CARD;
1218 
1219 	psr = cbb_get(sc, CBB_SOCKET_STATE);
1220 
1221 	if (psr & CBB_STATE_5VCARD)
1222 		vol |= CARD_5V_CARD;
1223 	if (psr & CBB_STATE_3VCARD)
1224 		vol |= CARD_3V_CARD;
1225 	if (psr & CBB_STATE_XVCARD)
1226 		vol |= CARD_XV_CARD;
1227 	if (psr & CBB_STATE_YVCARD)
1228 		vol |= CARD_YV_CARD;
1229 
1230 	return (vol);
1231 }
1232 
1233 static uint8_t
1234 cbb_o2micro_power_hack(struct cbb_softc *sc)
1235 {
1236 	uint8_t reg;
1237 
1238 	/*
1239 	 * Issue #2: INT# not qualified with IRQ Routing Bit.  An
1240 	 * unexpected PCI INT# may be generated during PC-Card
1241 	 * initialization even with the IRQ Routing Bit Set with some
1242 	 * PC-Cards.
1243 	 *
1244 	 * This is a two part issue.  The first part is that some of
1245 	 * our older controllers have an issue in which the slot's PCI
1246 	 * INT# is NOT qualified by the IRQ routing bit (PCI reg. 3Eh
1247 	 * bit 7).  Regardless of the IRQ routing bit, if NO ISA IRQ
1248 	 * is selected (ExCA register 03h bits 3:0, of the slot, are
1249 	 * cleared) we will generate INT# if IREQ# is asserted.  The
1250 	 * second part is because some PC-Cards prematurally assert
1251 	 * IREQ# before the ExCA registers are fully programmed.  This
1252 	 * in turn asserts INT# because ExCA register 03h bits 3:0
1253 	 * (ISA IRQ Select) are not yet programmed.
1254 	 *
1255 	 * The fix for this issue, which will work for any controller
1256 	 * (old or new), is to set ExCA register 03h bits 3:0 = 0001b
1257 	 * (select IRQ1), of the slot, before turning on slot power.
1258 	 * Selecting IRQ1 will result in INT# NOT being asserted
1259 	 * (because IRQ1 is selected), and IRQ1 won't be asserted
1260 	 * because our controllers don't generate IRQ1.
1261 	 */
1262 	reg = exca_getb(&sc->exca, EXCA_INTR);
1263 	exca_putb(&sc->exca, EXCA_INTR, (reg & 0xf0) | 1);
1264 	return (reg);
1265 }
1266 
1267 /*
1268  * Restore the damage that cbb_o2micro_power_hack does to EXCA_INTR so
1269  * we don't have an interrupt storm on power on.  This has the efect of
1270  * disabling card status change interrupts for the duration of poweron.
1271  */
1272 static void
1273 cbb_o2micro_power_hack2(struct cbb_softc *sc, uint8_t reg)
1274 {
1275 	exca_putb(&sc->exca, EXCA_INTR, reg);
1276 }
1277 
1278 static int
1279 cbb_power(device_t brdev, int volts)
1280 {
1281 	uint32_t status, sock_ctrl;
1282 	struct cbb_softc *sc = device_get_softc(brdev);
1283 	int timeout;
1284 	int retval = 0;
1285 	uint32_t sockevent;
1286 	uint8_t reg = 0;
1287 
1288 	status = cbb_get(sc, CBB_SOCKET_STATE);
1289 	sock_ctrl = cbb_get(sc, CBB_SOCKET_CONTROL);
1290 
1291 	sock_ctrl &= ~CBB_SOCKET_CTRL_VCCMASK;
1292 	switch (volts & CARD_VCCMASK) {
1293 	case 5:
1294 		sock_ctrl |= CBB_SOCKET_CTRL_VCC_5V;
1295 		break;
1296 	case 3:
1297 		sock_ctrl |= CBB_SOCKET_CTRL_VCC_3V;
1298 		break;
1299 	case XV:
1300 		sock_ctrl |= CBB_SOCKET_CTRL_VCC_XV;
1301 		break;
1302 	case YV:
1303 		sock_ctrl |= CBB_SOCKET_CTRL_VCC_YV;
1304 		break;
1305 	case 0:
1306 		break;
1307 	default:
1308 		return (0);			/* power NEVER changed */
1309 	}
1310 
1311 	/* VPP == VCC */
1312 	sock_ctrl &= ~CBB_SOCKET_CTRL_VPPMASK;
1313 	sock_ctrl |= ((sock_ctrl >> 4) & 0x07);
1314 
1315 	if (cbb_get(sc, CBB_SOCKET_CONTROL) == sock_ctrl)
1316 		return (1); /* no change necessary */
1317 	DEVPRINTF((sc->dev, "cbb_power: %dV\n", volts));
1318 	if (volts != 0 && sc->chipset == CB_O2MICRO)
1319 		reg = cbb_o2micro_power_hack(sc);
1320 
1321 	cbb_set(sc, CBB_SOCKET_CONTROL, sock_ctrl);
1322 	status = cbb_get(sc, CBB_SOCKET_STATE);
1323 
1324 	/*
1325 	 * XXX This busy wait is bogus.  We should wait for a power
1326 	 * interrupt and then whine if the status is bad.  If we're
1327 	 * worried about the card not coming up, then we should also
1328 	 * schedule a timeout which we can cancel in the power interrupt.
1329 	 */
1330 	timeout = 20;
1331 	do {
1332 		DELAY(20*1000);
1333 		sockevent = cbb_get(sc, CBB_SOCKET_EVENT);
1334 	} while (!(sockevent & CBB_SOCKET_EVENT_POWER) && --timeout > 0);
1335 	/* reset event status */
1336 	/* XXX should only reset EVENT_POWER */
1337 	cbb_set(sc, CBB_SOCKET_EVENT, sockevent);
1338 	if (timeout < 0) {
1339 		printf ("VCC supply failed.\n");
1340 		goto done;
1341 	}
1342 
1343 	/* XXX
1344 	 * delay 400 ms: thgough the standard defines that the Vcc set-up time
1345 	 * is 20 ms, some PC-Card bridge requires longer duration.
1346 	 * XXX Note: We should check the stutus AFTER the delay to give time
1347 	 * for things to stabilize.
1348 	 */
1349 	DELAY(400*1000);
1350 
1351 	if (status & CBB_STATE_BAD_VCC_REQ) {
1352 		device_printf(sc->dev,
1353 		    "bad Vcc request. ctrl=0x%x, status=0x%x\n",
1354 		    sock_ctrl ,status);
1355 		printf("cbb_power: %dV\n", volts);
1356 		goto done;
1357 	}
1358 	retval = 1;
1359 done:;
1360 	if (volts != 0 && sc->chipset == CB_O2MICRO)
1361 		cbb_o2micro_power_hack2(sc, reg);
1362 	return (retval);
1363 }
1364 
1365 /*
1366  * detect the voltage for the card, and set it.  Since the power
1367  * used is the square of the voltage, lower voltages is a big win
1368  * and what Windows does (and what Microsoft prefers).  The MS paper
1369  * also talks about preferring the CIS entry as well.  In addition,
1370  * we power up with OE disabled.  We'll set it later in the power
1371  * up sequence.
1372  */
1373 static int
1374 cbb_do_power(device_t brdev)
1375 {
1376 	struct cbb_softc *sc = device_get_softc(brdev);
1377 	int voltage;
1378 
1379 	/* Don't enable OE */
1380 	exca_clrb(&sc->exca, EXCA_PWRCTL, EXCA_PWRCTL_OE);
1381 
1382 	/* Prefer lowest voltage supported */
1383 	voltage = cbb_detect_voltage(brdev);
1384 	cbb_power(brdev, CARD_OFF);
1385 	if (voltage & CARD_YV_CARD)
1386 		cbb_power(brdev, CARD_VCC(YV));
1387 	else if (voltage & CARD_XV_CARD)
1388 		cbb_power(brdev, CARD_VCC(XV));
1389 	else if (voltage & CARD_3V_CARD)
1390 		cbb_power(brdev, CARD_VCC(3));
1391 	else if (voltage & CARD_5V_CARD)
1392 		cbb_power(brdev, CARD_VCC(5));
1393 	else {
1394 		device_printf(brdev, "Unknown card voltage\n");
1395 		return (ENXIO);
1396 	}
1397 	return (0);
1398 }
1399 
1400 /************************************************************************/
1401 /* CardBus power functions						*/
1402 /************************************************************************/
1403 
1404 static void
1405 cbb_cardbus_reset(device_t brdev)
1406 {
1407 	struct cbb_softc *sc = device_get_softc(brdev);
1408 	int delay_us;
1409 
1410 	delay_us = sc->chipset == CB_RF5C47X ? 400*1000 : 20*1000;
1411 
1412 	PCI_MASK_CONFIG(brdev, CBBR_BRIDGECTRL, |CBBM_BRIDGECTRL_RESET, 2);
1413 
1414 	DELAY(delay_us);
1415 
1416 	/* If a card exists, unreset it! */
1417 	if (CBB_CARD_PRESENT(cbb_get(sc, CBB_SOCKET_STATE))) {
1418 		PCI_MASK_CONFIG(brdev, CBBR_BRIDGECTRL,
1419 		    &~CBBM_BRIDGECTRL_RESET, 2);
1420 		DELAY(delay_us);
1421 	}
1422 }
1423 
1424 static int
1425 cbb_cardbus_power_enable_socket(device_t brdev, device_t child)
1426 {
1427 	struct cbb_softc *sc = device_get_softc(brdev);
1428 	int err;
1429 
1430 	if (!CBB_CARD_PRESENT(cbb_get(sc, CBB_SOCKET_STATE)))
1431 		return (ENODEV);
1432 
1433 	err = cbb_do_power(brdev);
1434 	if (err)
1435 		return (err);
1436 	cbb_cardbus_reset(brdev);
1437 	return (0);
1438 }
1439 
1440 static void
1441 cbb_cardbus_power_disable_socket(device_t brdev, device_t child)
1442 {
1443 	cbb_power(brdev, CARD_OFF);
1444 	cbb_cardbus_reset(brdev);
1445 }
1446 
1447 /************************************************************************/
1448 /* CardBus Resource							*/
1449 /************************************************************************/
1450 
1451 static int
1452 cbb_cardbus_io_open(device_t brdev, int win, uint32_t start, uint32_t end)
1453 {
1454 	int basereg;
1455 	int limitreg;
1456 
1457 	if ((win < 0) || (win > 1)) {
1458 		DEVPRINTF((brdev,
1459 		    "cbb_cardbus_io_open: window out of range %d\n", win));
1460 		return (EINVAL);
1461 	}
1462 
1463 	basereg = win * 8 + CBBR_IOBASE0;
1464 	limitreg = win * 8 + CBBR_IOLIMIT0;
1465 
1466 	pci_write_config(brdev, basereg, start, 4);
1467 	pci_write_config(brdev, limitreg, end, 4);
1468 	return (0);
1469 }
1470 
1471 static int
1472 cbb_cardbus_mem_open(device_t brdev, int win, uint32_t start, uint32_t end)
1473 {
1474 	int basereg;
1475 	int limitreg;
1476 
1477 	if ((win < 0) || (win > 1)) {
1478 		DEVPRINTF((brdev,
1479 		    "cbb_cardbus_mem_open: window out of range %d\n", win));
1480 		return (EINVAL);
1481 	}
1482 
1483 	basereg = win*8 + CBBR_MEMBASE0;
1484 	limitreg = win*8 + CBBR_MEMLIMIT0;
1485 
1486 	pci_write_config(brdev, basereg, start, 4);
1487 	pci_write_config(brdev, limitreg, end, 4);
1488 	return (0);
1489 }
1490 
1491 /*
1492  * XXX The following function belongs in the pci bus layer.
1493  */
1494 static void
1495 cbb_cardbus_auto_open(struct cbb_softc *sc, int type)
1496 {
1497 	uint32_t starts[2];
1498 	uint32_t ends[2];
1499 	struct cbb_reslist *rle;
1500 	int align;
1501 	int prefetchable[2];
1502 	uint32_t reg;
1503 
1504 	starts[0] = starts[1] = 0xffffffff;
1505 	ends[0] = ends[1] = 0;
1506 
1507 	if (type == SYS_RES_MEMORY)
1508 		align = CBB_MEMALIGN;
1509 	else if (type == SYS_RES_IOPORT)
1510 		align = CBB_IOALIGN;
1511 	else
1512 		align = 1;
1513 
1514 	/*
1515 	 * This looks somewhat bogus, and doesn't seem to really respect
1516 	 * alignment.  The alignment stuff is happening too late (it
1517 	 * should happen at allocation time, not activation time) and
1518 	 * this code looks generally to be too complex for the purpose
1519 	 * it surves.
1520 	 */
1521 	SLIST_FOREACH(rle, &sc->rl, link) {
1522 		if (rle->type != type)
1523 			;
1524 		else if (rle->res == NULL) {
1525 			device_printf(sc->dev, "WARNING: Resource not reserved?  "
1526 			    "(type=%d, addr=%lx)\n",
1527 			    rle->type, rman_get_start(rle->res));
1528 		} else if (!(rman_get_flags(rle->res) & RF_ACTIVE)) {
1529 			/* XXX */
1530 		} else if (starts[0] == 0xffffffff) {
1531 			starts[0] = rman_get_start(rle->res);
1532 			ends[0] = rman_get_end(rle->res);
1533 			prefetchable[0] =
1534 			    rman_get_flags(rle->res) & RF_PREFETCHABLE;
1535 		} else if (rman_get_end(rle->res) > ends[0] &&
1536 		    rman_get_start(rle->res) - ends[0] <
1537 		    CBB_AUTO_OPEN_SMALLHOLE && prefetchable[0] ==
1538 		    (rman_get_flags(rle->res) & RF_PREFETCHABLE)) {
1539 			ends[0] = rman_get_end(rle->res);
1540 		} else if (rman_get_start(rle->res) < starts[0] &&
1541 		    starts[0] - rman_get_end(rle->res) <
1542 		    CBB_AUTO_OPEN_SMALLHOLE && prefetchable[0] ==
1543 		    (rman_get_flags(rle->res) & RF_PREFETCHABLE)) {
1544 			starts[0] = rman_get_start(rle->res);
1545 		} else if (starts[1] == 0xffffffff) {
1546 			starts[1] = rman_get_start(rle->res);
1547 			ends[1] = rman_get_end(rle->res);
1548 			prefetchable[1] =
1549 			    rman_get_flags(rle->res) & RF_PREFETCHABLE;
1550 		} else if (rman_get_end(rle->res) > ends[1] &&
1551 		    rman_get_start(rle->res) - ends[1] <
1552 		    CBB_AUTO_OPEN_SMALLHOLE && prefetchable[1] ==
1553 		    (rman_get_flags(rle->res) & RF_PREFETCHABLE)) {
1554 			ends[1] = rman_get_end(rle->res);
1555 		} else if (rman_get_start(rle->res) < starts[1] &&
1556 		    starts[1] - rman_get_end(rle->res) <
1557 		    CBB_AUTO_OPEN_SMALLHOLE && prefetchable[1] ==
1558 		    (rman_get_flags(rle->res) & RF_PREFETCHABLE)) {
1559 			starts[1] = rman_get_start(rle->res);
1560 		} else {
1561 			uint32_t diffs[2];
1562 			int win;
1563 
1564 			diffs[0] = diffs[1] = 0xffffffff;
1565 			if (rman_get_start(rle->res) > ends[0])
1566 				diffs[0] = rman_get_start(rle->res) - ends[0];
1567 			else if (rman_get_end(rle->res) < starts[0])
1568 				diffs[0] = starts[0] - rman_get_end(rle->res);
1569 			if (rman_get_start(rle->res) > ends[1])
1570 				diffs[1] = rman_get_start(rle->res) - ends[1];
1571 			else if (rman_get_end(rle->res) < starts[1])
1572 				diffs[1] = starts[1] - rman_get_end(rle->res);
1573 
1574 			win = (diffs[0] <= diffs[1])?0:1;
1575 			if (rman_get_start(rle->res) > ends[win])
1576 				ends[win] = rman_get_end(rle->res);
1577 			else if (rman_get_end(rle->res) < starts[win])
1578 				starts[win] = rman_get_start(rle->res);
1579 			if (!(rman_get_flags(rle->res) & RF_PREFETCHABLE))
1580 				prefetchable[win] = 0;
1581 		}
1582 
1583 		if (starts[0] != 0xffffffff)
1584 			starts[0] -= starts[0] % align;
1585 		if (starts[1] != 0xffffffff)
1586 			starts[1] -= starts[1] % align;
1587 		if (ends[0] % align != 0)
1588 			ends[0] += align - ends[0] % align - 1;
1589 		if (ends[1] % align != 0)
1590 			ends[1] += align - ends[1] % align - 1;
1591 	}
1592 
1593 	if (type == SYS_RES_MEMORY) {
1594 		cbb_cardbus_mem_open(sc->dev, 0, starts[0], ends[0]);
1595 		cbb_cardbus_mem_open(sc->dev, 1, starts[1], ends[1]);
1596 		reg = pci_read_config(sc->dev, CBBR_BRIDGECTRL, 2);
1597 		reg &= ~(CBBM_BRIDGECTRL_PREFETCH_0|
1598 		    CBBM_BRIDGECTRL_PREFETCH_1);
1599 		reg |= (prefetchable[0]?CBBM_BRIDGECTRL_PREFETCH_0:0)|
1600 		    (prefetchable[1]?CBBM_BRIDGECTRL_PREFETCH_1:0);
1601 		pci_write_config(sc->dev, CBBR_BRIDGECTRL, reg, 2);
1602 	} else if (type == SYS_RES_IOPORT) {
1603 		cbb_cardbus_io_open(sc->dev, 0, starts[0], ends[0]);
1604 		cbb_cardbus_io_open(sc->dev, 1, starts[1], ends[1]);
1605 	}
1606 }
1607 
1608 static int
1609 cbb_cardbus_activate_resource(device_t brdev, device_t child, int type,
1610     int rid, struct resource *res)
1611 {
1612 	int ret;
1613 
1614 	ret = BUS_ACTIVATE_RESOURCE(device_get_parent(brdev), child,
1615 	    type, rid, res);
1616 	if (ret != 0)
1617 		return (ret);
1618 	cbb_cardbus_auto_open(device_get_softc(brdev), type);
1619 	return (0);
1620 }
1621 
1622 static int
1623 cbb_cardbus_deactivate_resource(device_t brdev, device_t child, int type,
1624     int rid, struct resource *res)
1625 {
1626 	int ret;
1627 
1628 	ret = BUS_DEACTIVATE_RESOURCE(device_get_parent(brdev), child,
1629 	    type, rid, res);
1630 	if (ret != 0)
1631 		return (ret);
1632 	cbb_cardbus_auto_open(device_get_softc(brdev), type);
1633 	return (0);
1634 }
1635 
1636 static struct resource *
1637 cbb_cardbus_alloc_resource(device_t brdev, device_t child, int type,
1638     int *rid, u_long start, u_long end, u_long count, u_int flags)
1639 {
1640 	struct cbb_softc *sc = device_get_softc(brdev);
1641 	int tmp;
1642 	struct resource *res;
1643 	u_long align;
1644 
1645 	switch (type) {
1646 	case SYS_RES_IRQ:
1647 		tmp = rman_get_start(sc->irq_res);
1648 		if (start > tmp || end < tmp || count != 1) {
1649 			device_printf(child, "requested interrupt %ld-%ld,"
1650 			    "count = %ld not supported by cbb\n",
1651 			    start, end, count);
1652 			return (NULL);
1653 		}
1654 		start = end = tmp;
1655 		flags |= RF_SHAREABLE;
1656 		break;
1657 	case SYS_RES_IOPORT:
1658 		if (start <= cbb_start_32_io)
1659 			start = cbb_start_32_io;
1660 		if (end < start)
1661 			end = start;
1662 		break;
1663 	case SYS_RES_MEMORY:
1664 		if (start <= cbb_start_mem)
1665 			start = cbb_start_mem;
1666 		if (end < start)
1667 			end = start;
1668 		if (count < CBB_MEMALIGN)
1669 			align = CBB_MEMALIGN;
1670 		else
1671 			align = count;
1672 		if (align > (1 << RF_ALIGNMENT(flags)))
1673 			flags = (flags & ~RF_ALIGNMENT_MASK) |
1674 			    rman_make_alignment_flags(align);
1675 		break;
1676 	}
1677 
1678 	res = BUS_ALLOC_RESOURCE(device_get_parent(brdev), child, type, rid,
1679 	    start, end, count, flags & ~RF_ACTIVE);
1680 	if (res == NULL) {
1681 		printf("cbb alloc res fail\n");
1682 		return (NULL);
1683 	}
1684 	cbb_insert_res(sc, res, type, *rid);
1685 	if (flags & RF_ACTIVE)
1686 		if (bus_activate_resource(child, type, *rid, res) != 0) {
1687 			bus_release_resource(child, type, *rid, res);
1688 			return (NULL);
1689 		}
1690 
1691 	return (res);
1692 }
1693 
1694 static int
1695 cbb_cardbus_release_resource(device_t brdev, device_t child, int type,
1696     int rid, struct resource *res)
1697 {
1698 	struct cbb_softc *sc = device_get_softc(brdev);
1699 	int error;
1700 
1701 	if (rman_get_flags(res) & RF_ACTIVE) {
1702 		error = bus_deactivate_resource(child, type, rid, res);
1703 		if (error != 0)
1704 			return (error);
1705 	}
1706 	cbb_remove_res(sc, res);
1707 	return (BUS_RELEASE_RESOURCE(device_get_parent(brdev), child,
1708 	    type, rid, res));
1709 }
1710 
1711 /************************************************************************/
1712 /* PC Card Power Functions						*/
1713 /************************************************************************/
1714 
1715 static int
1716 cbb_pcic_power_enable_socket(device_t brdev, device_t child)
1717 {
1718 	struct cbb_softc *sc = device_get_softc(brdev);
1719 	int err;
1720 
1721 	DPRINTF(("cbb_pcic_socket_enable:\n"));
1722 
1723 	/* power down/up the socket to reset */
1724 	err = cbb_do_power(brdev);
1725 	if (err)
1726 		return (err);
1727 	exca_reset(&sc->exca, child);
1728 
1729 	return (0);
1730 }
1731 
1732 static void
1733 cbb_pcic_power_disable_socket(device_t brdev, device_t child)
1734 {
1735 	struct cbb_softc *sc = device_get_softc(brdev);
1736 
1737 	DPRINTF(("cbb_pcic_socket_disable\n"));
1738 
1739 	/* reset signal asserting... */
1740 	exca_clrb(&sc->exca, EXCA_INTR, EXCA_INTR_RESET);
1741 	DELAY(2*1000);
1742 
1743 	/* power down the socket */
1744 	cbb_power(brdev, CARD_OFF);
1745 	exca_clrb(&sc->exca, EXCA_PWRCTL, EXCA_PWRCTL_OE);
1746 
1747 	/* wait 300ms until power fails (Tpf). */
1748 	DELAY(300 * 1000);
1749 }
1750 
1751 /************************************************************************/
1752 /* POWER methods							*/
1753 /************************************************************************/
1754 
1755 static int
1756 cbb_power_enable_socket(device_t brdev, device_t child)
1757 {
1758 	struct cbb_softc *sc = device_get_softc(brdev);
1759 
1760 	if (sc->flags & CBB_16BIT_CARD)
1761 		return (cbb_pcic_power_enable_socket(brdev, child));
1762 	else
1763 		return (cbb_cardbus_power_enable_socket(brdev, child));
1764 }
1765 
1766 static void
1767 cbb_power_disable_socket(device_t brdev, device_t child)
1768 {
1769 	struct cbb_softc *sc = device_get_softc(brdev);
1770 	if (sc->flags & CBB_16BIT_CARD)
1771 		cbb_pcic_power_disable_socket(brdev, child);
1772 	else
1773 		cbb_cardbus_power_disable_socket(brdev, child);
1774 }
1775 
1776 static int
1777 cbb_pcic_activate_resource(device_t brdev, device_t child, int type, int rid,
1778     struct resource *res)
1779 {
1780 	struct cbb_softc *sc = device_get_softc(brdev);
1781 	return (exca_activate_resource(&sc->exca, child, type, rid, res));
1782 }
1783 
1784 static int
1785 cbb_pcic_deactivate_resource(device_t brdev, device_t child, int type,
1786     int rid, struct resource *res)
1787 {
1788 	struct cbb_softc *sc = device_get_softc(brdev);
1789 	return (exca_deactivate_resource(&sc->exca, child, type, rid, res));
1790 }
1791 
1792 static struct resource *
1793 cbb_pcic_alloc_resource(device_t brdev, device_t child, int type, int *rid,
1794     u_long start, u_long end, u_long count, u_int flags)
1795 {
1796 	struct resource *res = NULL;
1797 	struct cbb_softc *sc = device_get_softc(brdev);
1798 	int align;
1799 	int tmp;
1800 
1801 	switch (type) {
1802 	case SYS_RES_MEMORY:
1803 		if (start < cbb_start_mem)
1804 			start = cbb_start_mem;
1805 		if (end < start)
1806 			end = start;
1807 		if (count < CBB_MEMALIGN)
1808 			align = CBB_MEMALIGN;
1809 		else
1810 			align = count;
1811 		if (align > (1 << RF_ALIGNMENT(flags)))
1812 			flags = (flags & ~RF_ALIGNMENT_MASK) |
1813 			    rman_make_alignment_flags(align);
1814 		break;
1815 	case SYS_RES_IOPORT:
1816 		if (start < cbb_start_16_io)
1817 			start = cbb_start_16_io;
1818 		if (end < start)
1819 			end = start;
1820 		break;
1821 	case SYS_RES_IRQ:
1822 		tmp = rman_get_start(sc->irq_res);
1823 		if (start > tmp || end < tmp || count != 1) {
1824 			device_printf(child, "requested interrupt %ld-%ld,"
1825 			    "count = %ld not supported by cbb\n",
1826 			    start, end, count);
1827 			return (NULL);
1828 		}
1829 		flags |= RF_SHAREABLE;
1830 		start = end = rman_get_start(sc->irq_res);
1831 		break;
1832 	}
1833 	res = BUS_ALLOC_RESOURCE(device_get_parent(brdev), child, type, rid,
1834 	    start, end, count, flags & ~RF_ACTIVE);
1835 	if (res == NULL)
1836 		return (NULL);
1837 	cbb_insert_res(sc, res, type, *rid);
1838 	if (flags & RF_ACTIVE) {
1839 		if (bus_activate_resource(child, type, *rid, res) != 0) {
1840 			bus_release_resource(child, type, *rid, res);
1841 			return (NULL);
1842 		}
1843 	}
1844 
1845 	return (res);
1846 }
1847 
1848 static int
1849 cbb_pcic_release_resource(device_t brdev, device_t child, int type,
1850     int rid, struct resource *res)
1851 {
1852 	struct cbb_softc *sc = device_get_softc(brdev);
1853 	int error;
1854 
1855 	if (rman_get_flags(res) & RF_ACTIVE) {
1856 		error = bus_deactivate_resource(child, type, rid, res);
1857 		if (error != 0)
1858 			return (error);
1859 	}
1860 	cbb_remove_res(sc, res);
1861 	return (BUS_RELEASE_RESOURCE(device_get_parent(brdev), child,
1862 	    type, rid, res));
1863 }
1864 
1865 /************************************************************************/
1866 /* PC Card methods							*/
1867 /************************************************************************/
1868 
1869 static int
1870 cbb_pcic_set_res_flags(device_t brdev, device_t child, int type, int rid,
1871     uint32_t flags)
1872 {
1873 	struct cbb_softc *sc = device_get_softc(brdev);
1874 	struct resource *res;
1875 
1876 	if (type != SYS_RES_MEMORY)
1877 		return (EINVAL);
1878 	res = cbb_find_res(sc, type, rid);
1879 	if (res == NULL) {
1880 		device_printf(brdev,
1881 		    "set_res_flags: specified rid not found\n");
1882 		return (ENOENT);
1883 	}
1884 	return (exca_mem_set_flags(&sc->exca, res, flags));
1885 }
1886 
1887 static int
1888 cbb_pcic_set_memory_offset(device_t brdev, device_t child, int rid,
1889     uint32_t cardaddr, uint32_t *deltap)
1890 {
1891 	struct cbb_softc *sc = device_get_softc(brdev);
1892 	struct resource *res;
1893 
1894 	res = cbb_find_res(sc, SYS_RES_MEMORY, rid);
1895 	if (res == NULL) {
1896 		device_printf(brdev,
1897 		    "set_memory_offset: specified rid not found\n");
1898 		return (ENOENT);
1899 	}
1900 	return (exca_mem_set_offset(&sc->exca, res, cardaddr, deltap));
1901 }
1902 
1903 /************************************************************************/
1904 /* BUS Methods								*/
1905 /************************************************************************/
1906 
1907 
1908 static int
1909 cbb_activate_resource(device_t brdev, device_t child, int type, int rid,
1910     struct resource *r)
1911 {
1912 	struct cbb_softc *sc = device_get_softc(brdev);
1913 
1914 	if (sc->flags & CBB_16BIT_CARD)
1915 		return (cbb_pcic_activate_resource(brdev, child, type, rid, r));
1916 	else
1917 		return (cbb_cardbus_activate_resource(brdev, child, type, rid,
1918 		    r));
1919 }
1920 
1921 static int
1922 cbb_deactivate_resource(device_t brdev, device_t child, int type,
1923     int rid, struct resource *r)
1924 {
1925 	struct cbb_softc *sc = device_get_softc(brdev);
1926 
1927 	if (sc->flags & CBB_16BIT_CARD)
1928 		return (cbb_pcic_deactivate_resource(brdev, child, type,
1929 		    rid, r));
1930 	else
1931 		return (cbb_cardbus_deactivate_resource(brdev, child, type,
1932 		    rid, r));
1933 }
1934 
1935 static struct resource *
1936 cbb_alloc_resource(device_t brdev, device_t child, int type, int *rid,
1937     u_long start, u_long end, u_long count, u_int flags)
1938 {
1939 	struct cbb_softc *sc = device_get_softc(brdev);
1940 
1941 	if (sc->flags & CBB_16BIT_CARD)
1942 		return (cbb_pcic_alloc_resource(brdev, child, type, rid,
1943 		    start, end, count, flags));
1944 	else
1945 		return (cbb_cardbus_alloc_resource(brdev, child, type, rid,
1946 		    start, end, count, flags));
1947 }
1948 
1949 static int
1950 cbb_release_resource(device_t brdev, device_t child, int type, int rid,
1951     struct resource *r)
1952 {
1953 	struct cbb_softc *sc = device_get_softc(brdev);
1954 
1955 	if (sc->flags & CBB_16BIT_CARD)
1956 		return (cbb_pcic_release_resource(brdev, child, type,
1957 		    rid, r));
1958 	else
1959 		return (cbb_cardbus_release_resource(brdev, child, type,
1960 		    rid, r));
1961 }
1962 
1963 static int
1964 cbb_read_ivar(device_t brdev, device_t child, int which, uintptr_t *result)
1965 {
1966 	struct cbb_softc *sc = device_get_softc(brdev);
1967 
1968 	switch (which) {
1969 	case PCIB_IVAR_BUS:
1970 		*result = sc->secbus;
1971 		return (0);
1972 	}
1973 	return (ENOENT);
1974 }
1975 
1976 static int
1977 cbb_write_ivar(device_t brdev, device_t child, int which, uintptr_t value)
1978 {
1979 	struct cbb_softc *sc = device_get_softc(brdev);
1980 
1981 	switch (which) {
1982 	case PCIB_IVAR_BUS:
1983 		sc->secbus = value;
1984 		break;
1985 	}
1986 	return (ENOENT);
1987 }
1988 
1989 /************************************************************************/
1990 /* PCI compat methods							*/
1991 /************************************************************************/
1992 
1993 static int
1994 cbb_maxslots(device_t brdev)
1995 {
1996 	return (0);
1997 }
1998 
1999 static uint32_t
2000 cbb_read_config(device_t brdev, int b, int s, int f, int reg, int width)
2001 {
2002 	/*
2003 	 * Pass through to the next ppb up the chain (i.e. our grandparent).
2004 	 */
2005 	return (PCIB_READ_CONFIG(device_get_parent(device_get_parent(brdev)),
2006 	    b, s, f, reg, width));
2007 }
2008 
2009 static void
2010 cbb_write_config(device_t brdev, int b, int s, int f, int reg, uint32_t val,
2011     int width)
2012 {
2013 	/*
2014 	 * Pass through to the next ppb up the chain (i.e. our grandparent).
2015 	 */
2016 	PCIB_WRITE_CONFIG(device_get_parent(device_get_parent(brdev)),
2017 	    b, s, f, reg, val, width);
2018 }
2019 
2020 static int
2021 cbb_suspend(device_t self)
2022 {
2023 	int			error = 0;
2024 	struct cbb_softc	*sc = device_get_softc(self);
2025 
2026 	cbb_set(sc, CBB_SOCKET_MASK, 0);	/* Quiet hardware */
2027 	bus_teardown_intr(self, sc->irq_res, sc->intrhand);
2028 	sc->flags &= ~CBB_CARD_OK;		/* Card is bogus now */
2029 	error = bus_generic_suspend(self);
2030 	return (error);
2031 }
2032 
2033 static int
2034 cbb_resume(device_t self)
2035 {
2036 	int	error = 0;
2037 	struct cbb_softc *sc = (struct cbb_softc *)device_get_softc(self);
2038 	uint32_t tmp;
2039 
2040 	/*
2041 	 * Some BIOSes will not save the BARs for the pci chips, so we
2042 	 * must do it ourselves.  If the BAR is reset to 0 for an I/O
2043 	 * device, it will read back as 0x1, so no explicit test for
2044 	 * memory devices are needed.
2045 	 *
2046 	 * Note: The PCI bus code should do this automatically for us on
2047 	 * suspend/resume, but until it does, we have to cope.
2048 	 */
2049 	pci_write_config(self, CBBR_SOCKBASE, rman_get_start(sc->base_res), 4);
2050 	DEVPRINTF((self, "PCI Memory allocated: %08lx\n",
2051 	    rman_get_start(sc->base_res)));
2052 
2053 	cbb_chipinit(sc);
2054 
2055 	/* reset interrupt -- Do we really need to do this? */
2056 	tmp = cbb_get(sc, CBB_SOCKET_EVENT);
2057 	cbb_set(sc, CBB_SOCKET_EVENT, tmp);
2058 
2059 	/* re-establish the interrupt. */
2060 	if (bus_setup_intr(self, sc->irq_res, INTR_TYPE_AV | INTR_MPSAFE,
2061 	    cbb_intr, sc, &sc->intrhand)) {
2062 		device_printf(self, "couldn't re-establish interrupt");
2063 		bus_release_resource(self, SYS_RES_IRQ, 0, sc->irq_res);
2064 		bus_release_resource(self, SYS_RES_MEMORY, CBBR_SOCKBASE,
2065 		    sc->base_res);
2066 		sc->irq_res = NULL;
2067 		sc->base_res = NULL;
2068 		return (ENOMEM);
2069 	}
2070 
2071 	/* CSC Interrupt: Card detect interrupt on */
2072 	cbb_setb(sc, CBB_SOCKET_MASK, CBB_SOCKET_MASK_CD);
2073 
2074 	/* Signal the thread to wakeup. */
2075 	mtx_lock(&sc->mtx);
2076 	cv_signal(&sc->cv);
2077 	mtx_unlock(&sc->mtx);
2078 
2079 	error = bus_generic_resume(self);
2080 
2081 	return (error);
2082 }
2083 
2084 static int
2085 cbb_child_present(device_t self)
2086 {
2087 	struct cbb_softc *sc = (struct cbb_softc *)device_get_softc(self);
2088 	uint32_t sockstate;
2089 
2090 	sockstate = cbb_get(sc, CBB_SOCKET_STATE);
2091 	return (CBB_CARD_PRESENT(sockstate) &&
2092 	  (sc->flags & CBB_CARD_OK) == CBB_CARD_OK);
2093 }
2094 
2095 static device_method_t cbb_methods[] = {
2096 	/* Device interface */
2097 	DEVMETHOD(device_probe,			cbb_probe),
2098 	DEVMETHOD(device_attach,		cbb_attach),
2099 	DEVMETHOD(device_detach,		cbb_detach),
2100 	DEVMETHOD(device_shutdown,		cbb_shutdown),
2101 	DEVMETHOD(device_suspend,		cbb_suspend),
2102 	DEVMETHOD(device_resume,		cbb_resume),
2103 
2104 	/* bus methods */
2105 	DEVMETHOD(bus_print_child,		bus_generic_print_child),
2106 	DEVMETHOD(bus_read_ivar,		cbb_read_ivar),
2107 	DEVMETHOD(bus_write_ivar,		cbb_write_ivar),
2108 	DEVMETHOD(bus_alloc_resource,		cbb_alloc_resource),
2109 	DEVMETHOD(bus_release_resource,		cbb_release_resource),
2110 	DEVMETHOD(bus_activate_resource,	cbb_activate_resource),
2111 	DEVMETHOD(bus_deactivate_resource,	cbb_deactivate_resource),
2112 	DEVMETHOD(bus_driver_added,		cbb_driver_added),
2113 	DEVMETHOD(bus_child_detached,		cbb_child_detached),
2114 	DEVMETHOD(bus_setup_intr,		cbb_setup_intr),
2115 	DEVMETHOD(bus_teardown_intr,		cbb_teardown_intr),
2116 	DEVMETHOD(bus_child_present,		cbb_child_present),
2117 
2118 	/* 16-bit card interface */
2119 	DEVMETHOD(card_set_res_flags,		cbb_pcic_set_res_flags),
2120 	DEVMETHOD(card_set_memory_offset,	cbb_pcic_set_memory_offset),
2121 
2122 	/* power interface */
2123 	DEVMETHOD(power_enable_socket,		cbb_power_enable_socket),
2124 	DEVMETHOD(power_disable_socket,		cbb_power_disable_socket),
2125 
2126 	/* pcib compatibility interface */
2127 	DEVMETHOD(pcib_maxslots,		cbb_maxslots),
2128 	DEVMETHOD(pcib_read_config,		cbb_read_config),
2129 	DEVMETHOD(pcib_write_config,		cbb_write_config),
2130 	{0,0}
2131 };
2132 
2133 static driver_t cbb_driver = {
2134 	"cbb",
2135 	cbb_methods,
2136 	sizeof(struct cbb_softc)
2137 };
2138 
2139 static devclass_t cbb_devclass;
2140 
2141 DRIVER_MODULE(cbb, pci, cbb_driver, cbb_devclass, 0, 0);
2142 MODULE_VERSION(cbb, 1);
2143 MODULE_DEPEND(cbb, exca, 1, 1, 1);
2144