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