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