xref: /freebsd/sys/dev/pccbb/pccbb.c (revision d8a0fe102c0cfdfcd5b818f850eff09d8536c9bc)
1 /*-
2  * SPDX-License-Identifier: BSD-2-Clause-FreeBSD
3  *
4  * Copyright (c) 2002-2004 M. Warner Losh.
5  * Copyright (c) 2000-2001 Jonathan Chen.
6  * All rights reserved.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in the
15  *    documentation and/or other materials provided with the 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
21  * FOR 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 /*-
32  * Copyright (c) 1998, 1999 and 2000
33  *      HAYAKAWA Koichi.  All rights reserved.
34  *
35  * Redistribution and use in source and binary forms, with or without
36  * modification, are permitted provided that the following conditions
37  * are met:
38  * 1. Redistributions of source code must retain the above copyright
39  *    notice, this list of conditions and the following disclaimer.
40  * 2. Redistributions in binary form must reproduce the above copyright
41  *    notice, this list of conditions and the following disclaimer in the
42  *    documentation and/or other materials provided with the distribution.
43  * 3. All advertising materials mentioning features or use of this software
44  *    must display the following acknowledgement:
45  *	This product includes software developed by HAYAKAWA Koichi.
46  * 4. The name of the author may not be used to endorse or promote products
47  *    derived from this software without specific prior written permission.
48  *
49  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
50  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
51  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
52  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
53  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
54  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
55  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
56  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
57  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
58  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
59  */
60 
61 /*
62  * Driver for PCI to CardBus Bridge chips
63  * and PCI to PCMCIA Bridge chips
64  * and ISA to PCMCIA host adapters
65  * and C Bus to PCMCIA host adapters
66  *
67  * References:
68  *  TI Datasheets:
69  *   http://www-s.ti.com/cgi-bin/sc/generic2.cgi?family=PCI+CARDBUS+CONTROLLERS
70  *
71  * Written by Jonathan Chen <jon@freebsd.org>
72  * The author would like to acknowledge:
73  *  * HAYAKAWA Koichi: Author of the NetBSD code for the same thing
74  *  * Warner Losh: Newbus/newcard guru and author of the pccard side of things
75  *  * YAMAMOTO Shigeru: Author of another FreeBSD cardbus driver
76  *  * David Cross: Author of the initial ugly hack for a specific cardbus card
77  */
78 
79 #include <sys/cdefs.h>
80 __FBSDID("$FreeBSD$");
81 
82 #include <sys/param.h>
83 #include <sys/bus.h>
84 #include <sys/condvar.h>
85 #include <sys/errno.h>
86 #include <sys/kernel.h>
87 #include <sys/module.h>
88 #include <sys/kthread.h>
89 #include <sys/interrupt.h>
90 #include <sys/lock.h>
91 #include <sys/malloc.h>
92 #include <sys/mutex.h>
93 #include <sys/proc.h>
94 #include <sys/rman.h>
95 #include <sys/sysctl.h>
96 #include <sys/systm.h>
97 #include <machine/bus.h>
98 #include <machine/resource.h>
99 
100 #include <dev/pci/pcireg.h>
101 #include <dev/pci/pcivar.h>
102 #include <dev/pci/pcib_private.h>
103 
104 #include <dev/pccard/pccardreg.h>
105 #include <dev/pccard/pccardvar.h>
106 
107 #include <dev/exca/excareg.h>
108 #include <dev/exca/excavar.h>
109 
110 #include <dev/pccbb/pccbbreg.h>
111 #include <dev/pccbb/pccbbvar.h>
112 
113 #include "power_if.h"
114 #include "card_if.h"
115 #include "pcib_if.h"
116 
117 #define	DPRINTF(x) do { if (cbb_debug) printf x; } while (0)
118 #define	DEVPRINTF(x) do { if (cbb_debug) device_printf x; } while (0)
119 
120 #define	PCI_MASK_CONFIG(DEV,REG,MASK,SIZE)				\
121 	pci_write_config(DEV, REG, pci_read_config(DEV, REG, SIZE) MASK, SIZE)
122 #define	PCI_MASK2_CONFIG(DEV,REG,MASK1,MASK2,SIZE)			\
123 	pci_write_config(DEV, REG, (					\
124 		pci_read_config(DEV, REG, SIZE) MASK1) MASK2, SIZE)
125 
126 #define CBB_CARD_PRESENT(s) ((s & CBB_STATE_CD) == 0)
127 
128 #define CBB_START_MEM	0x88000000
129 #define CBB_START_32_IO 0x1000
130 #define CBB_START_16_IO 0x100
131 
132 devclass_t cbb_devclass;
133 
134 /* sysctl vars */
135 static SYSCTL_NODE(_hw, OID_AUTO, cbb, CTLFLAG_RD, 0, "CBB parameters");
136 
137 /* There's no way to say TUNEABLE_LONG to get the right types */
138 u_long cbb_start_mem = CBB_START_MEM;
139 SYSCTL_ULONG(_hw_cbb, OID_AUTO, start_memory, CTLFLAG_RWTUN,
140     &cbb_start_mem, CBB_START_MEM,
141     "Starting address for memory allocations");
142 
143 u_long cbb_start_16_io = CBB_START_16_IO;
144 SYSCTL_ULONG(_hw_cbb, OID_AUTO, start_16_io, CTLFLAG_RWTUN,
145     &cbb_start_16_io, CBB_START_16_IO,
146     "Starting ioport for 16-bit cards");
147 
148 u_long cbb_start_32_io = CBB_START_32_IO;
149 SYSCTL_ULONG(_hw_cbb, OID_AUTO, start_32_io, CTLFLAG_RWTUN,
150     &cbb_start_32_io, CBB_START_32_IO,
151     "Starting ioport for 32-bit cards");
152 
153 int cbb_debug = 0;
154 SYSCTL_INT(_hw_cbb, OID_AUTO, debug, CTLFLAG_RWTUN, &cbb_debug, 0,
155     "Verbose cardbus bridge debugging");
156 
157 static void	cbb_insert(struct cbb_softc *sc);
158 static void	cbb_removal(struct cbb_softc *sc);
159 static uint32_t	cbb_detect_voltage(device_t brdev);
160 static int	cbb_cardbus_reset_power(device_t brdev, device_t child, int on);
161 static int	cbb_cardbus_io_open(device_t brdev, int win, uint32_t start,
162 		    uint32_t end);
163 static int	cbb_cardbus_mem_open(device_t brdev, int win,
164 		    uint32_t start, uint32_t end);
165 static void	cbb_cardbus_auto_open(struct cbb_softc *sc, int type);
166 static int	cbb_cardbus_activate_resource(device_t brdev, device_t child,
167 		    int type, int rid, struct resource *res);
168 static int	cbb_cardbus_deactivate_resource(device_t brdev,
169 		    device_t child, int type, int rid, struct resource *res);
170 static struct resource	*cbb_cardbus_alloc_resource(device_t brdev,
171 		    device_t child, int type, int *rid, rman_res_t start,
172 		    rman_res_t end, rman_res_t count, u_int flags);
173 static int	cbb_cardbus_release_resource(device_t brdev, device_t child,
174 		    int type, int rid, struct resource *res);
175 static int	cbb_cardbus_power_enable_socket(device_t brdev,
176 		    device_t child);
177 static int	cbb_cardbus_power_disable_socket(device_t brdev,
178 		    device_t child);
179 static int	cbb_func_filt(void *arg);
180 static void	cbb_func_intr(void *arg);
181 
182 static void
183 cbb_remove_res(struct cbb_softc *sc, struct resource *res)
184 {
185 	struct cbb_reslist *rle;
186 
187 	SLIST_FOREACH(rle, &sc->rl, link) {
188 		if (rle->res == res) {
189 			SLIST_REMOVE(&sc->rl, rle, cbb_reslist, link);
190 			free(rle, M_DEVBUF);
191 			return;
192 		}
193 	}
194 }
195 
196 static struct resource *
197 cbb_find_res(struct cbb_softc *sc, int type, int rid)
198 {
199 	struct cbb_reslist *rle;
200 
201 	SLIST_FOREACH(rle, &sc->rl, link)
202 		if (SYS_RES_MEMORY == rle->type && rid == rle->rid)
203 			return (rle->res);
204 	return (NULL);
205 }
206 
207 static void
208 cbb_insert_res(struct cbb_softc *sc, struct resource *res, int type,
209     int rid)
210 {
211 	struct cbb_reslist *rle;
212 
213 	/*
214 	 * Need to record allocated resource so we can iterate through
215 	 * it later.
216 	 */
217 	rle = malloc(sizeof(struct cbb_reslist), M_DEVBUF, M_NOWAIT);
218 	if (rle == NULL)
219 		panic("cbb_cardbus_alloc_resource: can't record entry!");
220 	rle->res = res;
221 	rle->type = type;
222 	rle->rid = rid;
223 	SLIST_INSERT_HEAD(&sc->rl, rle, link);
224 }
225 
226 static void
227 cbb_destroy_res(struct cbb_softc *sc)
228 {
229 	struct cbb_reslist *rle;
230 
231 	while ((rle = SLIST_FIRST(&sc->rl)) != NULL) {
232 		device_printf(sc->dev, "Danger Will Robinson: Resource "
233 		    "left allocated!  This is a bug... "
234 		    "(rid=%x, type=%d, addr=%jx)\n", rle->rid, rle->type,
235 		    rman_get_start(rle->res));
236 		SLIST_REMOVE_HEAD(&sc->rl, link);
237 		free(rle, M_DEVBUF);
238 	}
239 }
240 
241 /*
242  * Disable function interrupts by telling the bridge to generate IRQ1
243  * interrupts.  These interrupts aren't really generated by the chip, since
244  * IRQ1 is reserved.  Some chipsets assert INTA# inappropriately during
245  * initialization, so this helps to work around the problem.
246  *
247  * XXX We can't do this workaround for all chipsets, because this
248  * XXX causes interference with the keyboard because somechipsets will
249  * XXX actually signal IRQ1 over their serial interrupt connections to
250  * XXX the south bridge.  Disable it it for now.
251  */
252 void
253 cbb_disable_func_intr(struct cbb_softc *sc)
254 {
255 #if 0
256 	uint8_t reg;
257 
258 	reg = (exca_getb(&sc->exca[0], EXCA_INTR) & ~EXCA_INTR_IRQ_MASK) |
259 	    EXCA_INTR_IRQ_RESERVED1;
260 	exca_putb(&sc->exca[0], EXCA_INTR, reg);
261 #endif
262 }
263 
264 /*
265  * Enable function interrupts.  We turn on function interrupts when the card
266  * requests an interrupt.  The PCMCIA standard says that we should set
267  * the lower 4 bits to 0 to route via PCI.  Note: we call this for both
268  * CardBus and R2 (PC Card) cases, but it should have no effect on CardBus
269  * cards.
270  */
271 static void
272 cbb_enable_func_intr(struct cbb_softc *sc)
273 {
274 	uint8_t reg;
275 
276 	reg = (exca_getb(&sc->exca[0], EXCA_INTR) & ~EXCA_INTR_IRQ_MASK) |
277 	    EXCA_INTR_IRQ_NONE;
278 	exca_putb(&sc->exca[0], EXCA_INTR, reg);
279 }
280 
281 int
282 cbb_detach(device_t brdev)
283 {
284 	struct cbb_softc *sc = device_get_softc(brdev);
285 	device_t *devlist;
286 	int tmp, tries, error, numdevs;
287 
288 	/*
289 	 * Before we delete the children (which we have to do because
290 	 * attach doesn't check for children busses correctly), we have
291 	 * to detach the children.  Even if we didn't need to delete the
292 	 * children, we have to detach them.
293 	 */
294 	error = bus_generic_detach(brdev);
295 	if (error != 0)
296 		return (error);
297 
298 	/*
299 	 * Since the attach routine doesn't search for children before it
300 	 * attaches them to this device, we must delete them here in order
301 	 * for the kldload/unload case to work.  If we failed to do that, then
302 	 * we'd get duplicate devices when cbb.ko was reloaded.
303 	 */
304 	tries = 10;
305 	do {
306 		error = device_get_children(brdev, &devlist, &numdevs);
307 		if (error == 0)
308 			break;
309 		/*
310 		 * Try hard to cope with low memory.
311 		 */
312 		if (error == ENOMEM) {
313 			pause("cbbnomem", 1);
314 			continue;
315 		}
316 	} while (tries-- > 0);
317 	for (tmp = 0; tmp < numdevs; tmp++)
318 		device_delete_child(brdev, devlist[tmp]);
319 	free(devlist, M_TEMP);
320 
321 	/* Turn off the interrupts */
322 	cbb_set(sc, CBB_SOCKET_MASK, 0);
323 
324 	/* reset 16-bit pcmcia bus */
325 	exca_clrb(&sc->exca[0], EXCA_INTR, EXCA_INTR_RESET);
326 
327 	/* turn off power */
328 	cbb_power(brdev, CARD_OFF);
329 
330 	/* Ack the interrupt */
331 	cbb_set(sc, CBB_SOCKET_EVENT, 0xffffffff);
332 
333 	/*
334 	 * Wait for the thread to die.  kproc_exit will do a wakeup
335 	 * on the event thread's struct proc * so that we know it is
336 	 * safe to proceed.  IF the thread is running, set the please
337 	 * die flag and wait for it to comply.  Since the wakeup on
338 	 * the event thread happens only in kproc_exit, we don't
339 	 * need to loop here.
340 	 */
341 	bus_teardown_intr(brdev, sc->irq_res, sc->intrhand);
342 	mtx_lock(&sc->mtx);
343 	sc->flags |= CBB_KTHREAD_DONE;
344 	while (sc->flags & CBB_KTHREAD_RUNNING) {
345 		DEVPRINTF((sc->dev, "Waiting for thread to die\n"));
346 		wakeup(&sc->intrhand);
347 		msleep(sc->event_thread, &sc->mtx, PWAIT, "cbbun", 0);
348 	}
349 	mtx_unlock(&sc->mtx);
350 
351 	bus_release_resource(brdev, SYS_RES_IRQ, 0, sc->irq_res);
352 	bus_release_resource(brdev, SYS_RES_MEMORY, CBBR_SOCKBASE,
353 	    sc->base_res);
354 	mtx_destroy(&sc->mtx);
355 	return (0);
356 }
357 
358 int
359 cbb_setup_intr(device_t dev, device_t child, struct resource *irq,
360   int flags, driver_filter_t *filt, driver_intr_t *intr, void *arg,
361    void **cookiep)
362 {
363 	struct cbb_intrhand *ih;
364 	struct cbb_softc *sc = device_get_softc(dev);
365 	int err;
366 
367 	if (filt == NULL && intr == NULL)
368 		return (EINVAL);
369 	ih = malloc(sizeof(struct cbb_intrhand), M_DEVBUF, M_NOWAIT);
370 	if (ih == NULL)
371 		return (ENOMEM);
372 	*cookiep = ih;
373 	ih->filt = filt;
374 	ih->intr = intr;
375 	ih->arg = arg;
376 	ih->sc = sc;
377 	/*
378 	 * XXX need to turn on ISA interrupts, if we ever support them, but
379 	 * XXX for now that's all we need to do.
380 	 */
381 	err = BUS_SETUP_INTR(device_get_parent(dev), child, irq, flags,
382 	    filt ? cbb_func_filt : NULL, intr ? cbb_func_intr : NULL, ih,
383 	    &ih->cookie);
384 	if (err != 0) {
385 		free(ih, M_DEVBUF);
386 		return (err);
387 	}
388 	cbb_enable_func_intr(sc);
389 	sc->cardok = 1;
390 	return 0;
391 }
392 
393 int
394 cbb_teardown_intr(device_t dev, device_t child, struct resource *irq,
395     void *cookie)
396 {
397 	struct cbb_intrhand *ih;
398 	int err;
399 
400 	/* XXX Need to do different things for ISA interrupts. */
401 	ih = (struct cbb_intrhand *) cookie;
402 	err = BUS_TEARDOWN_INTR(device_get_parent(dev), child, irq,
403 	    ih->cookie);
404 	if (err != 0)
405 		return (err);
406 	free(ih, M_DEVBUF);
407 	return (0);
408 }
409 
410 
411 void
412 cbb_driver_added(device_t brdev, driver_t *driver)
413 {
414 	struct cbb_softc *sc = device_get_softc(brdev);
415 	device_t *devlist;
416 	device_t dev;
417 	int tmp;
418 	int numdevs;
419 	int wake = 0;
420 
421 	DEVICE_IDENTIFY(driver, brdev);
422 	tmp = device_get_children(brdev, &devlist, &numdevs);
423 	if (tmp != 0) {
424 		device_printf(brdev, "Cannot get children list, no reprobe\n");
425 		return;
426 	}
427 	for (tmp = 0; tmp < numdevs; tmp++) {
428 		dev = devlist[tmp];
429 		if (device_get_state(dev) == DS_NOTPRESENT &&
430 		    device_probe_and_attach(dev) == 0)
431 			wake++;
432 	}
433 	free(devlist, M_TEMP);
434 
435 	if (wake > 0)
436 		wakeup(&sc->intrhand);
437 }
438 
439 void
440 cbb_child_detached(device_t brdev, device_t child)
441 {
442 	struct cbb_softc *sc = device_get_softc(brdev);
443 
444 	/* I'm not sure we even need this */
445 	if (child != sc->cbdev && child != sc->exca[0].pccarddev)
446 		device_printf(brdev, "Unknown child detached: %s\n",
447 		    device_get_nameunit(child));
448 }
449 
450 /************************************************************************/
451 /* Kthreads								*/
452 /************************************************************************/
453 
454 void
455 cbb_event_thread(void *arg)
456 {
457 	struct cbb_softc *sc = arg;
458 	uint32_t status;
459 	int err;
460 	int not_a_card = 0;
461 
462 	/*
463 	 * We need to act as a power sequencer on startup.  Delay 2s/channel
464 	 * to ensure the other channels have had a chance to come up.  We likely
465 	 * should add a lock that's shared on a per-slot basis so that only
466 	 * one power event can happen per slot at a time.
467 	 */
468 	pause("cbbstart", hz * device_get_unit(sc->dev) * 2);
469 	mtx_lock(&sc->mtx);
470 	sc->flags |= CBB_KTHREAD_RUNNING;
471 	while ((sc->flags & CBB_KTHREAD_DONE) == 0) {
472 		mtx_unlock(&sc->mtx);
473 		/*
474 		 * We take out Giant here because we need it deep,
475 		 * down in the bowels of the vm system for mapping the
476 		 * memory we need to read the CIS.  In addition, since
477 		 * we are adding/deleting devices from the dev tree,
478 		 * and that code isn't MP safe, we have to hold Giant.
479 		 */
480 		mtx_lock(&Giant);
481 		status = cbb_get(sc, CBB_SOCKET_STATE);
482 		DPRINTF(("Status is 0x%x\n", status));
483 		if (!CBB_CARD_PRESENT(status)) {
484 			not_a_card = 0;		/* We know card type */
485 			cbb_removal(sc);
486 		} else if (status & CBB_STATE_NOT_A_CARD) {
487 			/*
488 			 * Up to 10 times, try to rescan the card when we see
489 			 * NOT_A_CARD.  10 is somehwat arbitrary.  When this
490 			 * pathology hits, there's a ~40% chance each try will
491 			 * fail.  10 tries takes about 5s and results in a
492 			 * 99.99% certainty of the results.
493 			 */
494 			if (not_a_card++ < 10) {
495 				DEVPRINTF((sc->dev,
496 				    "Not a card bit set, rescanning\n"));
497 				cbb_setb(sc, CBB_SOCKET_FORCE, CBB_FORCE_CV_TEST);
498 			} else {
499 				device_printf(sc->dev,
500 				    "Can't determine card type\n");
501 			}
502 		} else {
503 			not_a_card = 0;		/* We know card type */
504 			cbb_insert(sc);
505 		}
506 		mtx_unlock(&Giant);
507 
508 		/*
509 		 * First time through we need to tell mountroot that we're
510 		 * done.
511 		 */
512 		if (sc->sc_root_token) {
513 			root_mount_rel(sc->sc_root_token);
514 			sc->sc_root_token = NULL;
515 		}
516 
517 		/*
518 		 * Wait until it has been 250ms since the last time we
519 		 * get an interrupt.  We handle the rest of the interrupt
520 		 * at the top of the loop.  Although we clear the bit in the
521 		 * ISR, we signal sc->cv from the detach path after we've
522 		 * set the CBB_KTHREAD_DONE bit, so we can't do a simple
523 		 * 250ms sleep here.
524 		 *
525 		 * In our ISR, we turn off the card changed interrupt.  Turn
526 		 * them back on here before we wait for them to happen.  We
527 		 * turn them on/off so that we can tolerate a large latency
528 		 * between the time we signal cbb_event_thread and it gets
529 		 * a chance to run.
530 		 */
531 		mtx_lock(&sc->mtx);
532 		cbb_setb(sc, CBB_SOCKET_MASK, CBB_SOCKET_MASK_CD | CBB_SOCKET_MASK_CSTS);
533 		msleep(&sc->intrhand, &sc->mtx, 0, "-", 0);
534 		err = 0;
535 		while (err != EWOULDBLOCK &&
536 		    (sc->flags & CBB_KTHREAD_DONE) == 0)
537 			err = msleep(&sc->intrhand, &sc->mtx, 0, "-", hz / 5);
538 	}
539 	DEVPRINTF((sc->dev, "Thread terminating\n"));
540 	sc->flags &= ~CBB_KTHREAD_RUNNING;
541 	mtx_unlock(&sc->mtx);
542 	kproc_exit(0);
543 }
544 
545 /************************************************************************/
546 /* Insert/removal							*/
547 /************************************************************************/
548 
549 static void
550 cbb_insert(struct cbb_softc *sc)
551 {
552 	uint32_t sockevent, sockstate;
553 
554 	sockevent = cbb_get(sc, CBB_SOCKET_EVENT);
555 	sockstate = cbb_get(sc, CBB_SOCKET_STATE);
556 
557 	DEVPRINTF((sc->dev, "card inserted: event=0x%08x, state=%08x\n",
558 	    sockevent, sockstate));
559 
560 	if (sockstate & CBB_STATE_R2_CARD) {
561 		if (device_is_attached(sc->exca[0].pccarddev)) {
562 			sc->flags |= CBB_16BIT_CARD;
563 			exca_insert(&sc->exca[0]);
564 		} else {
565 			device_printf(sc->dev,
566 			    "16-bit card inserted, but no pccard bus.\n");
567 		}
568 	} else if (sockstate & CBB_STATE_CB_CARD) {
569 		if (device_is_attached(sc->cbdev)) {
570 			sc->flags &= ~CBB_16BIT_CARD;
571 			CARD_ATTACH_CARD(sc->cbdev);
572 		} else {
573 			device_printf(sc->dev,
574 			    "CardBus card inserted, but no cardbus bus.\n");
575 		}
576 	} else {
577 		/*
578 		 * We should power the card down, and try again a couple of
579 		 * times if this happens. XXX
580 		 */
581 		device_printf(sc->dev, "Unsupported card type detected\n");
582 	}
583 }
584 
585 static void
586 cbb_removal(struct cbb_softc *sc)
587 {
588 	sc->cardok = 0;
589 	if (sc->flags & CBB_16BIT_CARD) {
590 		exca_removal(&sc->exca[0]);
591 	} else {
592 		if (device_is_attached(sc->cbdev))
593 			CARD_DETACH_CARD(sc->cbdev);
594 	}
595 	cbb_destroy_res(sc);
596 }
597 
598 /************************************************************************/
599 /* Interrupt Handler							*/
600 /************************************************************************/
601 
602 static int
603 cbb_func_filt(void *arg)
604 {
605 	struct cbb_intrhand *ih = (struct cbb_intrhand *)arg;
606 	struct cbb_softc *sc = ih->sc;
607 
608 	/*
609 	 * Make sure that the card is really there.
610 	 */
611 	if (!sc->cardok)
612 		return (FILTER_STRAY);
613 	if (!CBB_CARD_PRESENT(cbb_get(sc, CBB_SOCKET_STATE))) {
614 		sc->cardok = 0;
615 		return (FILTER_HANDLED);
616 	}
617 
618 	/*
619 	 * nb: don't have to check for giant or not, since that's done in the
620 	 * ISR dispatch and one can't hold Giant in a filter anyway...
621 	 */
622 	return ((*ih->filt)(ih->arg));
623 }
624 
625 static void
626 cbb_func_intr(void *arg)
627 {
628 	struct cbb_intrhand *ih = (struct cbb_intrhand *)arg;
629 	struct cbb_softc *sc = ih->sc;
630 
631 	/*
632 	 * While this check may seem redundant, it helps close a race
633 	 * condition.  If the card is ejected after the filter runs, but
634 	 * before this ISR can be scheduled, then we need to do the same
635 	 * filtering to prevent the card's ISR from being called.  One could
636 	 * argue that the card's ISR should be able to cope, but experience
637 	 * has shown they can't always.  This mitigates the problem by making
638 	 * the race quite a bit smaller.  Properly written client ISRs should
639 	 * cope with the card going away in the middle of the ISR.  We assume
640 	 * that drivers that are sophisticated enough to use filters don't
641 	 * need our protection.  This also allows us to ensure they *ARE*
642 	 * called if their filter said they needed to be called.
643 	 */
644 	if (ih->filt == NULL) {
645 		if (!sc->cardok)
646 			return;
647 		if (!CBB_CARD_PRESENT(cbb_get(sc, CBB_SOCKET_STATE))) {
648 			sc->cardok = 0;
649 			return;
650 		}
651 	}
652 
653 	/*
654 	 * Call the registered ithread interrupt handler.  This entire routine
655 	 * will be called with Giant if this isn't an MP safe driver, or not
656 	 * if it is.  Either way, we don't have to worry.
657 	 */
658 	ih->intr(ih->arg);
659 }
660 
661 /************************************************************************/
662 /* Generic Power functions						*/
663 /************************************************************************/
664 
665 static uint32_t
666 cbb_detect_voltage(device_t brdev)
667 {
668 	struct cbb_softc *sc = device_get_softc(brdev);
669 	uint32_t psr;
670 	uint32_t vol = CARD_UKN_CARD;
671 
672 	psr = cbb_get(sc, CBB_SOCKET_STATE);
673 
674 	if (psr & CBB_STATE_5VCARD && psr & CBB_STATE_5VSOCK)
675 		vol |= CARD_5V_CARD;
676 	if (psr & CBB_STATE_3VCARD && psr & CBB_STATE_3VSOCK)
677 		vol |= CARD_3V_CARD;
678 	if (psr & CBB_STATE_XVCARD && psr & CBB_STATE_XVSOCK)
679 		vol |= CARD_XV_CARD;
680 	if (psr & CBB_STATE_YVCARD && psr & CBB_STATE_YVSOCK)
681 		vol |= CARD_YV_CARD;
682 
683 	return (vol);
684 }
685 
686 static uint8_t
687 cbb_o2micro_power_hack(struct cbb_softc *sc)
688 {
689 	uint8_t reg;
690 
691 	/*
692 	 * Issue #2: INT# not qualified with IRQ Routing Bit.  An
693 	 * unexpected PCI INT# may be generated during PC Card
694 	 * initialization even with the IRQ Routing Bit Set with some
695 	 * PC Cards.
696 	 *
697 	 * This is a two part issue.  The first part is that some of
698 	 * our older controllers have an issue in which the slot's PCI
699 	 * INT# is NOT qualified by the IRQ routing bit (PCI reg. 3Eh
700 	 * bit 7).  Regardless of the IRQ routing bit, if NO ISA IRQ
701 	 * is selected (ExCA register 03h bits 3:0, of the slot, are
702 	 * cleared) we will generate INT# if IREQ# is asserted.  The
703 	 * second part is because some PC Cards prematurally assert
704 	 * IREQ# before the ExCA registers are fully programmed.  This
705 	 * in turn asserts INT# because ExCA register 03h bits 3:0
706 	 * (ISA IRQ Select) are not yet programmed.
707 	 *
708 	 * The fix for this issue, which will work for any controller
709 	 * (old or new), is to set ExCA register 03h bits 3:0 = 0001b
710 	 * (select IRQ1), of the slot, before turning on slot power.
711 	 * Selecting IRQ1 will result in INT# NOT being asserted
712 	 * (because IRQ1 is selected), and IRQ1 won't be asserted
713 	 * because our controllers don't generate IRQ1.
714 	 *
715 	 * Other, non O2Micro controllers will generate irq 1 in some
716 	 * situations, so we can't do this hack for everybody.  Reports of
717 	 * keyboard controller's interrupts being suppressed occurred when
718 	 * we did this.
719 	 */
720 	reg = exca_getb(&sc->exca[0], EXCA_INTR);
721 	exca_putb(&sc->exca[0], EXCA_INTR, (reg & 0xf0) | 1);
722 	return (reg);
723 }
724 
725 /*
726  * Restore the damage that cbb_o2micro_power_hack does to EXCA_INTR so
727  * we don't have an interrupt storm on power on.  This has the effect of
728  * disabling card status change interrupts for the duration of poweron.
729  */
730 static void
731 cbb_o2micro_power_hack2(struct cbb_softc *sc, uint8_t reg)
732 {
733 	exca_putb(&sc->exca[0], EXCA_INTR, reg);
734 }
735 
736 int
737 cbb_power(device_t brdev, int volts)
738 {
739 	uint32_t status, sock_ctrl, reg_ctrl, mask;
740 	struct cbb_softc *sc = device_get_softc(brdev);
741 	int cnt, sane;
742 	int retval = 0;
743 	int on = 0;
744 	uint8_t reg = 0;
745 
746 	sock_ctrl = cbb_get(sc, CBB_SOCKET_CONTROL);
747 
748 	sock_ctrl &= ~CBB_SOCKET_CTRL_VCCMASK;
749 	switch (volts & CARD_VCCMASK) {
750 	case 5:
751 		sock_ctrl |= CBB_SOCKET_CTRL_VCC_5V;
752 		on++;
753 		break;
754 	case 3:
755 		sock_ctrl |= CBB_SOCKET_CTRL_VCC_3V;
756 		on++;
757 		break;
758 	case XV:
759 		sock_ctrl |= CBB_SOCKET_CTRL_VCC_XV;
760 		on++;
761 		break;
762 	case YV:
763 		sock_ctrl |= CBB_SOCKET_CTRL_VCC_YV;
764 		on++;
765 		break;
766 	case 0:
767 		break;
768 	default:
769 		return (0);			/* power NEVER changed */
770 	}
771 
772 	/* VPP == VCC */
773 	sock_ctrl &= ~CBB_SOCKET_CTRL_VPPMASK;
774 	sock_ctrl |= ((sock_ctrl >> 4) & 0x07);
775 
776 	if (cbb_get(sc, CBB_SOCKET_CONTROL) == sock_ctrl)
777 		return (1); /* no change necessary */
778 	DEVPRINTF((sc->dev, "cbb_power: %dV\n", volts));
779 	if (volts != 0 && sc->chipset == CB_O2MICRO)
780 		reg = cbb_o2micro_power_hack(sc);
781 
782 	/*
783 	 * We have to mask the card change detect interrupt while we're
784 	 * messing with the power.  It is allowed to bounce while we're
785 	 * messing with power as things settle down.  In addition, we mask off
786 	 * the card's function interrupt by routing it via the ISA bus.  This
787 	 * bit generally only affects 16-bit cards.  Some bridges allow one to
788 	 * set another bit to have it also affect 32-bit cards.  Since 32-bit
789 	 * cards are required to be better behaved, we don't bother to get
790 	 * into those bridge specific features.
791 	 *
792 	 * XXX I wonder if we need to enable the READY bit interrupt in the
793 	 * EXCA CSC register for 16-bit cards, and disable the CD bit?
794 	 */
795 	mask = cbb_get(sc, CBB_SOCKET_MASK);
796 	mask |= CBB_SOCKET_MASK_POWER;
797 	mask &= ~CBB_SOCKET_MASK_CD;
798 	cbb_set(sc, CBB_SOCKET_MASK, mask);
799 	PCI_MASK_CONFIG(brdev, CBBR_BRIDGECTRL,
800 	    |CBBM_BRIDGECTRL_INTR_IREQ_ISA_EN, 2);
801 	cbb_set(sc, CBB_SOCKET_CONTROL, sock_ctrl);
802 	if (on) {
803 		mtx_lock(&sc->mtx);
804 		cnt = sc->powerintr;
805 		/*
806 		 * We have a shortish timeout of 500ms here.  Some bridges do
807 		 * not generate a POWER_CYCLE event for 16-bit cards.  In
808 		 * those cases, we have to cope the best we can, and having
809 		 * only a short delay is better than the alternatives.  Others
810 		 * raise the power cycle a smidge before it is really ready.
811 		 * We deal with those below.
812 		 */
813 		sane = 10;
814 		while (!(cbb_get(sc, CBB_SOCKET_STATE) & CBB_STATE_POWER_CYCLE) &&
815 		    cnt == sc->powerintr && sane-- > 0)
816 			msleep(&sc->powerintr, &sc->mtx, 0, "-", hz / 20);
817 		mtx_unlock(&sc->mtx);
818 
819 		/*
820 		 * Relax for 100ms.  Some bridges appear to assert this signal
821 		 * right away, but before the card has stabilized.  Other
822 		 * cards need need more time to cope up reliabily.
823 		 * Experiments with troublesome setups show this to be a
824 		 * "cheap" way to enhance reliabilty.  We need not do this for
825 		 * "off" since we don't touch the card after we turn it off.
826 		 */
827 		pause("cbbPwr", min(hz / 10, 1));
828 
829 		/*
830 		 * The TOPIC95B requires a little bit extra time to get its
831 		 * act together, so delay for an additional 100ms.  Also as
832 		 * documented below, it doesn't seem to set the POWER_CYCLE
833 		 * bit, so don't whine if it never came on.
834 		 */
835 		if (sc->chipset == CB_TOPIC95)
836 			pause("cbb95B", hz / 10);
837 		else if (sane <= 0)
838 			device_printf(sc->dev, "power timeout, doom?\n");
839 	}
840 
841 	/*
842 	 * After the power is good, we can turn off the power interrupt.
843 	 * However, the PC Card standard says that we must delay turning the
844 	 * CD bit back on for a bit to allow for bouncyness on power down
845 	 * (recall that we don't wait above for a power down, since we don't
846 	 * get an interrupt for that).  We're called either from the suspend
847 	 * code in which case we don't want to turn card change on again, or
848 	 * we're called from the card insertion code, in which case the cbb
849 	 * thread will turn it on for us before it waits to be woken by a
850 	 * change event.
851 	 *
852 	 * NB: Topic95B doesn't set the power cycle bit.  we assume that
853 	 * both it and the TOPIC95 behave the same.
854 	 */
855 	cbb_clrb(sc, CBB_SOCKET_MASK, CBB_SOCKET_MASK_POWER);
856 	status = cbb_get(sc, CBB_SOCKET_STATE);
857 	if (on && sc->chipset != CB_TOPIC95) {
858 		if ((status & CBB_STATE_POWER_CYCLE) == 0)
859 			device_printf(sc->dev, "Power not on?\n");
860 	}
861 	if (status & CBB_STATE_BAD_VCC_REQ) {
862 		device_printf(sc->dev, "Bad Vcc requested\n");
863 		/*
864 		 * Turn off the power, and try again.  Retrigger other
865 		 * active interrupts via force register.  From NetBSD
866 		 * PR 36652, coded by me to description there.
867 		 */
868 		sock_ctrl &= ~CBB_SOCKET_CTRL_VCCMASK;
869 		sock_ctrl &= ~CBB_SOCKET_CTRL_VPPMASK;
870 		cbb_set(sc, CBB_SOCKET_CONTROL, sock_ctrl);
871 		status &= ~CBB_STATE_BAD_VCC_REQ;
872 		status &= ~CBB_STATE_DATA_LOST;
873 		status |= CBB_FORCE_CV_TEST;
874 		cbb_set(sc, CBB_SOCKET_FORCE, status);
875 		goto done;
876 	}
877 	if (sc->chipset == CB_TOPIC97) {
878 		reg_ctrl = pci_read_config(sc->dev, TOPIC_REG_CTRL, 4);
879 		reg_ctrl &= ~TOPIC97_REG_CTRL_TESTMODE;
880 		if (on)
881 			reg_ctrl |= TOPIC97_REG_CTRL_CLKRUN_ENA;
882 		else
883 			reg_ctrl &= ~TOPIC97_REG_CTRL_CLKRUN_ENA;
884 		pci_write_config(sc->dev, TOPIC_REG_CTRL, reg_ctrl, 4);
885 	}
886 	PCI_MASK_CONFIG(brdev, CBBR_BRIDGECTRL,
887 	    & ~CBBM_BRIDGECTRL_INTR_IREQ_ISA_EN, 2);
888 	retval = 1;
889 done:;
890 	if (volts != 0 && sc->chipset == CB_O2MICRO)
891 		cbb_o2micro_power_hack2(sc, reg);
892 	return (retval);
893 }
894 
895 static int
896 cbb_current_voltage(device_t brdev)
897 {
898 	struct cbb_softc *sc = device_get_softc(brdev);
899 	uint32_t ctrl;
900 
901 	ctrl = cbb_get(sc, CBB_SOCKET_CONTROL);
902 	switch (ctrl & CBB_SOCKET_CTRL_VCCMASK) {
903 	case CBB_SOCKET_CTRL_VCC_5V:
904 		return CARD_5V_CARD;
905 	case CBB_SOCKET_CTRL_VCC_3V:
906 		return CARD_3V_CARD;
907 	case CBB_SOCKET_CTRL_VCC_XV:
908 		return CARD_XV_CARD;
909 	case CBB_SOCKET_CTRL_VCC_YV:
910 		return CARD_YV_CARD;
911 	}
912 	return 0;
913 }
914 
915 /*
916  * detect the voltage for the card, and set it.  Since the power
917  * used is the square of the voltage, lower voltages is a big win
918  * and what Windows does (and what Microsoft prefers).  The MS paper
919  * also talks about preferring the CIS entry as well, but that has
920  * to be done elsewhere.  We also optimize power sequencing here
921  * and don't change things if we're already powered up at a supported
922  * voltage.
923  *
924  * In addition, we power up with OE disabled.  We'll set it later
925  * in the power up sequence.
926  */
927 static int
928 cbb_do_power(device_t brdev)
929 {
930 	struct cbb_softc *sc = device_get_softc(brdev);
931 	uint32_t voltage, curpwr;
932 	uint32_t status;
933 
934 	/* Don't enable OE (output enable) until power stable */
935 	exca_clrb(&sc->exca[0], EXCA_PWRCTL, EXCA_PWRCTL_OE);
936 
937 	voltage = cbb_detect_voltage(brdev);
938 	curpwr = cbb_current_voltage(brdev);
939 	status = cbb_get(sc, CBB_SOCKET_STATE);
940 	if ((status & CBB_STATE_POWER_CYCLE) && (voltage & curpwr))
941 		return 0;
942 	/* Prefer lowest voltage supported */
943 	cbb_power(brdev, CARD_OFF);
944 	if (voltage & CARD_YV_CARD)
945 		cbb_power(brdev, CARD_VCC(YV));
946 	else if (voltage & CARD_XV_CARD)
947 		cbb_power(brdev, CARD_VCC(XV));
948 	else if (voltage & CARD_3V_CARD)
949 		cbb_power(brdev, CARD_VCC(3));
950 	else if (voltage & CARD_5V_CARD)
951 		cbb_power(brdev, CARD_VCC(5));
952 	else {
953 		device_printf(brdev, "Unknown card voltage\n");
954 		return (ENXIO);
955 	}
956 	return (0);
957 }
958 
959 /************************************************************************/
960 /* CardBus power functions						*/
961 /************************************************************************/
962 
963 static int
964 cbb_cardbus_reset_power(device_t brdev, device_t child, int on)
965 {
966 	struct cbb_softc *sc = device_get_softc(brdev);
967 	uint32_t b, h;
968 	int delay, count, zero_seen, func;
969 
970 	/*
971 	 * Asserting reset for 20ms is necessary for most bridges.  For some
972 	 * reason, the Ricoh RF5C47x bridges need it asserted for 400ms.  The
973 	 * root cause of this is unknown, and NetBSD does the same thing.
974 	 */
975 	delay = sc->chipset == CB_RF5C47X ? 400 : 20;
976 	PCI_MASK_CONFIG(brdev, CBBR_BRIDGECTRL, |CBBM_BRIDGECTRL_RESET, 2);
977 	pause("cbbP3", hz * delay / 1000);
978 
979 	/*
980 	 * If a card exists and we're turning it on, take it out of reset.
981 	 * After clearing reset, wait up to 1.1s for the first configuration
982 	 * register (vendor/product) configuration register of device 0.0 to
983 	 * become != 0xffffffff.  The PCMCIA PC Card Host System Specification
984 	 * says that when powering up the card, the PCI Spec v2.1 must be
985 	 * followed.  In PCI spec v2.2 Table 4-6, Trhfa (Reset High to first
986 	 * Config Access) is at most 2^25 clocks, or just over 1s.  Section
987 	 * 2.2.1 states any card not ready to participate in bus transactions
988 	 * must tristate its outputs.  Therefore, any access to its
989 	 * configuration registers must be ignored.  In that state, the config
990 	 * reg will read 0xffffffff.  Section 6.2.1 states a vendor id of
991 	 * 0xffff is invalid, so this can never match a real card.  Print a
992 	 * warning if it never returns a real id.  The PCMCIA PC Card
993 	 * Electrical Spec Section 5.2.7.1 implies only device 0 is present on
994 	 * a cardbus bus, so that's the only register we check here.
995 	 */
996 	if (on && CBB_CARD_PRESENT(cbb_get(sc, CBB_SOCKET_STATE))) {
997 		PCI_MASK_CONFIG(brdev, CBBR_BRIDGECTRL,
998 		    &~CBBM_BRIDGECTRL_RESET, 2);
999 		b = pcib_get_bus(child);
1000 		count = 1100 / 20;
1001 		do {
1002 			pause("cbbP4", hz * 2 / 100);
1003 		} while (PCIB_READ_CONFIG(brdev, b, 0, 0, PCIR_DEVVENDOR, 4) ==
1004 		    0xfffffffful && --count >= 0);
1005 		if (count < 0)
1006 			device_printf(brdev, "Warning: Bus reset timeout\n");
1007 
1008 		/*
1009 		 * Some cards (so far just an atheros card I have) seem to
1010 		 * come out of reset in a funky state. They report they are
1011 		 * multi-function cards, but have nonsense for some of the
1012 		 * higher functions.  So if the card claims to be MFDEV, and
1013 		 * any of the higher functions' ID is 0, then we've hit the
1014 		 * bug and we'll try again.
1015 		 */
1016 		h = PCIB_READ_CONFIG(brdev, b, 0, 0, PCIR_HDRTYPE, 1);
1017 		if ((h & PCIM_MFDEV) == 0)
1018 			return 0;
1019 		zero_seen = 0;
1020 		for (func = 1; func < 8; func++) {
1021 			h = PCIB_READ_CONFIG(brdev, b, 0, func,
1022 			    PCIR_DEVVENDOR, 4);
1023 			if (h == 0)
1024 				zero_seen++;
1025 		}
1026 		if (!zero_seen)
1027 			return 0;
1028 		return (EINVAL);
1029 	}
1030 	return 0;
1031 }
1032 
1033 static int
1034 cbb_cardbus_power_disable_socket(device_t brdev, device_t child)
1035 {
1036 	cbb_power(brdev, CARD_OFF);
1037 	cbb_cardbus_reset_power(brdev, child, 0);
1038 	return (0);
1039 }
1040 
1041 static int
1042 cbb_cardbus_power_enable_socket(device_t brdev, device_t child)
1043 {
1044 	struct cbb_softc *sc = device_get_softc(brdev);
1045 	int err, count;
1046 
1047 	if (!CBB_CARD_PRESENT(cbb_get(sc, CBB_SOCKET_STATE)))
1048 		return (ENODEV);
1049 
1050 	count = 10;
1051 	do {
1052 		err = cbb_do_power(brdev);
1053 		if (err)
1054 			return (err);
1055 		err = cbb_cardbus_reset_power(brdev, child, 1);
1056 		if (err) {
1057 			device_printf(brdev, "Reset failed, trying again.\n");
1058 			cbb_cardbus_power_disable_socket(brdev, child);
1059 			pause("cbbErr1", hz / 10); /* wait 100ms */
1060 		}
1061 	} while (err != 0 && count-- > 0);
1062 	return (0);
1063 }
1064 
1065 /************************************************************************/
1066 /* CardBus Resource							*/
1067 /************************************************************************/
1068 
1069 static void
1070 cbb_activate_window(device_t brdev, int type)
1071 {
1072 
1073 	PCI_ENABLE_IO(device_get_parent(brdev), brdev, type);
1074 }
1075 
1076 static int
1077 cbb_cardbus_io_open(device_t brdev, int win, uint32_t start, uint32_t end)
1078 {
1079 	int basereg;
1080 	int limitreg;
1081 
1082 	if ((win < 0) || (win > 1)) {
1083 		DEVPRINTF((brdev,
1084 		    "cbb_cardbus_io_open: window out of range %d\n", win));
1085 		return (EINVAL);
1086 	}
1087 
1088 	basereg = win * 8 + CBBR_IOBASE0;
1089 	limitreg = win * 8 + CBBR_IOLIMIT0;
1090 
1091 	pci_write_config(brdev, basereg, start, 4);
1092 	pci_write_config(brdev, limitreg, end, 4);
1093 	cbb_activate_window(brdev, SYS_RES_IOPORT);
1094 	return (0);
1095 }
1096 
1097 static int
1098 cbb_cardbus_mem_open(device_t brdev, int win, uint32_t start, uint32_t end)
1099 {
1100 	int basereg;
1101 	int limitreg;
1102 
1103 	if ((win < 0) || (win > 1)) {
1104 		DEVPRINTF((brdev,
1105 		    "cbb_cardbus_mem_open: window out of range %d\n", win));
1106 		return (EINVAL);
1107 	}
1108 
1109 	basereg = win * 8 + CBBR_MEMBASE0;
1110 	limitreg = win * 8 + CBBR_MEMLIMIT0;
1111 
1112 	pci_write_config(brdev, basereg, start, 4);
1113 	pci_write_config(brdev, limitreg, end, 4);
1114 	cbb_activate_window(brdev, SYS_RES_MEMORY);
1115 	return (0);
1116 }
1117 
1118 #define START_NONE 0xffffffff
1119 #define END_NONE 0
1120 
1121 static void
1122 cbb_cardbus_auto_open(struct cbb_softc *sc, int type)
1123 {
1124 	uint32_t starts[2];
1125 	uint32_t ends[2];
1126 	struct cbb_reslist *rle;
1127 	int align, i;
1128 	uint32_t reg;
1129 
1130 	starts[0] = starts[1] = START_NONE;
1131 	ends[0] = ends[1] = END_NONE;
1132 
1133 	if (type == SYS_RES_MEMORY)
1134 		align = CBB_MEMALIGN;
1135 	else if (type == SYS_RES_IOPORT)
1136 		align = CBB_IOALIGN;
1137 	else
1138 		align = 1;
1139 
1140 	SLIST_FOREACH(rle, &sc->rl, link) {
1141 		if (rle->type != type)
1142 			continue;
1143 		if (rle->res == NULL)
1144 			continue;
1145 		if (!(rman_get_flags(rle->res) & RF_ACTIVE))
1146 			continue;
1147 		if (rman_get_flags(rle->res) & RF_PREFETCHABLE)
1148 			i = 1;
1149 		else
1150 			i = 0;
1151 		if (rman_get_start(rle->res) < starts[i])
1152 			starts[i] = rman_get_start(rle->res);
1153 		if (rman_get_end(rle->res) > ends[i])
1154 			ends[i] = rman_get_end(rle->res);
1155 	}
1156 	for (i = 0; i < 2; i++) {
1157 		if (starts[i] == START_NONE)
1158 			continue;
1159 		starts[i] &= ~(align - 1);
1160 		ends[i] = roundup2(ends[i], align) - 1;
1161 	}
1162 	if (starts[0] != START_NONE && starts[1] != START_NONE) {
1163 		if (starts[0] < starts[1]) {
1164 			if (ends[0] > starts[1]) {
1165 				device_printf(sc->dev, "Overlapping ranges"
1166 				    " for prefetch and non-prefetch memory\n");
1167 				return;
1168 			}
1169 		} else {
1170 			if (ends[1] > starts[0]) {
1171 				device_printf(sc->dev, "Overlapping ranges"
1172 				    " for prefetch and non-prefetch memory\n");
1173 				return;
1174 			}
1175 		}
1176 	}
1177 
1178 	if (type == SYS_RES_MEMORY) {
1179 		cbb_cardbus_mem_open(sc->dev, 0, starts[0], ends[0]);
1180 		cbb_cardbus_mem_open(sc->dev, 1, starts[1], ends[1]);
1181 		reg = pci_read_config(sc->dev, CBBR_BRIDGECTRL, 2);
1182 		reg &= ~(CBBM_BRIDGECTRL_PREFETCH_0 |
1183 		    CBBM_BRIDGECTRL_PREFETCH_1);
1184 		if (starts[1] != START_NONE)
1185 			reg |= CBBM_BRIDGECTRL_PREFETCH_1;
1186 		pci_write_config(sc->dev, CBBR_BRIDGECTRL, reg, 2);
1187 		if (bootverbose) {
1188 			device_printf(sc->dev, "Opening memory:\n");
1189 			if (starts[0] != START_NONE)
1190 				device_printf(sc->dev, "Normal: %#x-%#x\n",
1191 				    starts[0], ends[0]);
1192 			if (starts[1] != START_NONE)
1193 				device_printf(sc->dev, "Prefetch: %#x-%#x\n",
1194 				    starts[1], ends[1]);
1195 		}
1196 	} else if (type == SYS_RES_IOPORT) {
1197 		cbb_cardbus_io_open(sc->dev, 0, starts[0], ends[0]);
1198 		cbb_cardbus_io_open(sc->dev, 1, starts[1], ends[1]);
1199 		if (bootverbose && starts[0] != START_NONE)
1200 			device_printf(sc->dev, "Opening I/O: %#x-%#x\n",
1201 			    starts[0], ends[0]);
1202 	}
1203 }
1204 
1205 static int
1206 cbb_cardbus_activate_resource(device_t brdev, device_t child, int type,
1207     int rid, struct resource *res)
1208 {
1209 	int ret;
1210 
1211 	ret = BUS_ACTIVATE_RESOURCE(device_get_parent(brdev), child,
1212 	    type, rid, res);
1213 	if (ret != 0)
1214 		return (ret);
1215 	cbb_cardbus_auto_open(device_get_softc(brdev), type);
1216 	return (0);
1217 }
1218 
1219 static int
1220 cbb_cardbus_deactivate_resource(device_t brdev, device_t child, int type,
1221     int rid, struct resource *res)
1222 {
1223 	int ret;
1224 
1225 	ret = BUS_DEACTIVATE_RESOURCE(device_get_parent(brdev), child,
1226 	    type, rid, res);
1227 	if (ret != 0)
1228 		return (ret);
1229 	cbb_cardbus_auto_open(device_get_softc(brdev), type);
1230 	return (0);
1231 }
1232 
1233 static struct resource *
1234 cbb_cardbus_alloc_resource(device_t brdev, device_t child, int type,
1235     int *rid, rman_res_t start, rman_res_t end, rman_res_t count, u_int flags)
1236 {
1237 	struct cbb_softc *sc = device_get_softc(brdev);
1238 	int tmp;
1239 	struct resource *res;
1240 	rman_res_t align;
1241 
1242 	switch (type) {
1243 	case SYS_RES_IRQ:
1244 		tmp = rman_get_start(sc->irq_res);
1245 		if (start > tmp || end < tmp || count != 1) {
1246 			device_printf(child, "requested interrupt %jd-%jd,"
1247 			    "count = %jd not supported by cbb\n",
1248 			    start, end, count);
1249 			return (NULL);
1250 		}
1251 		start = end = tmp;
1252 		flags |= RF_SHAREABLE;
1253 		break;
1254 	case SYS_RES_IOPORT:
1255 		if (start <= cbb_start_32_io)
1256 			start = cbb_start_32_io;
1257 		if (end < start)
1258 			end = start;
1259 		if (count > (1 << RF_ALIGNMENT(flags)))
1260 			flags = (flags & ~RF_ALIGNMENT_MASK) |
1261 			    rman_make_alignment_flags(count);
1262 		break;
1263 	case SYS_RES_MEMORY:
1264 		if (start <= cbb_start_mem)
1265 			start = cbb_start_mem;
1266 		if (end < start)
1267 			end = start;
1268 		if (count < CBB_MEMALIGN)
1269 			align = CBB_MEMALIGN;
1270 		else
1271 			align = count;
1272 		if (align > (1 << RF_ALIGNMENT(flags)))
1273 			flags = (flags & ~RF_ALIGNMENT_MASK) |
1274 			    rman_make_alignment_flags(align);
1275 		break;
1276 	}
1277 	res = BUS_ALLOC_RESOURCE(device_get_parent(brdev), child, type, rid,
1278 	    start, end, count, flags & ~RF_ACTIVE);
1279 	if (res == NULL) {
1280 		printf("cbb alloc res fail type %d rid %x\n", type, *rid);
1281 		return (NULL);
1282 	}
1283 	cbb_insert_res(sc, res, type, *rid);
1284 	if (flags & RF_ACTIVE)
1285 		if (bus_activate_resource(child, type, *rid, res) != 0) {
1286 			bus_release_resource(child, type, *rid, res);
1287 			return (NULL);
1288 		}
1289 
1290 	return (res);
1291 }
1292 
1293 static int
1294 cbb_cardbus_release_resource(device_t brdev, device_t child, int type,
1295     int rid, struct resource *res)
1296 {
1297 	struct cbb_softc *sc = device_get_softc(brdev);
1298 	int error;
1299 
1300 	if (rman_get_flags(res) & RF_ACTIVE) {
1301 		error = bus_deactivate_resource(child, type, rid, res);
1302 		if (error != 0)
1303 			return (error);
1304 	}
1305 	cbb_remove_res(sc, res);
1306 	return (BUS_RELEASE_RESOURCE(device_get_parent(brdev), child,
1307 	    type, rid, res));
1308 }
1309 
1310 /************************************************************************/
1311 /* PC Card Power Functions						*/
1312 /************************************************************************/
1313 
1314 static int
1315 cbb_pcic_power_enable_socket(device_t brdev, device_t child)
1316 {
1317 	struct cbb_softc *sc = device_get_softc(brdev);
1318 	int err;
1319 
1320 	DPRINTF(("cbb_pcic_socket_enable:\n"));
1321 
1322 	/* power down/up the socket to reset */
1323 	err = cbb_do_power(brdev);
1324 	if (err)
1325 		return (err);
1326 	exca_reset(&sc->exca[0], child);
1327 
1328 	return (0);
1329 }
1330 
1331 static int
1332 cbb_pcic_power_disable_socket(device_t brdev, device_t child)
1333 {
1334 	struct cbb_softc *sc = device_get_softc(brdev);
1335 
1336 	DPRINTF(("cbb_pcic_socket_disable\n"));
1337 
1338 	/* Turn off the card's interrupt and leave it in reset, wait 10ms */
1339 	exca_putb(&sc->exca[0], EXCA_INTR, 0);
1340 	pause("cbbP1", hz / 100);
1341 
1342 	/* power down the socket */
1343 	cbb_power(brdev, CARD_OFF);
1344 	exca_putb(&sc->exca[0], EXCA_PWRCTL, 0);
1345 
1346 	/* wait 300ms until power fails (Tpf). */
1347 	pause("cbbP2", hz * 300 / 1000);
1348 
1349 	/* enable CSC interrupts */
1350 	exca_putb(&sc->exca[0], EXCA_INTR, EXCA_INTR_ENABLE);
1351 	return (0);
1352 }
1353 
1354 /************************************************************************/
1355 /* POWER methods							*/
1356 /************************************************************************/
1357 
1358 int
1359 cbb_power_enable_socket(device_t brdev, device_t child)
1360 {
1361 	struct cbb_softc *sc = device_get_softc(brdev);
1362 
1363 	if (sc->flags & CBB_16BIT_CARD)
1364 		return (cbb_pcic_power_enable_socket(brdev, child));
1365 	return (cbb_cardbus_power_enable_socket(brdev, child));
1366 }
1367 
1368 int
1369 cbb_power_disable_socket(device_t brdev, device_t child)
1370 {
1371 	struct cbb_softc *sc = device_get_softc(brdev);
1372 	if (sc->flags & CBB_16BIT_CARD)
1373 		return (cbb_pcic_power_disable_socket(brdev, child));
1374 	return (cbb_cardbus_power_disable_socket(brdev, child));
1375 }
1376 
1377 static int
1378 cbb_pcic_activate_resource(device_t brdev, device_t child, int type, int rid,
1379     struct resource *res)
1380 {
1381 	struct cbb_softc *sc = device_get_softc(brdev);
1382 	int error;
1383 
1384 	error = exca_activate_resource(&sc->exca[0], child, type, rid, res);
1385 	if (error == 0)
1386 		cbb_activate_window(brdev, type);
1387 	return (error);
1388 }
1389 
1390 static int
1391 cbb_pcic_deactivate_resource(device_t brdev, device_t child, int type,
1392     int rid, struct resource *res)
1393 {
1394 	struct cbb_softc *sc = device_get_softc(brdev);
1395 	return (exca_deactivate_resource(&sc->exca[0], child, type, rid, res));
1396 }
1397 
1398 static struct resource *
1399 cbb_pcic_alloc_resource(device_t brdev, device_t child, int type, int *rid,
1400     rman_res_t start, rman_res_t end, rman_res_t count, u_int flags)
1401 {
1402 	struct resource *res = NULL;
1403 	struct cbb_softc *sc = device_get_softc(brdev);
1404 	int align;
1405 	int tmp;
1406 
1407 	switch (type) {
1408 	case SYS_RES_MEMORY:
1409 		if (start < cbb_start_mem)
1410 			start = cbb_start_mem;
1411 		if (end < start)
1412 			end = start;
1413 		if (count < CBB_MEMALIGN)
1414 			align = CBB_MEMALIGN;
1415 		else
1416 			align = count;
1417 		if (align > (1 << RF_ALIGNMENT(flags)))
1418 			flags = (flags & ~RF_ALIGNMENT_MASK) |
1419 			    rman_make_alignment_flags(align);
1420 		break;
1421 	case SYS_RES_IOPORT:
1422 		if (start < cbb_start_16_io)
1423 			start = cbb_start_16_io;
1424 		if (end < start)
1425 			end = start;
1426 		break;
1427 	case SYS_RES_IRQ:
1428 		tmp = rman_get_start(sc->irq_res);
1429 		if (start > tmp || end < tmp || count != 1) {
1430 			device_printf(child, "requested interrupt %jd-%jd,"
1431 			    "count = %jd not supported by cbb\n",
1432 			    start, end, count);
1433 			return (NULL);
1434 		}
1435 		flags |= RF_SHAREABLE;
1436 		start = end = rman_get_start(sc->irq_res);
1437 		break;
1438 	}
1439 	res = BUS_ALLOC_RESOURCE(device_get_parent(brdev), child, type, rid,
1440 	    start, end, count, flags & ~RF_ACTIVE);
1441 	if (res == NULL)
1442 		return (NULL);
1443 	cbb_insert_res(sc, res, type, *rid);
1444 	if (flags & RF_ACTIVE) {
1445 		if (bus_activate_resource(child, type, *rid, res) != 0) {
1446 			bus_release_resource(child, type, *rid, res);
1447 			return (NULL);
1448 		}
1449 	}
1450 
1451 	return (res);
1452 }
1453 
1454 static int
1455 cbb_pcic_release_resource(device_t brdev, device_t child, int type,
1456     int rid, struct resource *res)
1457 {
1458 	struct cbb_softc *sc = device_get_softc(brdev);
1459 	int error;
1460 
1461 	if (rman_get_flags(res) & RF_ACTIVE) {
1462 		error = bus_deactivate_resource(child, type, rid, res);
1463 		if (error != 0)
1464 			return (error);
1465 	}
1466 	cbb_remove_res(sc, res);
1467 	return (BUS_RELEASE_RESOURCE(device_get_parent(brdev), child,
1468 	    type, rid, res));
1469 }
1470 
1471 /************************************************************************/
1472 /* PC Card methods							*/
1473 /************************************************************************/
1474 
1475 int
1476 cbb_pcic_set_res_flags(device_t brdev, device_t child, int type, int rid,
1477     u_long flags)
1478 {
1479 	struct cbb_softc *sc = device_get_softc(brdev);
1480 	struct resource *res;
1481 
1482 	if (type != SYS_RES_MEMORY)
1483 		return (EINVAL);
1484 	res = cbb_find_res(sc, type, rid);
1485 	if (res == NULL) {
1486 		device_printf(brdev,
1487 		    "set_res_flags: specified rid not found\n");
1488 		return (ENOENT);
1489 	}
1490 	return (exca_mem_set_flags(&sc->exca[0], res, flags));
1491 }
1492 
1493 int
1494 cbb_pcic_set_memory_offset(device_t brdev, device_t child, int rid,
1495     uint32_t cardaddr, uint32_t *deltap)
1496 {
1497 	struct cbb_softc *sc = device_get_softc(brdev);
1498 	struct resource *res;
1499 
1500 	res = cbb_find_res(sc, SYS_RES_MEMORY, rid);
1501 	if (res == NULL) {
1502 		device_printf(brdev,
1503 		    "set_memory_offset: specified rid not found\n");
1504 		return (ENOENT);
1505 	}
1506 	return (exca_mem_set_offset(&sc->exca[0], res, cardaddr, deltap));
1507 }
1508 
1509 /************************************************************************/
1510 /* BUS Methods								*/
1511 /************************************************************************/
1512 
1513 
1514 int
1515 cbb_activate_resource(device_t brdev, device_t child, int type, int rid,
1516     struct resource *r)
1517 {
1518 	struct cbb_softc *sc = device_get_softc(brdev);
1519 
1520 	if (sc->flags & CBB_16BIT_CARD)
1521 		return (cbb_pcic_activate_resource(brdev, child, type, rid, r));
1522 	else
1523 		return (cbb_cardbus_activate_resource(brdev, child, type, rid,
1524 		    r));
1525 }
1526 
1527 int
1528 cbb_deactivate_resource(device_t brdev, device_t child, int type,
1529     int rid, struct resource *r)
1530 {
1531 	struct cbb_softc *sc = device_get_softc(brdev);
1532 
1533 	if (sc->flags & CBB_16BIT_CARD)
1534 		return (cbb_pcic_deactivate_resource(brdev, child, type,
1535 		    rid, r));
1536 	else
1537 		return (cbb_cardbus_deactivate_resource(brdev, child, type,
1538 		    rid, r));
1539 }
1540 
1541 struct resource *
1542 cbb_alloc_resource(device_t brdev, device_t child, int type, int *rid,
1543     rman_res_t start, rman_res_t end, rman_res_t count, u_int flags)
1544 {
1545 	struct cbb_softc *sc = device_get_softc(brdev);
1546 
1547 	if (sc->flags & CBB_16BIT_CARD)
1548 		return (cbb_pcic_alloc_resource(brdev, child, type, rid,
1549 		    start, end, count, flags));
1550 	else
1551 		return (cbb_cardbus_alloc_resource(brdev, child, type, rid,
1552 		    start, end, count, flags));
1553 }
1554 
1555 int
1556 cbb_release_resource(device_t brdev, device_t child, int type, int rid,
1557     struct resource *r)
1558 {
1559 	struct cbb_softc *sc = device_get_softc(brdev);
1560 
1561 	if (sc->flags & CBB_16BIT_CARD)
1562 		return (cbb_pcic_release_resource(brdev, child, type,
1563 		    rid, r));
1564 	else
1565 		return (cbb_cardbus_release_resource(brdev, child, type,
1566 		    rid, r));
1567 }
1568 
1569 int
1570 cbb_read_ivar(device_t brdev, device_t child, int which, uintptr_t *result)
1571 {
1572 	struct cbb_softc *sc = device_get_softc(brdev);
1573 
1574 	switch (which) {
1575 	case PCIB_IVAR_DOMAIN:
1576 		*result = sc->domain;
1577 		return (0);
1578 	case PCIB_IVAR_BUS:
1579 		*result = sc->bus.sec;
1580 		return (0);
1581 	}
1582 	return (ENOENT);
1583 }
1584 
1585 int
1586 cbb_write_ivar(device_t brdev, device_t child, int which, uintptr_t value)
1587 {
1588 
1589 	switch (which) {
1590 	case PCIB_IVAR_DOMAIN:
1591 		return (EINVAL);
1592 	case PCIB_IVAR_BUS:
1593 		return (EINVAL);
1594 	}
1595 	return (ENOENT);
1596 }
1597 
1598 int
1599 cbb_child_present(device_t parent, device_t child)
1600 {
1601 	struct cbb_softc *sc = (struct cbb_softc *)device_get_softc(parent);
1602 	uint32_t sockstate;
1603 
1604 	sockstate = cbb_get(sc, CBB_SOCKET_STATE);
1605 	return (CBB_CARD_PRESENT(sockstate) && sc->cardok);
1606 }
1607