Home | History | Annotate | Line # | Download | only in ic
rtw.c revision 1.134
      1 /* $NetBSD: rtw.c,v 1.134 2019/11/10 21:16:35 chs Exp $ */
      2 /*-
      3  * Copyright (c) 2004, 2005, 2006, 2007 David Young.  All rights
      4  * reserved.
      5  *
      6  * Programmed for NetBSD by David Young.
      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 David Young ``AS IS'' AND ANY
     18  * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
     19  * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
     20  * PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL David
     21  * Young BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
     22  * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
     23  * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
     24  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
     25  * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
     26  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
     27  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
     28  * OF SUCH DAMAGE.
     29  */
     30 /*
     31  * Device driver for the Realtek RTL8180 802.11 MAC/BBP.
     32  */
     33 
     34 #include <sys/cdefs.h>
     35 __KERNEL_RCSID(0, "$NetBSD: rtw.c,v 1.134 2019/11/10 21:16:35 chs Exp $");
     36 
     37 
     38 #include <sys/param.h>
     39 #include <sys/sysctl.h>
     40 #include <sys/systm.h>
     41 #include <sys/callout.h>
     42 #include <sys/mbuf.h>
     43 #include <sys/malloc.h>
     44 #include <sys/kernel.h>
     45 #include <sys/time.h>
     46 #include <sys/types.h>
     47 #include <sys/device.h>
     48 #include <sys/sockio.h>
     49 
     50 #include <machine/endian.h>
     51 #include <sys/bus.h>
     52 #include <sys/intr.h>	/* splnet */
     53 
     54 #include <net/if.h>
     55 #include <net/if_media.h>
     56 #include <net/if_ether.h>
     57 
     58 #include <net80211/ieee80211_netbsd.h>
     59 #include <net80211/ieee80211_var.h>
     60 #include <net80211/ieee80211_radiotap.h>
     61 
     62 #include <net/bpf.h>
     63 
     64 #include <dev/ic/rtwreg.h>
     65 #include <dev/ic/rtwvar.h>
     66 #include <dev/ic/rtwphyio.h>
     67 #include <dev/ic/rtwphy.h>
     68 
     69 #include <dev/ic/smc93cx6var.h>
     70 
     71 static int rtw_rfprog_fallback = 0;
     72 static int rtw_host_rfio = 0;
     73 
     74 #ifdef RTW_DEBUG
     75 int rtw_debug = 0;
     76 static int rtw_rxbufs_limit = RTW_RXQLEN;
     77 #endif /* RTW_DEBUG */
     78 
     79 #define NEXT_ATTACH_STATE(sc, state) do {			\
     80 	DPRINTF(sc, RTW_DEBUG_ATTACH,				\
     81 	    ("%s: attach state %s\n", __func__, #state));	\
     82 	sc->sc_attach_state = state;				\
     83 } while (0)
     84 
     85 int rtw_dwelltime = 200;	/* milliseconds */
     86 static struct ieee80211_cipher rtw_cipher_wep;
     87 
     88 static void rtw_disable_interrupts(struct rtw_regs *);
     89 static void rtw_enable_interrupts(struct rtw_softc *);
     90 
     91 static int rtw_init(struct ifnet *);
     92 static void rtw_softintr(void *);
     93 
     94 static void rtw_start(struct ifnet *);
     95 static void rtw_reset_oactive(struct rtw_softc *);
     96 static struct mbuf *rtw_beacon_alloc(struct rtw_softc *,
     97     struct ieee80211_node *);
     98 static u_int rtw_txring_next(struct rtw_regs *, struct rtw_txdesc_blk *);
     99 
    100 static void rtw_io_enable(struct rtw_softc *, uint8_t, int);
    101 static int rtw_key_delete(struct ieee80211com *, const struct ieee80211_key *);
    102 static int rtw_key_set(struct ieee80211com *, const struct ieee80211_key *,
    103     const uint8_t[IEEE80211_ADDR_LEN]);
    104 static void rtw_key_update_end(struct ieee80211com *);
    105 static void rtw_key_update_begin(struct ieee80211com *);
    106 static int rtw_wep_decap(struct ieee80211_key *, struct mbuf *, int);
    107 static void rtw_wep_setkeys(struct rtw_softc *, struct ieee80211_key *, int);
    108 
    109 static void rtw_led_attach(struct rtw_led_state *, void *);
    110 static void rtw_led_detach(struct rtw_led_state *);
    111 static void rtw_led_init(struct rtw_regs *);
    112 static void rtw_led_slowblink(void *);
    113 static void rtw_led_fastblink(void *);
    114 static void rtw_led_set(struct rtw_led_state *, struct rtw_regs *, int);
    115 
    116 static int rtw_sysctl_verify_rfio(SYSCTLFN_PROTO);
    117 static int rtw_sysctl_verify_rfprog(SYSCTLFN_PROTO);
    118 #ifdef RTW_DEBUG
    119 static void rtw_dump_rings(struct rtw_softc *sc);
    120 static void rtw_print_txdesc(struct rtw_softc *, const char *,
    121     struct rtw_txsoft *, struct rtw_txdesc_blk *, int);
    122 static int rtw_sysctl_verify_debug(SYSCTLFN_PROTO);
    123 static int rtw_sysctl_verify_rxbufs_limit(SYSCTLFN_PROTO);
    124 #endif /* RTW_DEBUG */
    125 #ifdef RTW_DIAG
    126 static void rtw_txring_fixup(struct rtw_softc *sc, const char *fn, int ln);
    127 #endif /* RTW_DIAG */
    128 
    129 /*
    130  * Setup sysctl(3) MIB, hw.rtw.*
    131  *
    132  * TBD condition CTLFLAG_PERMANENT on being a module or not
    133  */
    134 SYSCTL_SETUP(sysctl_rtw, "sysctl rtw(4) subtree setup")
    135 {
    136 	int rc;
    137 	const struct sysctlnode *cnode, *rnode;
    138 
    139 	if ((rc = sysctl_createv(clog, 0, NULL, &rnode,
    140 	    CTLFLAG_PERMANENT, CTLTYPE_NODE, "rtw",
    141 	    "Realtek RTL818x 802.11 controls",
    142 	    NULL, 0, NULL, 0, CTL_HW, CTL_CREATE, CTL_EOL)) != 0)
    143 		goto err;
    144 
    145 #ifdef RTW_DEBUG
    146 	/* control debugging printfs */
    147 	if ((rc = sysctl_createv(clog, 0, &rnode, &cnode,
    148 	    CTLFLAG_PERMANENT | CTLFLAG_READWRITE, CTLTYPE_INT,
    149 	    "debug", SYSCTL_DESCR("Enable RTL818x debugging output"),
    150 	    rtw_sysctl_verify_debug, 0, &rtw_debug, 0,
    151 	    CTL_CREATE, CTL_EOL)) != 0)
    152 		goto err;
    153 
    154 	/* Limit rx buffers, for simulating resource exhaustion. */
    155 	if ((rc = sysctl_createv(clog, 0, &rnode, &cnode,
    156 	    CTLFLAG_PERMANENT | CTLFLAG_READWRITE, CTLTYPE_INT,
    157 	    "rxbufs_limit",
    158 	    SYSCTL_DESCR("Set rx buffers limit"),
    159 	    rtw_sysctl_verify_rxbufs_limit, 0, &rtw_rxbufs_limit, 0,
    160 	    CTL_CREATE, CTL_EOL)) != 0)
    161 		goto err;
    162 
    163 #endif /* RTW_DEBUG */
    164 	/* set fallback RF programming method */
    165 	if ((rc = sysctl_createv(clog, 0, &rnode, &cnode,
    166 	    CTLFLAG_PERMANENT | CTLFLAG_READWRITE, CTLTYPE_INT,
    167 	    "rfprog_fallback",
    168 	    SYSCTL_DESCR("Set fallback RF programming method"),
    169 	    rtw_sysctl_verify_rfprog, 0, &rtw_rfprog_fallback, 0,
    170 	    CTL_CREATE, CTL_EOL)) != 0)
    171 		goto err;
    172 
    173 	/* force host to control RF I/O bus */
    174 	if ((rc = sysctl_createv(clog, 0, &rnode, &cnode,
    175 	    CTLFLAG_PERMANENT | CTLFLAG_READWRITE, CTLTYPE_INT,
    176 	    "host_rfio", SYSCTL_DESCR("Enable host control of RF I/O"),
    177 	    rtw_sysctl_verify_rfio, 0, &rtw_host_rfio, 0,
    178 	    CTL_CREATE, CTL_EOL)) != 0)
    179 		goto err;
    180 
    181 	return;
    182 err:
    183 	printf("%s: sysctl_createv failed (rc = %d)\n", __func__, rc);
    184 }
    185 
    186 static int
    187 rtw_sysctl_verify(SYSCTLFN_ARGS, int lower, int upper)
    188 {
    189 	int error, t;
    190 	struct sysctlnode node;
    191 
    192 	node = *rnode;
    193 	t = *(int*)rnode->sysctl_data;
    194 	node.sysctl_data = &t;
    195 	error = sysctl_lookup(SYSCTLFN_CALL(&node));
    196 	if (error || newp == NULL)
    197 		return (error);
    198 
    199 	if (t < lower || t > upper)
    200 		return (EINVAL);
    201 
    202 	*(int*)rnode->sysctl_data = t;
    203 
    204 	return (0);
    205 }
    206 
    207 static int
    208 rtw_sysctl_verify_rfprog(SYSCTLFN_ARGS)
    209 {
    210 	return rtw_sysctl_verify(SYSCTLFN_CALL(__UNCONST(rnode)), 0,
    211 	    __SHIFTOUT(RTW_CONFIG4_RFTYPE_MASK, RTW_CONFIG4_RFTYPE_MASK));
    212 }
    213 
    214 static int
    215 rtw_sysctl_verify_rfio(SYSCTLFN_ARGS)
    216 {
    217 	return rtw_sysctl_verify(SYSCTLFN_CALL(__UNCONST(rnode)), 0, 1);
    218 }
    219 
    220 #ifdef RTW_DEBUG
    221 static int
    222 rtw_sysctl_verify_debug(SYSCTLFN_ARGS)
    223 {
    224 	return rtw_sysctl_verify(SYSCTLFN_CALL(__UNCONST(rnode)),
    225 	    0, RTW_DEBUG_MAX);
    226 }
    227 
    228 static int
    229 rtw_sysctl_verify_rxbufs_limit(SYSCTLFN_ARGS)
    230 {
    231 	return rtw_sysctl_verify(SYSCTLFN_CALL(__UNCONST(rnode)),
    232 	    0, RTW_RXQLEN);
    233 }
    234 
    235 static void
    236 rtw_print_regs(struct rtw_regs *regs, const char *dvname, const char *where)
    237 {
    238 #define PRINTREG32(sc, reg)				\
    239 	RTW_DPRINTF(RTW_DEBUG_REGDUMP,			\
    240 	    ("%s: reg[ " #reg " / %03x ] = %08x\n",	\
    241 	    dvname, reg, RTW_READ(regs, reg)))
    242 
    243 #define PRINTREG16(sc, reg)				\
    244 	RTW_DPRINTF(RTW_DEBUG_REGDUMP,			\
    245 	    ("%s: reg[ " #reg " / %03x ] = %04x\n",	\
    246 	    dvname, reg, RTW_READ16(regs, reg)))
    247 
    248 #define PRINTREG8(sc, reg)				\
    249 	RTW_DPRINTF(RTW_DEBUG_REGDUMP,			\
    250 	    ("%s: reg[ " #reg " / %03x ] = %02x\n",	\
    251 	    dvname, reg, RTW_READ8(regs, reg)))
    252 
    253 	RTW_DPRINTF(RTW_DEBUG_REGDUMP, ("%s: %s\n", dvname, where));
    254 
    255 	PRINTREG32(regs, RTW_IDR0);
    256 	PRINTREG32(regs, RTW_IDR1);
    257 	PRINTREG32(regs, RTW_MAR0);
    258 	PRINTREG32(regs, RTW_MAR1);
    259 	PRINTREG32(regs, RTW_TSFTRL);
    260 	PRINTREG32(regs, RTW_TSFTRH);
    261 	PRINTREG32(regs, RTW_TLPDA);
    262 	PRINTREG32(regs, RTW_TNPDA);
    263 	PRINTREG32(regs, RTW_THPDA);
    264 	PRINTREG32(regs, RTW_TCR);
    265 	PRINTREG32(regs, RTW_RCR);
    266 	PRINTREG32(regs, RTW_TINT);
    267 	PRINTREG32(regs, RTW_TBDA);
    268 	PRINTREG32(regs, RTW_ANAPARM);
    269 	PRINTREG32(regs, RTW_BB);
    270 	PRINTREG32(regs, RTW_PHYCFG);
    271 	PRINTREG32(regs, RTW_WAKEUP0L);
    272 	PRINTREG32(regs, RTW_WAKEUP0H);
    273 	PRINTREG32(regs, RTW_WAKEUP1L);
    274 	PRINTREG32(regs, RTW_WAKEUP1H);
    275 	PRINTREG32(regs, RTW_WAKEUP2LL);
    276 	PRINTREG32(regs, RTW_WAKEUP2LH);
    277 	PRINTREG32(regs, RTW_WAKEUP2HL);
    278 	PRINTREG32(regs, RTW_WAKEUP2HH);
    279 	PRINTREG32(regs, RTW_WAKEUP3LL);
    280 	PRINTREG32(regs, RTW_WAKEUP3LH);
    281 	PRINTREG32(regs, RTW_WAKEUP3HL);
    282 	PRINTREG32(regs, RTW_WAKEUP3HH);
    283 	PRINTREG32(regs, RTW_WAKEUP4LL);
    284 	PRINTREG32(regs, RTW_WAKEUP4LH);
    285 	PRINTREG32(regs, RTW_WAKEUP4HL);
    286 	PRINTREG32(regs, RTW_WAKEUP4HH);
    287 	PRINTREG32(regs, RTW_DK0);
    288 	PRINTREG32(regs, RTW_DK1);
    289 	PRINTREG32(regs, RTW_DK2);
    290 	PRINTREG32(regs, RTW_DK3);
    291 	PRINTREG32(regs, RTW_RETRYCTR);
    292 	PRINTREG32(regs, RTW_RDSAR);
    293 	PRINTREG32(regs, RTW_FER);
    294 	PRINTREG32(regs, RTW_FEMR);
    295 	PRINTREG32(regs, RTW_FPSR);
    296 	PRINTREG32(regs, RTW_FFER);
    297 
    298 	/* 16-bit registers */
    299 	PRINTREG16(regs, RTW_BRSR);
    300 	PRINTREG16(regs, RTW_IMR);
    301 	PRINTREG16(regs, RTW_ISR);
    302 	PRINTREG16(regs, RTW_BCNITV);
    303 	PRINTREG16(regs, RTW_ATIMWND);
    304 	PRINTREG16(regs, RTW_BINTRITV);
    305 	PRINTREG16(regs, RTW_ATIMTRITV);
    306 	PRINTREG16(regs, RTW_CRC16ERR);
    307 	PRINTREG16(regs, RTW_CRC0);
    308 	PRINTREG16(regs, RTW_CRC1);
    309 	PRINTREG16(regs, RTW_CRC2);
    310 	PRINTREG16(regs, RTW_CRC3);
    311 	PRINTREG16(regs, RTW_CRC4);
    312 	PRINTREG16(regs, RTW_CWR);
    313 
    314 	/* 8-bit registers */
    315 	PRINTREG8(regs, RTW_CR);
    316 	PRINTREG8(regs, RTW_9346CR);
    317 	PRINTREG8(regs, RTW_CONFIG0);
    318 	PRINTREG8(regs, RTW_CONFIG1);
    319 	PRINTREG8(regs, RTW_CONFIG2);
    320 	PRINTREG8(regs, RTW_MSR);
    321 	PRINTREG8(regs, RTW_CONFIG3);
    322 	PRINTREG8(regs, RTW_CONFIG4);
    323 	PRINTREG8(regs, RTW_TESTR);
    324 	PRINTREG8(regs, RTW_PSR);
    325 	PRINTREG8(regs, RTW_SCR);
    326 	PRINTREG8(regs, RTW_PHYDELAY);
    327 	PRINTREG8(regs, RTW_CRCOUNT);
    328 	PRINTREG8(regs, RTW_PHYADDR);
    329 	PRINTREG8(regs, RTW_PHYDATAW);
    330 	PRINTREG8(regs, RTW_PHYDATAR);
    331 	PRINTREG8(regs, RTW_CONFIG5);
    332 	PRINTREG8(regs, RTW_TPPOLL);
    333 
    334 	PRINTREG16(regs, RTW_BSSID16);
    335 	PRINTREG32(regs, RTW_BSSID32);
    336 #undef PRINTREG32
    337 #undef PRINTREG16
    338 #undef PRINTREG8
    339 }
    340 #endif /* RTW_DEBUG */
    341 
    342 void
    343 rtw_continuous_tx_enable(struct rtw_softc *sc, int enable)
    344 {
    345 	struct rtw_regs *regs = &sc->sc_regs;
    346 
    347 	uint32_t tcr;
    348 	tcr = RTW_READ(regs, RTW_TCR);
    349 	tcr &= ~RTW_TCR_LBK_MASK;
    350 	if (enable)
    351 		tcr |= RTW_TCR_LBK_CONT;
    352 	else
    353 		tcr |= RTW_TCR_LBK_NORMAL;
    354 	RTW_WRITE(regs, RTW_TCR, tcr);
    355 	RTW_SYNC(regs, RTW_TCR, RTW_TCR);
    356 	rtw_set_access(regs, RTW_ACCESS_ANAPARM);
    357 	rtw_txdac_enable(sc, !enable);
    358 	rtw_set_access(regs, RTW_ACCESS_ANAPARM);/* XXX Voodoo from Linux. */
    359 	rtw_set_access(regs, RTW_ACCESS_NONE);
    360 }
    361 
    362 #ifdef RTW_DEBUG
    363 static const char *
    364 rtw_access_string(enum rtw_access access)
    365 {
    366 	switch (access) {
    367 	case RTW_ACCESS_NONE:
    368 		return "none";
    369 	case RTW_ACCESS_CONFIG:
    370 		return "config";
    371 	case RTW_ACCESS_ANAPARM:
    372 		return "anaparm";
    373 	default:
    374 		return "unknown";
    375 	}
    376 }
    377 #endif /* RTW_DEBUG */
    378 
    379 static void
    380 rtw_set_access1(struct rtw_regs *regs, enum rtw_access naccess)
    381 {
    382 	KASSERT(/* naccess >= RTW_ACCESS_NONE && */
    383 	    naccess <= RTW_ACCESS_ANAPARM);
    384 	KASSERT(/* regs->r_access >= RTW_ACCESS_NONE && */
    385 	    regs->r_access <= RTW_ACCESS_ANAPARM);
    386 
    387 	if (naccess == regs->r_access)
    388 		return;
    389 
    390 	switch (naccess) {
    391 	case RTW_ACCESS_NONE:
    392 		switch (regs->r_access) {
    393 		case RTW_ACCESS_ANAPARM:
    394 			rtw_anaparm_enable(regs, 0);
    395 			/*FALLTHROUGH*/
    396 		case RTW_ACCESS_CONFIG:
    397 			rtw_config0123_enable(regs, 0);
    398 			/*FALLTHROUGH*/
    399 		case RTW_ACCESS_NONE:
    400 			break;
    401 		}
    402 		break;
    403 	case RTW_ACCESS_CONFIG:
    404 		switch (regs->r_access) {
    405 		case RTW_ACCESS_NONE:
    406 			rtw_config0123_enable(regs, 1);
    407 			/*FALLTHROUGH*/
    408 		case RTW_ACCESS_CONFIG:
    409 			break;
    410 		case RTW_ACCESS_ANAPARM:
    411 			rtw_anaparm_enable(regs, 0);
    412 			break;
    413 		}
    414 		break;
    415 	case RTW_ACCESS_ANAPARM:
    416 		switch (regs->r_access) {
    417 		case RTW_ACCESS_NONE:
    418 			rtw_config0123_enable(regs, 1);
    419 			/*FALLTHROUGH*/
    420 		case RTW_ACCESS_CONFIG:
    421 			rtw_anaparm_enable(regs, 1);
    422 			/*FALLTHROUGH*/
    423 		case RTW_ACCESS_ANAPARM:
    424 			break;
    425 		}
    426 		break;
    427 	}
    428 }
    429 
    430 void
    431 rtw_set_access(struct rtw_regs *regs, enum rtw_access access)
    432 {
    433 	rtw_set_access1(regs, access);
    434 	RTW_DPRINTF(RTW_DEBUG_ACCESS,
    435 	    ("%s: access %s -> %s\n", __func__,
    436 	    rtw_access_string(regs->r_access),
    437 	    rtw_access_string(access)));
    438 	regs->r_access = access;
    439 }
    440 
    441 /*
    442  * Enable registers, switch register banks.
    443  */
    444 void
    445 rtw_config0123_enable(struct rtw_regs *regs, int enable)
    446 {
    447 	uint8_t ecr;
    448 	ecr = RTW_READ8(regs, RTW_9346CR);
    449 	ecr &= ~(RTW_9346CR_EEM_MASK | RTW_9346CR_EECS | RTW_9346CR_EESK);
    450 	if (enable)
    451 		ecr |= RTW_9346CR_EEM_CONFIG;
    452 	else {
    453 		RTW_WBW(regs, RTW_9346CR, MAX(RTW_CONFIG0, RTW_CONFIG3));
    454 		ecr |= RTW_9346CR_EEM_NORMAL;
    455 	}
    456 	RTW_WRITE8(regs, RTW_9346CR, ecr);
    457 	RTW_SYNC(regs, RTW_9346CR, RTW_9346CR);
    458 }
    459 
    460 /* requires rtw_config0123_enable(, 1) */
    461 void
    462 rtw_anaparm_enable(struct rtw_regs *regs, int enable)
    463 {
    464 	uint8_t cfg3;
    465 
    466 	cfg3 = RTW_READ8(regs, RTW_CONFIG3);
    467 	cfg3 |= RTW_CONFIG3_CLKRUNEN;
    468 	if (enable)
    469 		cfg3 |= RTW_CONFIG3_PARMEN;
    470 	else
    471 		cfg3 &= ~RTW_CONFIG3_PARMEN;
    472 	RTW_WRITE8(regs, RTW_CONFIG3, cfg3);
    473 	RTW_SYNC(regs, RTW_CONFIG3, RTW_CONFIG3);
    474 }
    475 
    476 /* requires rtw_anaparm_enable(, 1) */
    477 void
    478 rtw_txdac_enable(struct rtw_softc *sc, int enable)
    479 {
    480 	uint32_t anaparm;
    481 	struct rtw_regs *regs = &sc->sc_regs;
    482 
    483 	anaparm = RTW_READ(regs, RTW_ANAPARM);
    484 	if (enable)
    485 		anaparm &= ~RTW_ANAPARM_TXDACOFF;
    486 	else
    487 		anaparm |= RTW_ANAPARM_TXDACOFF;
    488 	RTW_WRITE(regs, RTW_ANAPARM, anaparm);
    489 	RTW_SYNC(regs, RTW_ANAPARM, RTW_ANAPARM);
    490 }
    491 
    492 static inline int
    493 rtw_chip_reset1(struct rtw_regs *regs, device_t dev)
    494 {
    495 	uint8_t cr;
    496 	int i;
    497 
    498 	RTW_WRITE8(regs, RTW_CR, RTW_CR_RST);
    499 
    500 	RTW_WBR(regs, RTW_CR, RTW_CR);
    501 
    502 	for (i = 0; i < 1000; i++) {
    503 		if ((cr = RTW_READ8(regs, RTW_CR) & RTW_CR_RST) == 0) {
    504 			RTW_DPRINTF(RTW_DEBUG_RESET,
    505 			    ("%s: reset in %dus\n", device_xname(dev), i));
    506 			return 0;
    507 		}
    508 		RTW_RBR(regs, RTW_CR, RTW_CR);
    509 		DELAY(10); /* 10us */
    510 	}
    511 
    512 	aprint_error_dev(dev, "reset failed\n");
    513 	return ETIMEDOUT;
    514 }
    515 
    516 static inline int
    517 rtw_chip_reset(struct rtw_regs *regs, device_t dev)
    518 {
    519 	uint32_t tcr;
    520 
    521 	/* from Linux driver */
    522 	tcr = RTW_TCR_CWMIN | RTW_TCR_MXDMA_2048 |
    523 	      __SHIFTIN(7, RTW_TCR_SRL_MASK) | __SHIFTIN(7, RTW_TCR_LRL_MASK);
    524 
    525 	RTW_WRITE(regs, RTW_TCR, tcr);
    526 
    527 	RTW_WBW(regs, RTW_CR, RTW_TCR);
    528 
    529 	return rtw_chip_reset1(regs, dev);
    530 }
    531 
    532 static int
    533 rtw_wep_decap(struct ieee80211_key *k, struct mbuf *m, int hdrlen)
    534 {
    535 	struct ieee80211_key keycopy;
    536 
    537 	RTW_DPRINTF(RTW_DEBUG_KEY, ("%s:\n", __func__));
    538 
    539 	keycopy = *k;
    540 	keycopy.wk_flags &= ~IEEE80211_KEY_SWCRYPT;
    541 
    542 	return (*ieee80211_cipher_wep.ic_decap)(&keycopy, m, hdrlen);
    543 }
    544 
    545 static int
    546 rtw_key_delete(struct ieee80211com *ic, const struct ieee80211_key *k)
    547 {
    548 	struct rtw_softc *sc = ic->ic_ifp->if_softc;
    549 
    550 	DPRINTF(sc, RTW_DEBUG_KEY, ("%s: delete key %u\n", __func__,
    551 	    k->wk_keyix));
    552 
    553 	KASSERT(k->wk_keyix < IEEE80211_WEP_NKID);
    554 
    555 	if (k->wk_keylen != 0 &&
    556 	    k->wk_cipher->ic_cipher == IEEE80211_CIPHER_WEP)
    557 		sc->sc_flags &= ~RTW_F_DK_VALID;
    558 
    559 	return 1;
    560 }
    561 
    562 static int
    563 rtw_key_set(struct ieee80211com *ic, const struct ieee80211_key *k,
    564     const uint8_t mac[IEEE80211_ADDR_LEN])
    565 {
    566 	struct rtw_softc *sc = ic->ic_ifp->if_softc;
    567 
    568 	DPRINTF(sc, RTW_DEBUG_KEY, ("%s: set key %u\n", __func__, k->wk_keyix));
    569 
    570 	KASSERT(k->wk_keyix < IEEE80211_WEP_NKID);
    571 
    572 	sc->sc_flags &= ~RTW_F_DK_VALID;
    573 
    574 	return 1;
    575 }
    576 
    577 static void
    578 rtw_key_update_begin(struct ieee80211com *ic)
    579 {
    580 #ifdef RTW_DEBUG
    581 	struct ifnet *ifp = ic->ic_ifp;
    582 	struct rtw_softc *sc = ifp->if_softc;
    583 #endif
    584 
    585 	DPRINTF(sc, RTW_DEBUG_KEY, ("%s:\n", __func__));
    586 }
    587 
    588 static void
    589 rtw_tx_kick(struct rtw_regs *regs, uint8_t ringsel)
    590 {
    591 	uint8_t tppoll;
    592 
    593 	tppoll = RTW_READ8(regs, RTW_TPPOLL);
    594 	tppoll &= ~RTW_TPPOLL_SALL;
    595 	tppoll |= ringsel & RTW_TPPOLL_ALL;
    596 	RTW_WRITE8(regs, RTW_TPPOLL, tppoll);
    597 	RTW_SYNC(regs, RTW_TPPOLL, RTW_TPPOLL);
    598 }
    599 
    600 static void
    601 rtw_key_update_end(struct ieee80211com *ic)
    602 {
    603 	struct ifnet *ifp = ic->ic_ifp;
    604 	struct rtw_softc *sc = ifp->if_softc;
    605 
    606 	DPRINTF(sc, RTW_DEBUG_KEY, ("%s:\n", __func__));
    607 
    608 	if ((sc->sc_flags & RTW_F_DK_VALID) != 0 ||
    609 	    !device_is_active(sc->sc_dev))
    610 		return;
    611 
    612 	rtw_io_enable(sc, RTW_CR_RE | RTW_CR_TE, 0);
    613 	rtw_wep_setkeys(sc, ic->ic_nw_keys, ic->ic_def_txkey);
    614 	rtw_io_enable(sc, RTW_CR_RE | RTW_CR_TE,
    615 	    (ifp->if_flags & IFF_RUNNING) != 0);
    616 }
    617 
    618 static bool
    619 rtw_key_hwsupp(uint32_t flags, const struct ieee80211_key *k)
    620 {
    621 	if (k->wk_cipher->ic_cipher != IEEE80211_CIPHER_WEP)
    622 		return false;
    623 
    624 	return	((flags & RTW_C_RXWEP_40) != 0 && k->wk_keylen == 5) ||
    625 		((flags & RTW_C_RXWEP_104) != 0 && k->wk_keylen == 13);
    626 }
    627 
    628 static void
    629 rtw_wep_setkeys(struct rtw_softc *sc, struct ieee80211_key *wk, int txkey)
    630 {
    631 	uint8_t psr, scr;
    632 	int i, keylen = 0;
    633 	struct rtw_regs *regs;
    634 	union rtw_keys *rk;
    635 
    636 	regs = &sc->sc_regs;
    637 	rk = &sc->sc_keys;
    638 
    639 	(void)memset(rk, 0, sizeof(*rk));
    640 
    641 	/* Temporarily use software crypto for all keys. */
    642 	for (i = 0; i < IEEE80211_WEP_NKID; i++) {
    643 		if (wk[i].wk_cipher == &rtw_cipher_wep)
    644 			wk[i].wk_cipher = &ieee80211_cipher_wep;
    645 	}
    646 
    647 	rtw_set_access(regs, RTW_ACCESS_CONFIG);
    648 
    649 	psr = RTW_READ8(regs, RTW_PSR);
    650 	scr = RTW_READ8(regs, RTW_SCR);
    651 	scr &= ~(RTW_SCR_KM_MASK | RTW_SCR_TXSECON | RTW_SCR_RXSECON);
    652 
    653 	if ((sc->sc_ic.ic_flags & IEEE80211_F_PRIVACY) == 0)
    654 		goto out;
    655 
    656 	for (i = 0; i < IEEE80211_WEP_NKID; i++) {
    657 		if (!rtw_key_hwsupp(sc->sc_flags, &wk[i]))
    658 			continue;
    659 		if (i == txkey) {
    660 			keylen = wk[i].wk_keylen;
    661 			break;
    662 		}
    663 		keylen = MAX(keylen, wk[i].wk_keylen);
    664 	}
    665 
    666 	if (keylen == 5)
    667 		scr |= RTW_SCR_KM_WEP40 | RTW_SCR_RXSECON;
    668 	else if (keylen == 13)
    669 		scr |= RTW_SCR_KM_WEP104 | RTW_SCR_RXSECON;
    670 
    671 	for (i = 0; i < IEEE80211_WEP_NKID; i++) {
    672 		if (wk[i].wk_keylen != keylen ||
    673 		    wk[i].wk_cipher->ic_cipher != IEEE80211_CIPHER_WEP)
    674 			continue;
    675 		/* h/w will decrypt, s/w still strips headers */
    676 		wk[i].wk_cipher = &rtw_cipher_wep;
    677 		(void)memcpy(rk->rk_keys[i], wk[i].wk_key, wk[i].wk_keylen);
    678 	}
    679 
    680 out:
    681 	RTW_WRITE8(regs, RTW_PSR, psr & ~RTW_PSR_PSEN);
    682 
    683 	bus_space_write_region_stream_4(regs->r_bt, regs->r_bh,
    684 	    RTW_DK0, rk->rk_words, __arraycount(rk->rk_words));
    685 
    686 	bus_space_barrier(regs->r_bt, regs->r_bh, RTW_DK0, sizeof(rk->rk_words),
    687 	    BUS_SPACE_BARRIER_READ | BUS_SPACE_BARRIER_WRITE);
    688 
    689 	RTW_DPRINTF(RTW_DEBUG_KEY,
    690 	    ("%s.%d: scr %02" PRIx8 ", keylen %d\n", __func__, __LINE__, scr,
    691 	     keylen));
    692 
    693 	RTW_WBW(regs, RTW_DK0, RTW_PSR);
    694 	RTW_WRITE8(regs, RTW_PSR, psr);
    695 	RTW_WBW(regs, RTW_PSR, RTW_SCR);
    696 	RTW_WRITE8(regs, RTW_SCR, scr);
    697 	RTW_SYNC(regs, RTW_SCR, RTW_SCR);
    698 	rtw_set_access(regs, RTW_ACCESS_NONE);
    699 	sc->sc_flags |= RTW_F_DK_VALID;
    700 }
    701 
    702 static inline int
    703 rtw_recall_eeprom(struct rtw_regs *regs, device_t dev)
    704 {
    705 	int i;
    706 	uint8_t ecr;
    707 
    708 	ecr = RTW_READ8(regs, RTW_9346CR);
    709 	ecr = (ecr & ~RTW_9346CR_EEM_MASK) | RTW_9346CR_EEM_AUTOLOAD;
    710 	RTW_WRITE8(regs, RTW_9346CR, ecr);
    711 
    712 	RTW_WBR(regs, RTW_9346CR, RTW_9346CR);
    713 
    714 	/* wait 25ms for completion */
    715 	for (i = 0; i < 250; i++) {
    716 		ecr = RTW_READ8(regs, RTW_9346CR);
    717 		if ((ecr & RTW_9346CR_EEM_MASK) == RTW_9346CR_EEM_NORMAL) {
    718 			RTW_DPRINTF(RTW_DEBUG_RESET,
    719 			    ("%s: recall EEPROM in %dus\n", device_xname(dev),
    720 			    i * 100));
    721 			return 0;
    722 		}
    723 		RTW_RBR(regs, RTW_9346CR, RTW_9346CR);
    724 		DELAY(100);
    725 	}
    726 	aprint_error_dev(dev, "recall EEPROM failed\n");
    727 	return ETIMEDOUT;
    728 }
    729 
    730 static inline int
    731 rtw_reset(struct rtw_softc *sc)
    732 {
    733 	int rc;
    734 	uint8_t config1;
    735 
    736 	sc->sc_flags &= ~RTW_F_DK_VALID;
    737 
    738 	if ((rc = rtw_chip_reset(&sc->sc_regs, sc->sc_dev)) != 0)
    739 		return rc;
    740 
    741 	rc = rtw_recall_eeprom(&sc->sc_regs, sc->sc_dev);
    742 
    743 	config1 = RTW_READ8(&sc->sc_regs, RTW_CONFIG1);
    744 	RTW_WRITE8(&sc->sc_regs, RTW_CONFIG1, config1 & ~RTW_CONFIG1_PMEN);
    745 	/* TBD turn off maximum power saving? */
    746 
    747 	return 0;
    748 }
    749 
    750 static inline int
    751 rtw_txdesc_dmamaps_create(bus_dma_tag_t dmat, struct rtw_txsoft *descs,
    752     u_int ndescs)
    753 {
    754 	int i, rc = 0;
    755 	for (i = 0; i < ndescs; i++) {
    756 		rc = bus_dmamap_create(dmat, MCLBYTES, RTW_MAXPKTSEGS, MCLBYTES,
    757 		    0, 0, &descs[i].ts_dmamap);
    758 		if (rc != 0)
    759 			break;
    760 	}
    761 	return rc;
    762 }
    763 
    764 static inline int
    765 rtw_rxdesc_dmamaps_create(bus_dma_tag_t dmat, struct rtw_rxsoft *descs,
    766     u_int ndescs)
    767 {
    768 	int i, rc = 0;
    769 	for (i = 0; i < ndescs; i++) {
    770 		rc = bus_dmamap_create(dmat, MCLBYTES, 1, MCLBYTES, 0, 0,
    771 		    &descs[i].rs_dmamap);
    772 		if (rc != 0)
    773 			break;
    774 	}
    775 	return rc;
    776 }
    777 
    778 static inline void
    779 rtw_rxdesc_dmamaps_destroy(bus_dma_tag_t dmat, struct rtw_rxsoft *descs,
    780     u_int ndescs)
    781 {
    782 	int i;
    783 	for (i = 0; i < ndescs; i++) {
    784 		if (descs[i].rs_dmamap != NULL)
    785 			bus_dmamap_destroy(dmat, descs[i].rs_dmamap);
    786 	}
    787 }
    788 
    789 static inline void
    790 rtw_txdesc_dmamaps_destroy(bus_dma_tag_t dmat, struct rtw_txsoft *descs,
    791     u_int ndescs)
    792 {
    793 	int i;
    794 	for (i = 0; i < ndescs; i++) {
    795 		if (descs[i].ts_dmamap != NULL)
    796 			bus_dmamap_destroy(dmat, descs[i].ts_dmamap);
    797 	}
    798 }
    799 
    800 static inline void
    801 rtw_srom_free(struct rtw_srom *sr)
    802 {
    803 	sr->sr_size = 0;
    804 	if (sr->sr_content == NULL)
    805 		return;
    806 	free(sr->sr_content, M_DEVBUF);
    807 	sr->sr_content = NULL;
    808 }
    809 
    810 static void
    811 rtw_srom_defaults(struct rtw_srom *sr, uint32_t *flags,
    812     uint8_t *cs_threshold, enum rtw_rfchipid *rfchipid, uint32_t *rcr)
    813 {
    814 	*flags |= (RTW_F_DIGPHY | RTW_F_ANTDIV);
    815 	*cs_threshold = RTW_SR_ENERGYDETTHR_DEFAULT;
    816 	*rcr |= RTW_RCR_ENCS1;
    817 	*rfchipid = RTW_RFCHIPID_PHILIPS;
    818 }
    819 
    820 static int
    821 rtw_srom_parse(struct rtw_srom *sr, uint32_t *flags, uint8_t *cs_threshold,
    822     enum rtw_rfchipid *rfchipid, uint32_t *rcr, enum rtw_locale *locale,
    823     device_t dev)
    824 {
    825 	int i;
    826 	const char *rfname, *paname;
    827 	char scratch[sizeof("unknown 0xXX")];
    828 	uint16_t srom_version;
    829 
    830 	*flags &= ~(RTW_F_DIGPHY | RTW_F_DFLANTB | RTW_F_ANTDIV);
    831 	*rcr &= ~(RTW_RCR_ENCS1 | RTW_RCR_ENCS2);
    832 
    833 	srom_version = RTW_SR_GET16(sr, RTW_SR_VERSION);
    834 
    835 	if (srom_version <= 0x0101) {
    836 		aprint_error_dev(dev,
    837 		    "SROM version %d.%d is not understood, "
    838 		    "limping along with defaults\n",
    839 		    srom_version >> 8, srom_version & 0xff);
    840 		rtw_srom_defaults(sr, flags, cs_threshold, rfchipid, rcr);
    841 		return 0;
    842 	} else {
    843 		aprint_verbose_dev(dev, "SROM version %d.%d\n",
    844 		    srom_version >> 8, srom_version & 0xff);
    845 	}
    846 
    847 	uint8_t mac[IEEE80211_ADDR_LEN];
    848 	for (i = 0; i < IEEE80211_ADDR_LEN; i++)
    849 		mac[i] = RTW_SR_GET(sr, RTW_SR_MAC + i);
    850 	__USE(mac);
    851 
    852 	RTW_DPRINTF(RTW_DEBUG_ATTACH,
    853 	    ("%s: EEPROM MAC %s\n", device_xname(dev), ether_sprintf(mac)));
    854 
    855 	*cs_threshold = RTW_SR_GET(sr, RTW_SR_ENERGYDETTHR);
    856 
    857 	if ((RTW_SR_GET(sr, RTW_SR_CONFIG2) & RTW_CONFIG2_ANT) != 0)
    858 		*flags |= RTW_F_ANTDIV;
    859 
    860 	/* Note well: the sense of the RTW_SR_RFPARM_DIGPHY bit seems
    861 	 * to be reversed.
    862 	 */
    863 	if ((RTW_SR_GET(sr, RTW_SR_RFPARM) & RTW_SR_RFPARM_DIGPHY) == 0)
    864 		*flags |= RTW_F_DIGPHY;
    865 	if ((RTW_SR_GET(sr, RTW_SR_RFPARM) & RTW_SR_RFPARM_DFLANTB) != 0)
    866 		*flags |= RTW_F_DFLANTB;
    867 
    868 	*rcr |= __SHIFTIN(__SHIFTOUT(RTW_SR_GET(sr, RTW_SR_RFPARM),
    869 	    RTW_SR_RFPARM_CS_MASK), RTW_RCR_ENCS1);
    870 
    871 	if ((RTW_SR_GET(sr, RTW_SR_CONFIG0) & RTW_CONFIG0_WEP104) != 0)
    872 		*flags |= RTW_C_RXWEP_104;
    873 
    874 	*flags |= RTW_C_RXWEP_40;	/* XXX */
    875 
    876 	*rfchipid = RTW_SR_GET(sr, RTW_SR_RFCHIPID);
    877 	switch (*rfchipid) {
    878 	case RTW_RFCHIPID_GCT:		/* this combo seen in the wild */
    879 		rfname = "GCT GRF5101";
    880 		paname = "Winspring WS9901";
    881 		break;
    882 	case RTW_RFCHIPID_MAXIM:
    883 		rfname = "Maxim MAX2820";	/* guess */
    884 		paname = "Maxim MAX2422";	/* guess */
    885 		break;
    886 	case RTW_RFCHIPID_INTERSIL:
    887 		rfname = "Intersil HFA3873";	/* guess */
    888 		paname = "Intersil <unknown>";
    889 		break;
    890 	case RTW_RFCHIPID_PHILIPS:	/* this combo seen in the wild */
    891 		rfname = "Philips SA2400A";
    892 		paname = "Philips SA2411";
    893 		break;
    894 	case RTW_RFCHIPID_RFMD:
    895 		/* this is the same front-end as an atw(4)! */
    896 		rfname = "RFMD RF2948B, "	/* mentioned in Realtek docs */
    897 			 "LNA: RFMD RF2494, "	/* mentioned in Realtek docs */
    898 			 "SYN: Silicon Labs Si4126";	/* inferred from
    899 							 * reference driver
    900 							 */
    901 		paname = "RFMD RF2189";		/* mentioned in Realtek docs */
    902 		break;
    903 	case RTW_RFCHIPID_RESERVED:
    904 		rfname = paname = "reserved";
    905 		break;
    906 	default:
    907 		snprintf(scratch, sizeof(scratch), "unknown 0x%02x", *rfchipid);
    908 		rfname = paname = scratch;
    909 	}
    910 	aprint_normal_dev(dev, "RF: %s, PA: %s\n", rfname, paname);
    911 
    912 	switch (RTW_SR_GET(sr, RTW_SR_CONFIG0) & RTW_CONFIG0_GL_MASK) {
    913 	case RTW_CONFIG0_GL_USA:
    914 	case _RTW_CONFIG0_GL_USA:
    915 		*locale = RTW_LOCALE_USA;
    916 		break;
    917 	case RTW_CONFIG0_GL_EUROPE:
    918 		*locale = RTW_LOCALE_EUROPE;
    919 		break;
    920 	case RTW_CONFIG0_GL_JAPAN:
    921 		*locale = RTW_LOCALE_JAPAN;
    922 		break;
    923 	default:
    924 		*locale = RTW_LOCALE_UNKNOWN;
    925 		break;
    926 	}
    927 	return 0;
    928 }
    929 
    930 /* Returns -1 on failure. */
    931 static int
    932 rtw_srom_read(struct rtw_regs *regs, uint32_t flags, struct rtw_srom *sr,
    933     device_t dev)
    934 {
    935 	int rc;
    936 	struct seeprom_descriptor sd;
    937 	uint8_t ecr;
    938 
    939 	(void)memset(&sd, 0, sizeof(sd));
    940 
    941 	ecr = RTW_READ8(regs, RTW_9346CR);
    942 
    943 	if ((flags & RTW_F_9356SROM) != 0) {
    944 		RTW_DPRINTF(RTW_DEBUG_ATTACH, ("%s: 93c56 SROM\n",
    945 		    device_xname(dev)));
    946 		sr->sr_size = 256;
    947 		sd.sd_chip = C56_66;
    948 	} else {
    949 		RTW_DPRINTF(RTW_DEBUG_ATTACH, ("%s: 93c46 SROM\n",
    950 		    device_xname(dev)));
    951 		sr->sr_size = 128;
    952 		sd.sd_chip = C46;
    953 	}
    954 
    955 	ecr &= ~(RTW_9346CR_EEDI | RTW_9346CR_EEDO | RTW_9346CR_EESK |
    956 	    RTW_9346CR_EEM_MASK | RTW_9346CR_EECS);
    957 	ecr |= RTW_9346CR_EEM_PROGRAM;
    958 
    959 	RTW_WRITE8(regs, RTW_9346CR, ecr);
    960 
    961 	sr->sr_content = malloc(sr->sr_size, M_DEVBUF, M_WAITOK | M_ZERO);
    962 
    963 	/* RTL8180 has a single 8-bit register for controlling the
    964 	 * 93cx6 SROM.  There is no "ready" bit. The RTL8180
    965 	 * input/output sense is the reverse of read_seeprom's.
    966 	 */
    967 	sd.sd_tag = regs->r_bt;
    968 	sd.sd_bsh = regs->r_bh;
    969 	sd.sd_regsize = 1;
    970 	sd.sd_control_offset = RTW_9346CR;
    971 	sd.sd_status_offset = RTW_9346CR;
    972 	sd.sd_dataout_offset = RTW_9346CR;
    973 	sd.sd_CK = RTW_9346CR_EESK;
    974 	sd.sd_CS = RTW_9346CR_EECS;
    975 	sd.sd_DI = RTW_9346CR_EEDO;
    976 	sd.sd_DO = RTW_9346CR_EEDI;
    977 	/* make read_seeprom enter EEPROM read/write mode */
    978 	sd.sd_MS = ecr;
    979 	sd.sd_RDY = 0;
    980 
    981 	/* TBD bus barriers */
    982 	if (!read_seeprom(&sd, sr->sr_content, 0, sr->sr_size/2)) {
    983 		aprint_error_dev(dev, "could not read SROM\n");
    984 		free(sr->sr_content, M_DEVBUF);
    985 		sr->sr_content = NULL;
    986 		return -1;	/* XXX */
    987 	}
    988 
    989 	/* end EEPROM read/write mode */
    990 	RTW_WRITE8(regs, RTW_9346CR,
    991 	    (ecr & ~RTW_9346CR_EEM_MASK) | RTW_9346CR_EEM_NORMAL);
    992 	RTW_WBRW(regs, RTW_9346CR, RTW_9346CR);
    993 
    994 	if ((rc = rtw_recall_eeprom(regs, dev)) != 0)
    995 		return rc;
    996 
    997 #ifdef RTW_DEBUG
    998 	{
    999 		int i;
   1000 		RTW_DPRINTF(RTW_DEBUG_ATTACH,
   1001 		    ("\n%s: serial ROM:\n\t", device_xname(dev)));
   1002 		for (i = 0; i < sr->sr_size/2; i++) {
   1003 			if (((i % 8) == 0) && (i != 0))
   1004 				RTW_DPRINTF(RTW_DEBUG_ATTACH, ("\n\t"));
   1005 			RTW_DPRINTF(RTW_DEBUG_ATTACH,
   1006 			    (" %04x", sr->sr_content[i]));
   1007 		}
   1008 		RTW_DPRINTF(RTW_DEBUG_ATTACH, ("\n"));
   1009 	}
   1010 #endif /* RTW_DEBUG */
   1011 	return 0;
   1012 }
   1013 
   1014 static void
   1015 rtw_set_rfprog(struct rtw_regs *regs, enum rtw_rfchipid rfchipid,
   1016     device_t dev)
   1017 {
   1018 	uint8_t cfg4;
   1019 	const char *method;
   1020 
   1021 	cfg4 = RTW_READ8(regs, RTW_CONFIG4) & ~RTW_CONFIG4_RFTYPE_MASK;
   1022 
   1023 	switch (rfchipid) {
   1024 	default:
   1025 		cfg4 |= __SHIFTIN(rtw_rfprog_fallback, RTW_CONFIG4_RFTYPE_MASK);
   1026 		method = "fallback";
   1027 		break;
   1028 	case RTW_RFCHIPID_INTERSIL:
   1029 		cfg4 |= RTW_CONFIG4_RFTYPE_INTERSIL;
   1030 		method = "Intersil";
   1031 		break;
   1032 	case RTW_RFCHIPID_PHILIPS:
   1033 		cfg4 |= RTW_CONFIG4_RFTYPE_PHILIPS;
   1034 		method = "Philips";
   1035 		break;
   1036 	case RTW_RFCHIPID_GCT:	/* XXX a guess */
   1037 	case RTW_RFCHIPID_RFMD:
   1038 		cfg4 |= RTW_CONFIG4_RFTYPE_RFMD;
   1039 		method = "RFMD";
   1040 		break;
   1041 	}
   1042 
   1043 	RTW_WRITE8(regs, RTW_CONFIG4, cfg4);
   1044 
   1045 	RTW_WBR(regs, RTW_CONFIG4, RTW_CONFIG4);
   1046 
   1047 #ifdef RTW_DEBUG
   1048 	RTW_DPRINTF(RTW_DEBUG_INIT,
   1049 	    ("%s: %s RF programming method, %#02x\n", device_xname(dev), method,
   1050 	    RTW_READ8(regs, RTW_CONFIG4)));
   1051 #else
   1052 	__USE(method);
   1053 #endif
   1054 }
   1055 
   1056 static inline void
   1057 rtw_init_channels(enum rtw_locale locale,
   1058     struct ieee80211_channel (*chans)[IEEE80211_CHAN_MAX+1], device_t dev)
   1059 {
   1060 	int i;
   1061 	const char *name = NULL;
   1062 #define ADD_CHANNEL(_chans, _chan) do {			\
   1063 	(*_chans)[_chan].ic_flags = IEEE80211_CHAN_B;		\
   1064 	(*_chans)[_chan].ic_freq =				\
   1065 	    ieee80211_ieee2mhz(_chan, (*_chans)[_chan].ic_flags);\
   1066 } while (0)
   1067 
   1068 	switch (locale) {
   1069 	case RTW_LOCALE_USA:	/* 1-11 */
   1070 		name = "USA";
   1071 		for (i = 1; i <= 11; i++)
   1072 			ADD_CHANNEL(chans, i);
   1073 		break;
   1074 	case RTW_LOCALE_JAPAN:	/* 1-14 */
   1075 		name = "Japan";
   1076 		ADD_CHANNEL(chans, 14);
   1077 		for (i = 1; i <= 14; i++)
   1078 			ADD_CHANNEL(chans, i);
   1079 		break;
   1080 	case RTW_LOCALE_EUROPE:	/* 1-13 */
   1081 		name = "Europe";
   1082 		for (i = 1; i <= 13; i++)
   1083 			ADD_CHANNEL(chans, i);
   1084 		break;
   1085 	default:			/* 10-11 allowed by most countries */
   1086 		name = "<unknown>";
   1087 		for (i = 10; i <= 11; i++)
   1088 			ADD_CHANNEL(chans, i);
   1089 		break;
   1090 	}
   1091 	aprint_normal_dev(dev, "Geographic Location %s\n", name);
   1092 #undef ADD_CHANNEL
   1093 }
   1094 
   1095 
   1096 static inline void
   1097 rtw_identify_country(struct rtw_regs *regs, enum rtw_locale *locale)
   1098 {
   1099 	uint8_t cfg0 = RTW_READ8(regs, RTW_CONFIG0);
   1100 
   1101 	switch (cfg0 & RTW_CONFIG0_GL_MASK) {
   1102 	case RTW_CONFIG0_GL_USA:
   1103 	case _RTW_CONFIG0_GL_USA:
   1104 		*locale = RTW_LOCALE_USA;
   1105 		break;
   1106 	case RTW_CONFIG0_GL_JAPAN:
   1107 		*locale = RTW_LOCALE_JAPAN;
   1108 		break;
   1109 	case RTW_CONFIG0_GL_EUROPE:
   1110 		*locale = RTW_LOCALE_EUROPE;
   1111 		break;
   1112 	default:
   1113 		*locale = RTW_LOCALE_UNKNOWN;
   1114 		break;
   1115 	}
   1116 }
   1117 
   1118 static inline int
   1119 rtw_identify_sta(struct rtw_regs *regs, uint8_t (*addr)[IEEE80211_ADDR_LEN],
   1120     device_t dev)
   1121 {
   1122 	static const uint8_t empty_macaddr[IEEE80211_ADDR_LEN] = {
   1123 		0x00, 0x00, 0x00, 0x00, 0x00, 0x00
   1124 	};
   1125 	uint32_t idr0 = RTW_READ(regs, RTW_IDR0),
   1126 		 idr1 = RTW_READ(regs, RTW_IDR1);
   1127 
   1128 	(*addr)[0] = __SHIFTOUT(idr0, __BITS(0,  7));
   1129 	(*addr)[1] = __SHIFTOUT(idr0, __BITS(8,  15));
   1130 	(*addr)[2] = __SHIFTOUT(idr0, __BITS(16, 23));
   1131 	(*addr)[3] = __SHIFTOUT(idr0, __BITS(24, 31));
   1132 
   1133 	(*addr)[4] = __SHIFTOUT(idr1, __BITS(0,  7));
   1134 	(*addr)[5] = __SHIFTOUT(idr1, __BITS(8, 15));
   1135 
   1136 	if (IEEE80211_ADDR_EQ(addr, empty_macaddr)) {
   1137 		aprint_error_dev(dev,
   1138 		    "could not get mac address, attach failed\n");
   1139 		return ENXIO;
   1140 	}
   1141 
   1142 	aprint_normal_dev(dev, "802.11 address %s\n", ether_sprintf(*addr));
   1143 
   1144 	return 0;
   1145 }
   1146 
   1147 static uint8_t
   1148 rtw_chan2txpower(struct rtw_srom *sr, struct ieee80211com *ic,
   1149     struct ieee80211_channel *chan)
   1150 {
   1151 	u_int idx = RTW_SR_TXPOWER1 + ieee80211_chan2ieee(ic, chan) - 1;
   1152 	KASSERT(idx >= RTW_SR_TXPOWER1 && idx <= RTW_SR_TXPOWER14);
   1153 	return RTW_SR_GET(sr, idx);
   1154 }
   1155 
   1156 static void
   1157 rtw_txdesc_blk_init_all(struct rtw_txdesc_blk *tdb)
   1158 {
   1159 	int pri;
   1160 	/* nfree: the number of free descriptors in each ring.
   1161 	 * The beacon ring is a special case: I do not let the
   1162 	 * driver use all of the descriptors on the beacon ring.
   1163 	 * The reasons are two-fold:
   1164 	 *
   1165 	 * (1) A BEACON descriptor's OWN bit is (apparently) not
   1166 	 * updated, so the driver cannot easily know if the descriptor
   1167 	 * belongs to it, or if it is racing the NIC.  If the NIC
   1168 	 * does not OWN every descriptor, then the driver can safely
   1169 	 * update the descriptors when RTW_TBDA points at tdb_next.
   1170 	 *
   1171 	 * (2) I hope that the NIC will process more than one BEACON
   1172 	 * descriptor in a single beacon interval, since that will
   1173 	 * enable multiple-BSS support.  Since the NIC does not
   1174 	 * clear the OWN bit, there is no natural place for it to
   1175 	 * stop processing BEACON desciptors.  Maybe it will *not*
   1176 	 * stop processing them!  I do not want to chance the NIC
   1177 	 * looping around and around a saturated beacon ring, so
   1178 	 * I will leave one descriptor unOWNed at all times.
   1179 	 */
   1180 	u_int nfree[RTW_NTXPRI] =
   1181 	    {RTW_NTXDESCLO, RTW_NTXDESCMD, RTW_NTXDESCHI,
   1182 	     RTW_NTXDESCBCN - 1};
   1183 
   1184 	for (pri = 0; pri < RTW_NTXPRI; pri++) {
   1185 		tdb[pri].tdb_nfree = nfree[pri];
   1186 		tdb[pri].tdb_next = 0;
   1187 	}
   1188 }
   1189 
   1190 static int
   1191 rtw_txsoft_blk_init(struct rtw_txsoft_blk *tsb)
   1192 {
   1193 	int i;
   1194 	struct rtw_txsoft *ts;
   1195 
   1196 	SIMPLEQ_INIT(&tsb->tsb_dirtyq);
   1197 	SIMPLEQ_INIT(&tsb->tsb_freeq);
   1198 	for (i = 0; i < tsb->tsb_ndesc; i++) {
   1199 		ts = &tsb->tsb_desc[i];
   1200 		ts->ts_mbuf = NULL;
   1201 		SIMPLEQ_INSERT_TAIL(&tsb->tsb_freeq, ts, ts_q);
   1202 	}
   1203 	tsb->tsb_tx_timer = 0;
   1204 	return 0;
   1205 }
   1206 
   1207 static void
   1208 rtw_txsoft_blk_init_all(struct rtw_txsoft_blk *tsb)
   1209 {
   1210 	int pri;
   1211 	for (pri = 0; pri < RTW_NTXPRI; pri++)
   1212 		rtw_txsoft_blk_init(&tsb[pri]);
   1213 }
   1214 
   1215 static inline void
   1216 rtw_rxdescs_sync(struct rtw_rxdesc_blk *rdb, int desc0, int nsync, int ops)
   1217 {
   1218 	KASSERT(nsync <= rdb->rdb_ndesc);
   1219 	/* sync to end of ring */
   1220 	if (desc0 + nsync > rdb->rdb_ndesc) {
   1221 		bus_dmamap_sync(rdb->rdb_dmat, rdb->rdb_dmamap,
   1222 		    offsetof(struct rtw_descs, hd_rx[desc0]),
   1223 		    sizeof(struct rtw_rxdesc) * (rdb->rdb_ndesc - desc0), ops);
   1224 		nsync -= (rdb->rdb_ndesc - desc0);
   1225 		desc0 = 0;
   1226 	}
   1227 
   1228 	KASSERT(desc0 < rdb->rdb_ndesc);
   1229 	KASSERT(nsync <= rdb->rdb_ndesc);
   1230 	KASSERT(desc0 + nsync <= rdb->rdb_ndesc);
   1231 
   1232 	/* sync what remains */
   1233 	bus_dmamap_sync(rdb->rdb_dmat, rdb->rdb_dmamap,
   1234 	    offsetof(struct rtw_descs, hd_rx[desc0]),
   1235 	    sizeof(struct rtw_rxdesc) * nsync, ops);
   1236 }
   1237 
   1238 static void
   1239 rtw_txdescs_sync(struct rtw_txdesc_blk *tdb, u_int desc0, u_int nsync, int ops)
   1240 {
   1241 	/* sync to end of ring */
   1242 	if (desc0 + nsync > tdb->tdb_ndesc) {
   1243 		bus_dmamap_sync(tdb->tdb_dmat, tdb->tdb_dmamap,
   1244 		    tdb->tdb_ofs + sizeof(struct rtw_txdesc) * desc0,
   1245 		    sizeof(struct rtw_txdesc) * (tdb->tdb_ndesc - desc0),
   1246 		    ops);
   1247 		nsync -= (tdb->tdb_ndesc - desc0);
   1248 		desc0 = 0;
   1249 	}
   1250 
   1251 	/* sync what remains */
   1252 	bus_dmamap_sync(tdb->tdb_dmat, tdb->tdb_dmamap,
   1253 	    tdb->tdb_ofs + sizeof(struct rtw_txdesc) * desc0,
   1254 	    sizeof(struct rtw_txdesc) * nsync, ops);
   1255 }
   1256 
   1257 static void
   1258 rtw_txdescs_sync_all(struct rtw_txdesc_blk *tdb)
   1259 {
   1260 	int pri;
   1261 	for (pri = 0; pri < RTW_NTXPRI; pri++) {
   1262 		rtw_txdescs_sync(&tdb[pri], 0, tdb[pri].tdb_ndesc,
   1263 		    BUS_DMASYNC_PREREAD | BUS_DMASYNC_PREWRITE);
   1264 	}
   1265 }
   1266 
   1267 static void
   1268 rtw_rxbufs_release(bus_dma_tag_t dmat, struct rtw_rxsoft *desc)
   1269 {
   1270 	int i;
   1271 	struct rtw_rxsoft *rs;
   1272 
   1273 	for (i = 0; i < RTW_RXQLEN; i++) {
   1274 		rs = &desc[i];
   1275 		if (rs->rs_mbuf == NULL)
   1276 			continue;
   1277 		bus_dmamap_sync(dmat, rs->rs_dmamap, 0,
   1278 		    rs->rs_dmamap->dm_mapsize, BUS_DMASYNC_POSTREAD);
   1279 		bus_dmamap_unload(dmat, rs->rs_dmamap);
   1280 		m_freem(rs->rs_mbuf);
   1281 		rs->rs_mbuf = NULL;
   1282 	}
   1283 }
   1284 
   1285 static inline int
   1286 rtw_rxsoft_alloc(bus_dma_tag_t dmat, struct rtw_rxsoft *rs)
   1287 {
   1288 	int rc;
   1289 	struct mbuf *m;
   1290 
   1291 	MGETHDR(m, M_DONTWAIT, MT_DATA);
   1292 	if (m == NULL)
   1293 		return ENOBUFS;
   1294 
   1295 	MCLGET(m, M_DONTWAIT);
   1296 	if ((m->m_flags & M_EXT) == 0) {
   1297 		m_freem(m);
   1298 		return ENOBUFS;
   1299 	}
   1300 
   1301 	m->m_pkthdr.len = m->m_len = m->m_ext.ext_size;
   1302 
   1303 	if (rs->rs_mbuf != NULL)
   1304 		bus_dmamap_unload(dmat, rs->rs_dmamap);
   1305 
   1306 	rs->rs_mbuf = NULL;
   1307 
   1308 	rc = bus_dmamap_load_mbuf(dmat, rs->rs_dmamap, m, BUS_DMA_NOWAIT);
   1309 	if (rc != 0) {
   1310 		m_freem(m);
   1311 		return -1;
   1312 	}
   1313 
   1314 	rs->rs_mbuf = m;
   1315 
   1316 	return 0;
   1317 }
   1318 
   1319 static int
   1320 rtw_rxsoft_init_all(bus_dma_tag_t dmat, struct rtw_rxsoft *desc,
   1321     int *ndesc, device_t dev)
   1322 {
   1323 	int i, rc = 0;
   1324 	struct rtw_rxsoft *rs;
   1325 
   1326 	for (i = 0; i < RTW_RXQLEN; i++) {
   1327 		rs = &desc[i];
   1328 		/* we're in rtw_init, so there should be no mbufs allocated */
   1329 		KASSERT(rs->rs_mbuf == NULL);
   1330 #ifdef RTW_DEBUG
   1331 		if (i == rtw_rxbufs_limit) {
   1332 			aprint_error_dev(dev, "TEST hit %d-buffer limit\n", i);
   1333 			rc = ENOBUFS;
   1334 			break;
   1335 		}
   1336 #endif /* RTW_DEBUG */
   1337 		if ((rc = rtw_rxsoft_alloc(dmat, rs)) != 0) {
   1338 			aprint_error_dev(dev,
   1339 			    "rtw_rxsoft_alloc failed, %d buffers, rc %d\n",
   1340 			    i, rc);
   1341 			break;
   1342 		}
   1343 	}
   1344 	*ndesc = i;
   1345 	return rc;
   1346 }
   1347 
   1348 static inline void
   1349 rtw_rxdesc_init(struct rtw_rxdesc_blk *rdb, struct rtw_rxsoft *rs,
   1350     int idx, int kick)
   1351 {
   1352 	int is_last = (idx == rdb->rdb_ndesc - 1);
   1353 	uint32_t ctl, octl, obuf;
   1354 	struct rtw_rxdesc *rd = &rdb->rdb_desc[idx];
   1355 
   1356 	/* sync the mbuf before the descriptor */
   1357 	bus_dmamap_sync(rdb->rdb_dmat, rs->rs_dmamap, 0,
   1358 	    rs->rs_dmamap->dm_mapsize, BUS_DMASYNC_PREREAD);
   1359 
   1360 	obuf = rd->rd_buf;
   1361 	rd->rd_buf = htole32(rs->rs_dmamap->dm_segs[0].ds_addr);
   1362 
   1363 	ctl = __SHIFTIN(rs->rs_mbuf->m_len, RTW_RXCTL_LENGTH_MASK) |
   1364 	    RTW_RXCTL_OWN | RTW_RXCTL_FS | RTW_RXCTL_LS;
   1365 
   1366 	if (is_last)
   1367 		ctl |= RTW_RXCTL_EOR;
   1368 
   1369 	octl = rd->rd_ctl;
   1370 	rd->rd_ctl = htole32(ctl);
   1371 
   1372 #ifdef RTW_DEBUG
   1373 	RTW_DPRINTF(
   1374 	    kick ? (RTW_DEBUG_RECV_DESC | RTW_DEBUG_IO_KICK)
   1375 		 : RTW_DEBUG_RECV_DESC,
   1376 	    ("%s: rd %p buf %08x -> %08x ctl %08x -> %08x\n", __func__, rd,
   1377 	     le32toh(obuf), le32toh(rd->rd_buf), le32toh(octl),
   1378 	     le32toh(rd->rd_ctl)));
   1379 #else
   1380 	__USE(octl);
   1381 	__USE(obuf);
   1382 #endif
   1383 
   1384 	/* sync the descriptor */
   1385 	bus_dmamap_sync(rdb->rdb_dmat, rdb->rdb_dmamap,
   1386 	    RTW_DESC_OFFSET(hd_rx, idx), sizeof(struct rtw_rxdesc),
   1387 	    BUS_DMASYNC_PREREAD | BUS_DMASYNC_PREWRITE);
   1388 }
   1389 
   1390 static void
   1391 rtw_rxdesc_init_all(struct rtw_rxdesc_blk *rdb, struct rtw_rxsoft *ctl, int kick)
   1392 {
   1393 	int i;
   1394 	struct rtw_rxsoft *rs;
   1395 
   1396 	for (i = 0; i < rdb->rdb_ndesc; i++) {
   1397 		rs = &ctl[i];
   1398 		rtw_rxdesc_init(rdb, rs, i, kick);
   1399 	}
   1400 }
   1401 
   1402 static void
   1403 rtw_io_enable(struct rtw_softc *sc, uint8_t flags, int enable)
   1404 {
   1405 	struct rtw_regs *regs = &sc->sc_regs;
   1406 	uint8_t cr;
   1407 
   1408 	RTW_DPRINTF(RTW_DEBUG_IOSTATE, ("%s: %s 0x%02x\n", __func__,
   1409 	    enable ? "enable" : "disable", flags));
   1410 
   1411 	cr = RTW_READ8(regs, RTW_CR);
   1412 
   1413 	/* XXX reference source does not enable MULRW */
   1414 	/* enable PCI Read/Write Multiple */
   1415 	cr |= RTW_CR_MULRW;
   1416 
   1417 	/* The receive engine will always start at RDSAR.  */
   1418 	if (enable && (flags & ~cr & RTW_CR_RE)) {
   1419 		struct rtw_rxdesc_blk *rdb;
   1420 		rdb = &sc->sc_rxdesc_blk;
   1421 		rdb->rdb_next = 0;
   1422 	}
   1423 
   1424 	RTW_RBW(regs, RTW_CR, RTW_CR);	/* XXX paranoia? */
   1425 	if (enable)
   1426 		cr |= flags;
   1427 	else
   1428 		cr &= ~flags;
   1429 	RTW_WRITE8(regs, RTW_CR, cr);
   1430 	RTW_SYNC(regs, RTW_CR, RTW_CR);
   1431 
   1432 #ifdef RTW_DIAG
   1433 	if (cr & RTW_CR_TE)
   1434 		rtw_txring_fixup(sc, __func__, __LINE__);
   1435 #endif
   1436 	if (cr & RTW_CR_TE) {
   1437 		rtw_tx_kick(&sc->sc_regs,
   1438 		    RTW_TPPOLL_HPQ | RTW_TPPOLL_NPQ | RTW_TPPOLL_LPQ);
   1439 	}
   1440 }
   1441 
   1442 static void
   1443 rtw_intr_rx(struct rtw_softc *sc, uint16_t isr)
   1444 {
   1445 #define	IS_BEACON(__fc0)						\
   1446     ((__fc0 & (IEEE80211_FC0_TYPE_MASK | IEEE80211_FC0_SUBTYPE_MASK)) ==\
   1447      (IEEE80211_FC0_TYPE_MGT | IEEE80211_FC0_SUBTYPE_BEACON))
   1448 
   1449 	static const int ratetbl[4] = {2, 4, 11, 22};	/* convert rates:
   1450 							 * hardware -> net80211
   1451 							 */
   1452 	u_int next, nproc = 0;
   1453 	int hwrate, len, rate, rssi, sq, s;
   1454 	uint32_t hrssi, hstat, htsfth, htsftl;
   1455 	struct rtw_rxdesc *rd;
   1456 	struct rtw_rxsoft *rs;
   1457 	struct rtw_rxdesc_blk *rdb;
   1458 	struct mbuf *m;
   1459 	struct ifnet *ifp = &sc->sc_if;
   1460 
   1461 	struct ieee80211_node *ni;
   1462 	struct ieee80211_frame_min *wh;
   1463 
   1464 	rdb = &sc->sc_rxdesc_blk;
   1465 
   1466 	for (next = rdb->rdb_next; ; next = rdb->rdb_next) {
   1467 		KASSERT(next < rdb->rdb_ndesc);
   1468 
   1469 		rtw_rxdescs_sync(rdb, next, 1,
   1470 		    BUS_DMASYNC_POSTREAD | BUS_DMASYNC_POSTWRITE);
   1471 		rd = &rdb->rdb_desc[next];
   1472 		rs = &sc->sc_rxsoft[next];
   1473 
   1474 		hstat = le32toh(rd->rd_stat);
   1475 		hrssi = le32toh(rd->rd_rssi);
   1476 		htsfth = le32toh(rd->rd_tsfth);
   1477 		htsftl = le32toh(rd->rd_tsftl);
   1478 
   1479 		RTW_DPRINTF(RTW_DEBUG_RECV_DESC,
   1480 		    ("%s: rxdesc[%d] hstat %08x hrssi %08x htsft %08x%08x\n",
   1481 		    __func__, next, hstat, hrssi, htsfth, htsftl));
   1482 
   1483 		++nproc;
   1484 
   1485 		/* still belongs to NIC */
   1486 		if ((hstat & RTW_RXSTAT_OWN) != 0) {
   1487 			rtw_rxdescs_sync(rdb, next, 1, BUS_DMASYNC_PREREAD);
   1488 			break;
   1489 		}
   1490 
   1491 		/* ieee80211_input() might reset the receive engine
   1492 		 * (e.g. by indirectly calling rtw_tune()), so save
   1493 		 * the next pointer here and retrieve it again on
   1494 		 * the next round.
   1495 		 */
   1496 		rdb->rdb_next = (next + 1) % rdb->rdb_ndesc;
   1497 
   1498 #ifdef RTW_DEBUG
   1499 #define PRINTSTAT(flag) do { \
   1500 	if ((hstat & flag) != 0) { \
   1501 		printf("%s" #flag, delim); \
   1502 		delim = ","; \
   1503 	} \
   1504 } while (0)
   1505 		if ((rtw_debug & RTW_DEBUG_RECV_DESC) != 0) {
   1506 			const char *delim = "<";
   1507 			printf("%s: ", device_xname(sc->sc_dev));
   1508 			if ((hstat & RTW_RXSTAT_DEBUG) != 0) {
   1509 				printf("status %08x", hstat);
   1510 				PRINTSTAT(RTW_RXSTAT_SPLCP);
   1511 				PRINTSTAT(RTW_RXSTAT_MAR);
   1512 				PRINTSTAT(RTW_RXSTAT_PAR);
   1513 				PRINTSTAT(RTW_RXSTAT_BAR);
   1514 				PRINTSTAT(RTW_RXSTAT_PWRMGT);
   1515 				PRINTSTAT(RTW_RXSTAT_CRC32);
   1516 				PRINTSTAT(RTW_RXSTAT_ICV);
   1517 				printf(">, ");
   1518 			}
   1519 		}
   1520 #endif /* RTW_DEBUG */
   1521 
   1522 		if ((hstat & RTW_RXSTAT_IOERROR) != 0) {
   1523 			aprint_error_dev(sc->sc_dev,
   1524 			    "DMA error/FIFO overflow %08" PRIx32 ", "
   1525 			    "rx descriptor %d\n", hstat, next);
   1526 			ifp->if_ierrors++;
   1527 			goto next;
   1528 		}
   1529 
   1530 		len = __SHIFTOUT(hstat, RTW_RXSTAT_LENGTH_MASK);
   1531 		if (len < IEEE80211_MIN_LEN) {
   1532 			sc->sc_ic.ic_stats.is_rx_tooshort++;
   1533 			goto next;
   1534 		}
   1535 		if (len > rs->rs_mbuf->m_len) {
   1536 			aprint_error_dev(sc->sc_dev,
   1537 			    "rx frame too long, %d > %d, %08" PRIx32
   1538 			    ", desc %d\n",
   1539 			    len, rs->rs_mbuf->m_len, hstat, next);
   1540 			ifp->if_ierrors++;
   1541 			goto next;
   1542 		}
   1543 
   1544 		hwrate = __SHIFTOUT(hstat, RTW_RXSTAT_RATE_MASK);
   1545 		if (hwrate >= __arraycount(ratetbl)) {
   1546 			aprint_error_dev(sc->sc_dev,
   1547 			    "unknown rate #%" __PRIuBITS "\n",
   1548 			    __SHIFTOUT(hstat, RTW_RXSTAT_RATE_MASK));
   1549 			ifp->if_ierrors++;
   1550 			goto next;
   1551 		}
   1552 		rate = ratetbl[hwrate];
   1553 
   1554 #ifdef RTW_DEBUG
   1555 		RTW_DPRINTF(RTW_DEBUG_RECV_DESC,
   1556 		    ("rate %d.%d Mb/s, time %08x%08x\n", (rate * 5) / 10,
   1557 		     (rate * 5) % 10, htsfth, htsftl));
   1558 #endif /* RTW_DEBUG */
   1559 
   1560 		/* if bad flags, skip descriptor */
   1561 		if ((hstat & RTW_RXSTAT_ONESEG) != RTW_RXSTAT_ONESEG) {
   1562 			aprint_error_dev(sc->sc_dev, "too many rx segments, "
   1563 			    "next=%d, %08" PRIx32 "\n", next, hstat);
   1564 			goto next;
   1565 		}
   1566 
   1567 		bus_dmamap_sync(sc->sc_dmat, rs->rs_dmamap, 0,
   1568 		    rs->rs_dmamap->dm_mapsize, BUS_DMASYNC_POSTREAD);
   1569 
   1570 		m = rs->rs_mbuf;
   1571 
   1572 		/* if temporarily out of memory, re-use mbuf */
   1573 		switch (rtw_rxsoft_alloc(sc->sc_dmat, rs)) {
   1574 		case 0:
   1575 			break;
   1576 		case ENOBUFS:
   1577 			aprint_error_dev(sc->sc_dev,
   1578 			    "rtw_rxsoft_alloc(, %d) failed, dropping packet\n",
   1579 			    next);
   1580 			goto next;
   1581 		default:
   1582 			/* XXX shorten rx ring, instead? */
   1583 			aprint_error_dev(sc->sc_dev,
   1584 			    "could not load DMA map\n");
   1585 		}
   1586 
   1587 		sq = __SHIFTOUT(hrssi, RTW_RXRSSI_SQ);
   1588 
   1589 		if (sc->sc_rfchipid == RTW_RFCHIPID_PHILIPS)
   1590 			rssi = UINT8_MAX - sq;
   1591 		else {
   1592 			rssi = __SHIFTOUT(hrssi, RTW_RXRSSI_IMR_RSSI);
   1593 			/* TBD find out each front-end's LNA gain in the
   1594 			 * front-end's units
   1595 			 */
   1596 			if ((hrssi & RTW_RXRSSI_IMR_LNA) == 0)
   1597 				rssi |= 0x80;
   1598 		}
   1599 
   1600 		/* Note well: now we cannot recycle the rs_mbuf unless
   1601 		 * we restore its original length.
   1602 		 */
   1603 		m_set_rcvif(m, ifp);
   1604 		m->m_pkthdr.len = m->m_len = len;
   1605 
   1606 		wh = mtod(m, struct ieee80211_frame_min *);
   1607 
   1608 		s = splnet();
   1609 
   1610 		if (!IS_BEACON(wh->i_fc[0]))
   1611 			sc->sc_led_state.ls_event |= RTW_LED_S_RX;
   1612 
   1613 		sc->sc_tsfth = htsfth;
   1614 
   1615 #ifdef RTW_DEBUG
   1616 		if ((ifp->if_flags & (IFF_DEBUG | IFF_LINK2)) ==
   1617 		    (IFF_DEBUG | IFF_LINK2)) {
   1618 			ieee80211_dump_pkt(mtod(m, uint8_t *), m->m_pkthdr.len,
   1619 			    rate, rssi);
   1620 		}
   1621 #endif /* RTW_DEBUG */
   1622 
   1623 		if (sc->sc_radiobpf != NULL) {
   1624 			struct rtw_rx_radiotap_header *rr = &sc->sc_rxtap;
   1625 
   1626 			rr->rr_tsft =
   1627 			    htole64(((uint64_t)htsfth << 32) | htsftl);
   1628 
   1629 			rr->rr_flags = IEEE80211_RADIOTAP_F_FCS;
   1630 
   1631 			if ((hstat & RTW_RXSTAT_SPLCP) != 0)
   1632 				rr->rr_flags |= IEEE80211_RADIOTAP_F_SHORTPRE;
   1633 			if ((hstat & RTW_RXSTAT_CRC32) != 0)
   1634 				rr->rr_flags |= IEEE80211_RADIOTAP_F_BADFCS;
   1635 
   1636 			rr->rr_rate = rate;
   1637 
   1638 			if (sc->sc_rfchipid == RTW_RFCHIPID_PHILIPS)
   1639 				rr->rr_u.u_philips.p_antsignal = rssi;
   1640 			else {
   1641 				rr->rr_u.u_other.o_antsignal = rssi;
   1642 				rr->rr_u.u_other.o_barker_lock =
   1643 				    htole16(UINT8_MAX - sq);
   1644 			}
   1645 
   1646 			bpf_mtap2(sc->sc_radiobpf,
   1647 			    rr, sizeof(sc->sc_rxtapu), m, BPF_D_IN);
   1648 		}
   1649 
   1650 		if ((hstat & RTW_RXSTAT_RES) != 0) {
   1651 			m_freem(m);
   1652 			splx(s);
   1653 			goto next;
   1654 		}
   1655 
   1656 		/* CRC is included with the packet; trim it off. */
   1657 		m_adj(m, -IEEE80211_CRC_LEN);
   1658 
   1659 		/* TBD use _MAR, _BAR, _PAR flags as hints to _find_rxnode? */
   1660 		ni = ieee80211_find_rxnode(&sc->sc_ic, wh);
   1661 		ieee80211_input(&sc->sc_ic, m, ni, rssi, htsftl);
   1662 		ieee80211_free_node(ni);
   1663 		splx(s);
   1664 next:
   1665 		rtw_rxdesc_init(rdb, rs, next, 0);
   1666 	}
   1667 #undef IS_BEACON
   1668 }
   1669 
   1670 static void
   1671 rtw_txsoft_release(bus_dma_tag_t dmat, struct ieee80211com *ic,
   1672     struct rtw_txsoft *ts)
   1673 {
   1674 	struct mbuf *m;
   1675 	struct ieee80211_node *ni;
   1676 
   1677 	m = ts->ts_mbuf;
   1678 	ni = ts->ts_ni;
   1679 	KASSERT(m != NULL);
   1680 	KASSERT(ni != NULL);
   1681 	ts->ts_mbuf = NULL;
   1682 	ts->ts_ni = NULL;
   1683 
   1684 	bus_dmamap_sync(dmat, ts->ts_dmamap, 0, ts->ts_dmamap->dm_mapsize,
   1685 	    BUS_DMASYNC_POSTWRITE);
   1686 	bus_dmamap_unload(dmat, ts->ts_dmamap);
   1687 	m_freem(m);
   1688 	ieee80211_free_node(ni);
   1689 }
   1690 
   1691 static void
   1692 rtw_txsofts_release(bus_dma_tag_t dmat, struct ieee80211com *ic,
   1693     struct rtw_txsoft_blk *tsb)
   1694 {
   1695 	struct rtw_txsoft *ts;
   1696 
   1697 	while ((ts = SIMPLEQ_FIRST(&tsb->tsb_dirtyq)) != NULL) {
   1698 		rtw_txsoft_release(dmat, ic, ts);
   1699 		SIMPLEQ_REMOVE_HEAD(&tsb->tsb_dirtyq, ts_q);
   1700 		SIMPLEQ_INSERT_TAIL(&tsb->tsb_freeq, ts, ts_q);
   1701 	}
   1702 	tsb->tsb_tx_timer = 0;
   1703 }
   1704 
   1705 static inline void
   1706 rtw_collect_txpkt(struct rtw_softc *sc, struct rtw_txdesc_blk *tdb,
   1707     struct rtw_txsoft *ts, int ndesc)
   1708 {
   1709 	uint32_t hstat;
   1710 	int data_retry, rts_retry;
   1711 	struct rtw_txdesc *tdn;
   1712 	const char *condstring;
   1713 	struct ifnet *ifp = &sc->sc_if;
   1714 
   1715 	rtw_txsoft_release(sc->sc_dmat, &sc->sc_ic, ts);
   1716 
   1717 	tdb->tdb_nfree += ndesc;
   1718 
   1719 	tdn = &tdb->tdb_desc[ts->ts_last];
   1720 
   1721 	hstat = le32toh(tdn->td_stat);
   1722 	rts_retry = __SHIFTOUT(hstat, RTW_TXSTAT_RTSRETRY_MASK);
   1723 	data_retry = __SHIFTOUT(hstat, RTW_TXSTAT_DRC_MASK);
   1724 
   1725 	ifp->if_collisions += rts_retry + data_retry;
   1726 
   1727 	if ((hstat & RTW_TXSTAT_TOK) != 0)
   1728 		condstring = "ok";
   1729 	else {
   1730 		ifp->if_oerrors++;
   1731 		condstring = "error";
   1732 	}
   1733 
   1734 #ifdef RTW_DEBUG
   1735 	DPRINTF(sc, RTW_DEBUG_XMIT_DESC,
   1736 	    ("%s: ts %p txdesc[%d, %d] %s tries rts %u data %u\n",
   1737 	    device_xname(sc->sc_dev), ts, ts->ts_first, ts->ts_last,
   1738 	    condstring, rts_retry, data_retry));
   1739 #else
   1740 	__USE(condstring);
   1741 #endif
   1742 }
   1743 
   1744 static void
   1745 rtw_reset_oactive(struct rtw_softc *sc)
   1746 {
   1747 	short oflags;
   1748 	int pri;
   1749 	struct rtw_txsoft_blk *tsb;
   1750 	struct rtw_txdesc_blk *tdb;
   1751 	oflags = sc->sc_if.if_flags;
   1752 	for (pri = 0; pri < RTW_NTXPRI; pri++) {
   1753 		tsb = &sc->sc_txsoft_blk[pri];
   1754 		tdb = &sc->sc_txdesc_blk[pri];
   1755 		if (!SIMPLEQ_EMPTY(&tsb->tsb_freeq) && tdb->tdb_nfree > 0)
   1756 			sc->sc_if.if_flags &= ~IFF_OACTIVE;
   1757 	}
   1758 	if (oflags != sc->sc_if.if_flags) {
   1759 		DPRINTF(sc, RTW_DEBUG_OACTIVE,
   1760 		    ("%s: reset OACTIVE\n", __func__));
   1761 	}
   1762 }
   1763 
   1764 /* Collect transmitted packets. */
   1765 static bool
   1766 rtw_collect_txring(struct rtw_softc *sc, struct rtw_txsoft_blk *tsb,
   1767     struct rtw_txdesc_blk *tdb, int force)
   1768 {
   1769 	bool collected = false;
   1770 	int ndesc;
   1771 	struct rtw_txsoft *ts;
   1772 
   1773 #ifdef RTW_DEBUG
   1774 	rtw_dump_rings(sc);
   1775 #endif
   1776 
   1777 	while ((ts = SIMPLEQ_FIRST(&tsb->tsb_dirtyq)) != NULL) {
   1778 		/* If we're clearing a failed transmission, only clear
   1779 		   up to the last packet the hardware has processed.  */
   1780 		if (ts->ts_first == rtw_txring_next(&sc->sc_regs, tdb))
   1781 			break;
   1782 
   1783 		ndesc = 1 + ts->ts_last - ts->ts_first;
   1784 		if (ts->ts_last < ts->ts_first)
   1785 			ndesc += tdb->tdb_ndesc;
   1786 
   1787 		KASSERT(ndesc > 0);
   1788 
   1789 		rtw_txdescs_sync(tdb, ts->ts_first, ndesc,
   1790 		    BUS_DMASYNC_POSTREAD | BUS_DMASYNC_POSTWRITE);
   1791 
   1792 		if (force) {
   1793 			int next;
   1794 #ifdef RTW_DIAG
   1795 			printf("%s: clearing packet, stats", __func__);
   1796 #endif
   1797 			for (next = ts->ts_first; ;
   1798 			    next = RTW_NEXT_IDX(tdb, next)) {
   1799 #ifdef RTW_DIAG
   1800 				printf(" %" PRIx32 "/%" PRIx32 "/%" PRIx32 "/%" PRIu32 "/%" PRIx32, le32toh(tdb->tdb_desc[next].td_stat), le32toh(tdb->tdb_desc[next].td_ctl1), le32toh(tdb->tdb_desc[next].td_buf), le32toh(tdb->tdb_desc[next].td_len), le32toh(tdb->tdb_desc[next].td_next));
   1801 #endif
   1802 				tdb->tdb_desc[next].td_stat &=
   1803 				    ~htole32(RTW_TXSTAT_OWN);
   1804 				if (next == ts->ts_last)
   1805 					break;
   1806 			}
   1807 			rtw_txdescs_sync(tdb, ts->ts_first, ndesc,
   1808 			    BUS_DMASYNC_PREREAD | BUS_DMASYNC_PREWRITE);
   1809 #ifdef RTW_DIAG
   1810 			next = RTW_NEXT_IDX(tdb, next);
   1811 			printf(" -> end %u stat %" PRIx32 ", was %u\n", next,
   1812 			    le32toh(tdb->tdb_desc[next].td_stat),
   1813 			    rtw_txring_next(&sc->sc_regs, tdb));
   1814 #endif
   1815 		} else if ((tdb->tdb_desc[ts->ts_last].td_stat &
   1816 		    htole32(RTW_TXSTAT_OWN)) != 0) {
   1817 			rtw_txdescs_sync(tdb, ts->ts_last, 1,
   1818 			    BUS_DMASYNC_PREREAD);
   1819 			break;
   1820 		}
   1821 
   1822 		collected = true;
   1823 
   1824 		rtw_collect_txpkt(sc, tdb, ts, ndesc);
   1825 		SIMPLEQ_REMOVE_HEAD(&tsb->tsb_dirtyq, ts_q);
   1826 		SIMPLEQ_INSERT_TAIL(&tsb->tsb_freeq, ts, ts_q);
   1827 	}
   1828 
   1829 	/* no more pending transmissions, cancel watchdog */
   1830 	if (ts == NULL)
   1831 		tsb->tsb_tx_timer = 0;
   1832 	rtw_reset_oactive(sc);
   1833 
   1834 	return collected;
   1835 }
   1836 
   1837 static void
   1838 rtw_intr_tx(struct rtw_softc *sc, uint16_t isr)
   1839 {
   1840 	int pri, s;
   1841 	struct rtw_txsoft_blk	*tsb;
   1842 	struct rtw_txdesc_blk	*tdb;
   1843 	struct ifnet *ifp = &sc->sc_if;
   1844 
   1845 	s = splnet();
   1846 
   1847 	for (pri = 0; pri < RTW_NTXPRI; pri++) {
   1848 		tsb = &sc->sc_txsoft_blk[pri];
   1849 		tdb = &sc->sc_txdesc_blk[pri];
   1850 		rtw_collect_txring(sc, tsb, tdb, 0);
   1851 	}
   1852 
   1853 	if ((isr & RTW_INTR_TX) != 0)
   1854 		rtw_start(ifp); /* in softint */
   1855 
   1856 	splx(s);
   1857 }
   1858 
   1859 static void
   1860 rtw_intr_beacon(struct rtw_softc *sc, uint16_t isr)
   1861 {
   1862 	u_int next;
   1863 	uint32_t tsfth, tsftl;
   1864 	struct ieee80211com *ic;
   1865 	struct rtw_txdesc_blk *tdb = &sc->sc_txdesc_blk[RTW_TXPRIBCN];
   1866 	struct rtw_txsoft_blk *tsb = &sc->sc_txsoft_blk[RTW_TXPRIBCN];
   1867 	struct mbuf *m;
   1868 	int s;
   1869 
   1870 	s = splnet();
   1871 
   1872 	tsfth = RTW_READ(&sc->sc_regs, RTW_TSFTRH);
   1873 	tsftl = RTW_READ(&sc->sc_regs, RTW_TSFTRL);
   1874 
   1875 	if ((isr & (RTW_INTR_TBDOK | RTW_INTR_TBDER)) != 0) {
   1876 		next = rtw_txring_next(&sc->sc_regs, tdb);
   1877 #ifdef RTW_DEBUG
   1878 		RTW_DPRINTF(RTW_DEBUG_BEACON,
   1879 		    ("%s: beacon ring %sprocessed, isr = %#04" PRIx16
   1880 		     ", next %u expected %u, %" PRIu64 "\n", __func__,
   1881 		     (next == tdb->tdb_next) ? "" : "un", isr, next,
   1882 		     tdb->tdb_next, (uint64_t)tsfth << 32 | tsftl));
   1883 #else
   1884 		__USE(next);
   1885 		__USE(tsfth);
   1886 		__USE(tsftl);
   1887 #endif
   1888 		if ((RTW_READ8(&sc->sc_regs, RTW_TPPOLL) & RTW_TPPOLL_BQ) == 0)
   1889 			rtw_collect_txring(sc, tsb, tdb, 1);
   1890 	}
   1891 	/* Start beacon transmission. */
   1892 
   1893 	if ((isr & RTW_INTR_BCNINT) != 0 &&
   1894 	    sc->sc_ic.ic_state == IEEE80211_S_RUN &&
   1895 	    SIMPLEQ_EMPTY(&tsb->tsb_dirtyq)) {
   1896 		RTW_DPRINTF(RTW_DEBUG_BEACON,
   1897 		    ("%s: beacon prep. time, isr = %#04" PRIx16
   1898 		     ", %16" PRIu64 "\n", __func__, isr,
   1899 		     (uint64_t)tsfth << 32 | tsftl));
   1900 		ic = &sc->sc_ic;
   1901 		m = rtw_beacon_alloc(sc, ic->ic_bss);
   1902 
   1903 		if (m == NULL) {
   1904 			aprint_error_dev(sc->sc_dev,
   1905 			    "could not allocate beacon\n");
   1906 			splx(s);
   1907 			return;
   1908 		}
   1909 		M_SETCTX(m, ieee80211_ref_node(ic->ic_bss));
   1910 		IF_ENQUEUE(&sc->sc_beaconq, m);
   1911 		rtw_start(&sc->sc_if); /* in softint */
   1912 	}
   1913 
   1914 	splx(s);
   1915 }
   1916 
   1917 static void
   1918 rtw_intr_atim(struct rtw_softc *sc)
   1919 {
   1920 	/* TBD */
   1921 	return;
   1922 }
   1923 
   1924 #ifdef RTW_DEBUG
   1925 static void
   1926 rtw_dump_rings(struct rtw_softc *sc)
   1927 {
   1928 	struct rtw_txdesc_blk *tdb;
   1929 	struct rtw_rxdesc *rd;
   1930 	struct rtw_rxdesc_blk *rdb;
   1931 	int desc, pri;
   1932 
   1933 	if ((rtw_debug & RTW_DEBUG_IO_KICK) == 0)
   1934 		return;
   1935 
   1936 	for (pri = 0; pri < RTW_NTXPRI; pri++) {
   1937 		tdb = &sc->sc_txdesc_blk[pri];
   1938 		printf("%s: txpri %d ndesc %d nfree %d\n", __func__, pri,
   1939 		    tdb->tdb_ndesc, tdb->tdb_nfree);
   1940 		for (desc = 0; desc < tdb->tdb_ndesc; desc++)
   1941 			rtw_print_txdesc(sc, ".", NULL, tdb, desc);
   1942 	}
   1943 
   1944 	rdb = &sc->sc_rxdesc_blk;
   1945 
   1946 	for (desc = 0; desc < RTW_RXQLEN; desc++) {
   1947 		rd = &rdb->rdb_desc[desc];
   1948 		printf("%s: %sctl %08x rsvd0/rssi %08x buf/tsftl %08x "
   1949 		    "rsvd1/tsfth %08x\n", __func__,
   1950 		    (desc >= rdb->rdb_ndesc) ? "UNUSED " : "",
   1951 		    le32toh(rd->rd_ctl), le32toh(rd->rd_rssi),
   1952 		    le32toh(rd->rd_buf), le32toh(rd->rd_tsfth));
   1953 	}
   1954 }
   1955 #endif /* RTW_DEBUG */
   1956 
   1957 static void
   1958 rtw_hwring_setup(struct rtw_softc *sc)
   1959 {
   1960 	int pri;
   1961 	struct rtw_regs *regs = &sc->sc_regs;
   1962 	struct rtw_txdesc_blk *tdb;
   1963 
   1964 	sc->sc_txdesc_blk[RTW_TXPRILO].tdb_basereg = RTW_TLPDA;
   1965 	sc->sc_txdesc_blk[RTW_TXPRILO].tdb_base = RTW_RING_BASE(sc, hd_txlo);
   1966 	sc->sc_txdesc_blk[RTW_TXPRIMD].tdb_basereg = RTW_TNPDA;
   1967 	sc->sc_txdesc_blk[RTW_TXPRIMD].tdb_base = RTW_RING_BASE(sc, hd_txmd);
   1968 	sc->sc_txdesc_blk[RTW_TXPRIHI].tdb_basereg = RTW_THPDA;
   1969 	sc->sc_txdesc_blk[RTW_TXPRIHI].tdb_base = RTW_RING_BASE(sc, hd_txhi);
   1970 	sc->sc_txdesc_blk[RTW_TXPRIBCN].tdb_basereg = RTW_TBDA;
   1971 	sc->sc_txdesc_blk[RTW_TXPRIBCN].tdb_base = RTW_RING_BASE(sc, hd_bcn);
   1972 
   1973 	for (pri = 0; pri < RTW_NTXPRI; pri++) {
   1974 		tdb = &sc->sc_txdesc_blk[pri];
   1975 		RTW_WRITE(regs, tdb->tdb_basereg, tdb->tdb_base);
   1976 		RTW_DPRINTF(RTW_DEBUG_XMIT_DESC,
   1977 		    ("%s: reg[tdb->tdb_basereg] <- %" PRIxPTR "\n", __func__,
   1978 		     (uintptr_t)tdb->tdb_base));
   1979 	}
   1980 
   1981 	RTW_WRITE(regs, RTW_RDSAR, RTW_RING_BASE(sc, hd_rx));
   1982 
   1983 	RTW_DPRINTF(RTW_DEBUG_RECV_DESC,
   1984 	    ("%s: reg[RDSAR] <- %" PRIxPTR "\n", __func__,
   1985 	     (uintptr_t)RTW_RING_BASE(sc, hd_rx)));
   1986 
   1987 	RTW_SYNC(regs, RTW_TLPDA, RTW_RDSAR);
   1988 
   1989 }
   1990 
   1991 static int
   1992 rtw_swring_setup(struct rtw_softc *sc)
   1993 {
   1994 	int rc;
   1995 	struct rtw_rxdesc_blk *rdb;
   1996 
   1997 	rtw_txdesc_blk_init_all(&sc->sc_txdesc_blk[0]);
   1998 
   1999 	rtw_txsoft_blk_init_all(&sc->sc_txsoft_blk[0]);
   2000 
   2001 	rdb = &sc->sc_rxdesc_blk;
   2002 	if ((rc = rtw_rxsoft_init_all(sc->sc_dmat, sc->sc_rxsoft, &rdb->rdb_ndesc,
   2003 	     sc->sc_dev)) != 0 && rdb->rdb_ndesc == 0) {
   2004 		aprint_error_dev(sc->sc_dev, "could not allocate rx buffers\n");
   2005 		return rc;
   2006 	}
   2007 
   2008 	rdb = &sc->sc_rxdesc_blk;
   2009 	rtw_rxdescs_sync(rdb, 0, rdb->rdb_ndesc,
   2010 	    BUS_DMASYNC_POSTREAD | BUS_DMASYNC_POSTWRITE);
   2011 	rtw_rxdesc_init_all(rdb, sc->sc_rxsoft, 1);
   2012 	rdb->rdb_next = 0;
   2013 
   2014 	rtw_txdescs_sync_all(&sc->sc_txdesc_blk[0]);
   2015 	return 0;
   2016 }
   2017 
   2018 static void
   2019 rtw_txdesc_blk_init(struct rtw_txdesc_blk *tdb)
   2020 {
   2021 	int i;
   2022 
   2023 	(void)memset(tdb->tdb_desc, 0,
   2024 	    sizeof(tdb->tdb_desc[0]) * tdb->tdb_ndesc);
   2025 	for (i = 0; i < tdb->tdb_ndesc; i++)
   2026 		tdb->tdb_desc[i].td_next = htole32(RTW_NEXT_DESC(tdb, i));
   2027 }
   2028 
   2029 static u_int
   2030 rtw_txring_next(struct rtw_regs *regs, struct rtw_txdesc_blk *tdb)
   2031 {
   2032 	return (le32toh(RTW_READ(regs, tdb->tdb_basereg)) - tdb->tdb_base) /
   2033 	    sizeof(struct rtw_txdesc);
   2034 }
   2035 
   2036 #ifdef RTW_DIAG
   2037 static void
   2038 rtw_txring_fixup(struct rtw_softc *sc, const char *fn, int ln)
   2039 {
   2040 	int pri;
   2041 	u_int next;
   2042 	struct rtw_txdesc_blk *tdb;
   2043 	struct rtw_regs *regs = &sc->sc_regs;
   2044 
   2045 	for (pri = 0; pri < RTW_NTXPRI; pri++) {
   2046 		int i;
   2047 		tdb = &sc->sc_txdesc_blk[pri];
   2048 		next = rtw_txring_next(regs, tdb);
   2049 		if (tdb->tdb_next == next)
   2050 			continue;
   2051 		for (i = 0; next != tdb->tdb_next;
   2052 		    next = RTW_NEXT_IDX(tdb, next), i++) {
   2053 			if ((tdb->tdb_desc[next].td_stat & htole32(RTW_TXSTAT_OWN)) == 0)
   2054 				break;
   2055 		}
   2056 		printf("%s:%d: tx-ring %d expected next %u, read %u+%d -> %s\n", fn,
   2057 		    ln, pri, tdb->tdb_next, next, i, tdb->tdb_next == next ? "okay" : "BAD");
   2058 		if (tdb->tdb_next == next)
   2059 			continue;
   2060 		tdb->tdb_next = MIN(next, tdb->tdb_ndesc - 1);
   2061 	}
   2062 }
   2063 #endif
   2064 
   2065 static void
   2066 rtw_txdescs_reset(struct rtw_softc *sc)
   2067 {
   2068 	int pri;
   2069 	struct rtw_txsoft_blk	*tsb;
   2070 	struct rtw_txdesc_blk	*tdb;
   2071 
   2072 	for (pri = 0; pri < RTW_NTXPRI; pri++) {
   2073 		tsb = &sc->sc_txsoft_blk[pri];
   2074 		tdb = &sc->sc_txdesc_blk[pri];
   2075 		rtw_collect_txring(sc, tsb, tdb, 1);
   2076 #ifdef RTW_DIAG
   2077 		if (!SIMPLEQ_EMPTY(&tsb->tsb_dirtyq))
   2078 			printf("%s: packets left in ring %d\n", __func__, pri);
   2079 #endif
   2080 	}
   2081 }
   2082 
   2083 static void
   2084 rtw_intr_ioerror(struct rtw_softc *sc, uint16_t isr)
   2085 {
   2086 	int s;
   2087 
   2088 	aprint_error_dev(sc->sc_dev, "tx fifo underflow\n");
   2089 
   2090 	RTW_DPRINTF(RTW_DEBUG_BUGS, ("%s: cleaning up xmit, isr %" PRIx16
   2091 	    "\n", device_xname(sc->sc_dev), isr));
   2092 
   2093 	s = splnet();
   2094 
   2095 #ifdef RTW_DEBUG
   2096 	rtw_dump_rings(sc);
   2097 #endif /* RTW_DEBUG */
   2098 
   2099 	/* Collect tx'd packets.  XXX let's hope this stops the transmit
   2100 	 * timeouts.
   2101 	 */
   2102 	rtw_txdescs_reset(sc);
   2103 
   2104 #ifdef RTW_DEBUG
   2105 	rtw_dump_rings(sc);
   2106 #endif /* RTW_DEBUG */
   2107 
   2108 	splx(s);
   2109 }
   2110 
   2111 static inline void
   2112 rtw_suspend_ticks(struct rtw_softc *sc)
   2113 {
   2114 	RTW_DPRINTF(RTW_DEBUG_TIMEOUT,
   2115 	    ("%s: suspending ticks\n", device_xname(sc->sc_dev)));
   2116 	sc->sc_do_tick = 0;
   2117 }
   2118 
   2119 static inline void
   2120 rtw_resume_ticks(struct rtw_softc *sc)
   2121 {
   2122 	uint32_t tsftrl0, tsftrl1, next_tint;
   2123 
   2124 	tsftrl0 = RTW_READ(&sc->sc_regs, RTW_TSFTRL);
   2125 
   2126 	tsftrl1 = RTW_READ(&sc->sc_regs, RTW_TSFTRL);
   2127 	next_tint = tsftrl1 + 1000000;
   2128 	RTW_WRITE(&sc->sc_regs, RTW_TINT, next_tint);
   2129 
   2130 	sc->sc_do_tick = 1;
   2131 
   2132 #ifdef RTW_DEBUG
   2133 	RTW_DPRINTF(RTW_DEBUG_TIMEOUT,
   2134 	    ("%s: resume ticks delta %#08x now %#08x next %#08x\n",
   2135 	    device_xname(sc->sc_dev), tsftrl1 - tsftrl0, tsftrl1, next_tint));
   2136 #else
   2137 	__USE(tsftrl0);
   2138 #endif
   2139 }
   2140 
   2141 static void
   2142 rtw_intr_timeout(struct rtw_softc *sc)
   2143 {
   2144 	int s;
   2145 
   2146 	s = splnet();
   2147 	RTW_DPRINTF(RTW_DEBUG_TIMEOUT, ("%s: timeout\n", device_xname(sc->sc_dev)));
   2148 	if (sc->sc_do_tick)
   2149 		rtw_resume_ticks(sc);
   2150 	splx(s);
   2151 }
   2152 
   2153 int
   2154 rtw_intr(void *arg)
   2155 {
   2156 	struct rtw_softc *sc = arg;
   2157 	struct rtw_regs *regs = &sc->sc_regs;
   2158 	uint16_t isr;
   2159 	struct ifnet *ifp = &sc->sc_if;
   2160 
   2161 	/*
   2162 	 * If the interface isn't running, the interrupt couldn't
   2163 	 * possibly have come from us.
   2164 	 */
   2165 	if ((ifp->if_flags & IFF_RUNNING) == 0 ||
   2166 	    !device_activation(sc->sc_dev, DEVACT_LEVEL_DRIVER)) {
   2167 		RTW_DPRINTF(RTW_DEBUG_INTR, ("%s: stray interrupt\n",
   2168 		    device_xname(sc->sc_dev)));
   2169 		return (0);
   2170 	}
   2171 
   2172 	isr = RTW_READ16(regs, RTW_ISR);
   2173 	if (isr == 0)
   2174 		return (0);
   2175 
   2176 	/* Disable interrupts. */
   2177 	RTW_WRITE16(regs, RTW_IMR, 0);
   2178 	RTW_WBW(regs, RTW_IMR, RTW_IMR);
   2179 
   2180 	softint_schedule(sc->sc_soft_ih);
   2181 	return (1);
   2182 }
   2183 
   2184 static void
   2185 rtw_softintr(void *arg)
   2186 {
   2187 	int i;
   2188 	struct rtw_softc *sc = arg;
   2189 	struct rtw_regs *regs = &sc->sc_regs;
   2190 	uint16_t isr;
   2191 	struct ifnet *ifp = &sc->sc_if;
   2192 
   2193 	if ((ifp->if_flags & IFF_RUNNING) == 0 ||
   2194 	    !device_activation(sc->sc_dev, DEVACT_LEVEL_DRIVER)) {
   2195 		RTW_DPRINTF(RTW_DEBUG_INTR, ("%s: stray interrupt\n",
   2196 		    device_xname(sc->sc_dev)));
   2197 		return;
   2198 	}
   2199 
   2200 	for (i = 0; i < 10; i++) {
   2201 		isr = RTW_READ16(regs, RTW_ISR);
   2202 
   2203 		RTW_WRITE16(regs, RTW_ISR, isr);
   2204 		RTW_WBR(regs, RTW_ISR, RTW_ISR);
   2205 
   2206 		if (sc->sc_intr_ack != NULL)
   2207 			(*sc->sc_intr_ack)(regs);
   2208 
   2209 		if (isr == 0)
   2210 			break;
   2211 
   2212 #ifdef RTW_DEBUG
   2213 #define PRINTINTR(flag) do { \
   2214 	if ((isr & flag) != 0) { \
   2215 		printf("%s" #flag, delim); \
   2216 		delim = ","; \
   2217 	} \
   2218 } while (0)
   2219 
   2220 		if ((rtw_debug & RTW_DEBUG_INTR) != 0 && isr != 0) {
   2221 			const char *delim = "<";
   2222 
   2223 			printf("%s: reg[ISR] = %x", device_xname(sc->sc_dev),
   2224 			    isr);
   2225 
   2226 			PRINTINTR(RTW_INTR_TXFOVW);
   2227 			PRINTINTR(RTW_INTR_TIMEOUT);
   2228 			PRINTINTR(RTW_INTR_BCNINT);
   2229 			PRINTINTR(RTW_INTR_ATIMINT);
   2230 			PRINTINTR(RTW_INTR_TBDER);
   2231 			PRINTINTR(RTW_INTR_TBDOK);
   2232 			PRINTINTR(RTW_INTR_THPDER);
   2233 			PRINTINTR(RTW_INTR_THPDOK);
   2234 			PRINTINTR(RTW_INTR_TNPDER);
   2235 			PRINTINTR(RTW_INTR_TNPDOK);
   2236 			PRINTINTR(RTW_INTR_RXFOVW);
   2237 			PRINTINTR(RTW_INTR_RDU);
   2238 			PRINTINTR(RTW_INTR_TLPDER);
   2239 			PRINTINTR(RTW_INTR_TLPDOK);
   2240 			PRINTINTR(RTW_INTR_RER);
   2241 			PRINTINTR(RTW_INTR_ROK);
   2242 
   2243 			printf(">\n");
   2244 		}
   2245 #undef PRINTINTR
   2246 #endif /* RTW_DEBUG */
   2247 
   2248 		if ((isr & RTW_INTR_RX) != 0)
   2249 			rtw_intr_rx(sc, isr);
   2250 		if ((isr & RTW_INTR_TX) != 0)
   2251 			rtw_intr_tx(sc, isr);
   2252 		if ((isr & RTW_INTR_BEACON) != 0)
   2253 			rtw_intr_beacon(sc, isr);
   2254 		if ((isr & RTW_INTR_ATIMINT) != 0)
   2255 			rtw_intr_atim(sc);
   2256 		if ((isr & RTW_INTR_IOERROR) != 0)
   2257 			rtw_intr_ioerror(sc, isr);
   2258 		if ((isr & RTW_INTR_TIMEOUT) != 0)
   2259 			rtw_intr_timeout(sc);
   2260 	}
   2261 	if (i == 10)
   2262 		softint_schedule(sc->sc_soft_ih);
   2263 
   2264 	/* Re-enable interrupts */
   2265 	RTW_WRITE16(regs, RTW_IMR, sc->sc_inten);
   2266 	RTW_WBW(regs, RTW_IMR, RTW_IMR);
   2267 }
   2268 
   2269 /* Must be called at splnet. */
   2270 static void
   2271 rtw_stop(struct ifnet *ifp, int disable)
   2272 {
   2273 	int pri;
   2274 	struct rtw_softc *sc = (struct rtw_softc *)ifp->if_softc;
   2275 	struct ieee80211com *ic = &sc->sc_ic;
   2276 	struct rtw_regs *regs = &sc->sc_regs;
   2277 
   2278 	rtw_suspend_ticks(sc);
   2279 
   2280 	ieee80211_new_state(ic, IEEE80211_S_INIT, -1);
   2281 
   2282 	if (device_has_power(sc->sc_dev)) {
   2283 		/* Disable interrupts. */
   2284 		RTW_WRITE16(regs, RTW_IMR, 0);
   2285 
   2286 		RTW_WBW(regs, RTW_TPPOLL, RTW_IMR);
   2287 
   2288 		/* Stop the transmit and receive processes. First stop DMA,
   2289 		 * then disable receiver and transmitter.
   2290 		 */
   2291 		RTW_WRITE8(regs, RTW_TPPOLL, RTW_TPPOLL_SALL);
   2292 
   2293 		RTW_SYNC(regs, RTW_TPPOLL, RTW_IMR);
   2294 
   2295 		rtw_io_enable(sc, RTW_CR_RE | RTW_CR_TE, 0);
   2296 	}
   2297 
   2298 	for (pri = 0; pri < RTW_NTXPRI; pri++) {
   2299 		rtw_txsofts_release(sc->sc_dmat, &sc->sc_ic,
   2300 		    &sc->sc_txsoft_blk[pri]);
   2301 	}
   2302 
   2303 	rtw_rxbufs_release(sc->sc_dmat, &sc->sc_rxsoft[0]);
   2304 
   2305 	/* Mark the interface as not running.  Cancel the watchdog timer. */
   2306 	ifp->if_flags &= ~(IFF_RUNNING | IFF_OACTIVE);
   2307 	ifp->if_timer = 0;
   2308 
   2309 	if (disable)
   2310 		pmf_device_suspend(sc->sc_dev, &sc->sc_qual);
   2311 
   2312 	return;
   2313 }
   2314 
   2315 const char *
   2316 rtw_pwrstate_string(enum rtw_pwrstate power)
   2317 {
   2318 	switch (power) {
   2319 	case RTW_ON:
   2320 		return "on";
   2321 	case RTW_SLEEP:
   2322 		return "sleep";
   2323 	case RTW_OFF:
   2324 		return "off";
   2325 	default:
   2326 		return "unknown";
   2327 	}
   2328 }
   2329 
   2330 /* XXX For Maxim, I am using the RFMD settings gleaned from the
   2331  * reference driver, plus a magic Maxim "ON" value that comes from
   2332  * the Realtek document "Windows PG for Rtl8180."
   2333  */
   2334 static void
   2335 rtw_maxim_pwrstate(struct rtw_regs *regs, enum rtw_pwrstate power,
   2336     int before_rf, int digphy)
   2337 {
   2338 	uint32_t anaparm;
   2339 
   2340 	anaparm = RTW_READ(regs, RTW_ANAPARM);
   2341 	anaparm &= ~(RTW_ANAPARM_RFPOW_MASK | RTW_ANAPARM_TXDACOFF);
   2342 
   2343 	switch (power) {
   2344 	case RTW_OFF:
   2345 		if (before_rf)
   2346 			return;
   2347 		anaparm |= RTW_ANAPARM_RFPOW_MAXIM_OFF;
   2348 		anaparm |= RTW_ANAPARM_TXDACOFF;
   2349 		break;
   2350 	case RTW_SLEEP:
   2351 		if (!before_rf)
   2352 			return;
   2353 		anaparm |= RTW_ANAPARM_RFPOW_MAXIM_SLEEP;
   2354 		anaparm |= RTW_ANAPARM_TXDACOFF;
   2355 		break;
   2356 	case RTW_ON:
   2357 		if (!before_rf)
   2358 			return;
   2359 		anaparm |= RTW_ANAPARM_RFPOW_MAXIM_ON;
   2360 		break;
   2361 	}
   2362 	RTW_DPRINTF(RTW_DEBUG_PWR,
   2363 	    ("%s: power state %s, %s RF, reg[ANAPARM] <- %08x\n",
   2364 	    __func__, rtw_pwrstate_string(power),
   2365 	    (before_rf) ? "before" : "after", anaparm));
   2366 
   2367 	RTW_WRITE(regs, RTW_ANAPARM, anaparm);
   2368 	RTW_SYNC(regs, RTW_ANAPARM, RTW_ANAPARM);
   2369 }
   2370 
   2371 /* XXX I am using the RFMD settings gleaned from the reference
   2372  * driver.  They agree
   2373  */
   2374 static void
   2375 rtw_rfmd_pwrstate(struct rtw_regs *regs, enum rtw_pwrstate power,
   2376     int before_rf, int digphy)
   2377 {
   2378 	uint32_t anaparm;
   2379 
   2380 	anaparm = RTW_READ(regs, RTW_ANAPARM);
   2381 	anaparm &= ~(RTW_ANAPARM_RFPOW_MASK | RTW_ANAPARM_TXDACOFF);
   2382 
   2383 	switch (power) {
   2384 	case RTW_OFF:
   2385 		if (before_rf)
   2386 			return;
   2387 		anaparm |= RTW_ANAPARM_RFPOW_RFMD_OFF;
   2388 		anaparm |= RTW_ANAPARM_TXDACOFF;
   2389 		break;
   2390 	case RTW_SLEEP:
   2391 		if (!before_rf)
   2392 			return;
   2393 		anaparm |= RTW_ANAPARM_RFPOW_RFMD_SLEEP;
   2394 		anaparm |= RTW_ANAPARM_TXDACOFF;
   2395 		break;
   2396 	case RTW_ON:
   2397 		if (!before_rf)
   2398 			return;
   2399 		anaparm |= RTW_ANAPARM_RFPOW_RFMD_ON;
   2400 		break;
   2401 	}
   2402 	RTW_DPRINTF(RTW_DEBUG_PWR,
   2403 	    ("%s: power state %s, %s RF, reg[ANAPARM] <- %08x\n",
   2404 	    __func__, rtw_pwrstate_string(power),
   2405 	    (before_rf) ? "before" : "after", anaparm));
   2406 
   2407 	RTW_WRITE(regs, RTW_ANAPARM, anaparm);
   2408 	RTW_SYNC(regs, RTW_ANAPARM, RTW_ANAPARM);
   2409 }
   2410 
   2411 static void
   2412 rtw_philips_pwrstate(struct rtw_regs *regs, enum rtw_pwrstate power,
   2413     int before_rf, int digphy)
   2414 {
   2415 	uint32_t anaparm;
   2416 
   2417 	anaparm = RTW_READ(regs, RTW_ANAPARM);
   2418 	anaparm &= ~(RTW_ANAPARM_RFPOW_MASK | RTW_ANAPARM_TXDACOFF);
   2419 
   2420 	switch (power) {
   2421 	case RTW_OFF:
   2422 		if (before_rf)
   2423 			return;
   2424 		anaparm |= RTW_ANAPARM_RFPOW_PHILIPS_OFF;
   2425 		anaparm |= RTW_ANAPARM_TXDACOFF;
   2426 		break;
   2427 	case RTW_SLEEP:
   2428 		if (!before_rf)
   2429 			return;
   2430 		anaparm |= RTW_ANAPARM_RFPOW_PHILIPS_SLEEP;
   2431 		anaparm |= RTW_ANAPARM_TXDACOFF;
   2432 		break;
   2433 	case RTW_ON:
   2434 		if (!before_rf)
   2435 			return;
   2436 		if (digphy) {
   2437 			anaparm |= RTW_ANAPARM_RFPOW_DIG_PHILIPS_ON;
   2438 			/* XXX guess */
   2439 			anaparm |= RTW_ANAPARM_TXDACOFF;
   2440 		} else
   2441 			anaparm |= RTW_ANAPARM_RFPOW_ANA_PHILIPS_ON;
   2442 		break;
   2443 	}
   2444 	RTW_DPRINTF(RTW_DEBUG_PWR,
   2445 	    ("%s: power state %s, %s RF, reg[ANAPARM] <- %08x\n",
   2446 	    __func__, rtw_pwrstate_string(power),
   2447 	    (before_rf) ? "before" : "after", anaparm));
   2448 
   2449 	RTW_WRITE(regs, RTW_ANAPARM, anaparm);
   2450 	RTW_SYNC(regs, RTW_ANAPARM, RTW_ANAPARM);
   2451 }
   2452 
   2453 static void
   2454 rtw_pwrstate0(struct rtw_softc *sc, enum rtw_pwrstate power, int before_rf,
   2455     int digphy)
   2456 {
   2457 	struct rtw_regs *regs = &sc->sc_regs;
   2458 
   2459 	rtw_set_access(regs, RTW_ACCESS_ANAPARM);
   2460 
   2461 	(*sc->sc_pwrstate_cb)(regs, power, before_rf, digphy);
   2462 
   2463 	rtw_set_access(regs, RTW_ACCESS_NONE);
   2464 
   2465 	return;
   2466 }
   2467 
   2468 static int
   2469 rtw_pwrstate(struct rtw_softc *sc, enum rtw_pwrstate power)
   2470 {
   2471 	int rc;
   2472 
   2473 	RTW_DPRINTF(RTW_DEBUG_PWR,
   2474 	    ("%s: %s->%s\n", __func__,
   2475 	    rtw_pwrstate_string(sc->sc_pwrstate), rtw_pwrstate_string(power)));
   2476 
   2477 	if (sc->sc_pwrstate == power)
   2478 		return 0;
   2479 
   2480 	rtw_pwrstate0(sc, power, 1, sc->sc_flags & RTW_F_DIGPHY);
   2481 	rc = rtw_rf_pwrstate(sc->sc_rf, power);
   2482 	rtw_pwrstate0(sc, power, 0, sc->sc_flags & RTW_F_DIGPHY);
   2483 
   2484 	switch (power) {
   2485 	case RTW_ON:
   2486 		/* TBD set LEDs */
   2487 		break;
   2488 	case RTW_SLEEP:
   2489 		/* TBD */
   2490 		break;
   2491 	case RTW_OFF:
   2492 		/* TBD */
   2493 		break;
   2494 	}
   2495 	if (rc == 0)
   2496 		sc->sc_pwrstate = power;
   2497 	else
   2498 		sc->sc_pwrstate = RTW_OFF;
   2499 	return rc;
   2500 }
   2501 
   2502 static int
   2503 rtw_tune(struct rtw_softc *sc)
   2504 {
   2505 	struct ieee80211com *ic = &sc->sc_ic;
   2506 	struct rtw_tx_radiotap_header *rt = &sc->sc_txtap;
   2507 	struct rtw_rx_radiotap_header *rr = &sc->sc_rxtap;
   2508 	u_int chan;
   2509 	int rc;
   2510 	int antdiv = sc->sc_flags & RTW_F_ANTDIV,
   2511 	    dflantb = sc->sc_flags & RTW_F_DFLANTB;
   2512 
   2513 	chan = ieee80211_chan2ieee(ic, ic->ic_curchan);
   2514 	KASSERT(chan != IEEE80211_CHAN_ANY);
   2515 
   2516 	rt->rt_chan_freq = htole16(ic->ic_curchan->ic_freq);
   2517 	rt->rt_chan_flags = htole16(ic->ic_curchan->ic_flags);
   2518 
   2519 	rr->rr_chan_freq = htole16(ic->ic_curchan->ic_freq);
   2520 	rr->rr_chan_flags = htole16(ic->ic_curchan->ic_flags);
   2521 
   2522 	if (chan == sc->sc_cur_chan) {
   2523 		RTW_DPRINTF(RTW_DEBUG_TUNE,
   2524 		    ("%s: already tuned chan #%d\n", __func__, chan));
   2525 		return 0;
   2526 	}
   2527 
   2528 	rtw_suspend_ticks(sc);
   2529 
   2530 	rtw_io_enable(sc, RTW_CR_RE | RTW_CR_TE, 0);
   2531 
   2532 	/* TBD wait for Tx to complete */
   2533 
   2534 	KASSERT(device_has_power(sc->sc_dev));
   2535 
   2536 	if ((rc = rtw_phy_init(&sc->sc_regs, sc->sc_rf,
   2537 	    rtw_chan2txpower(&sc->sc_srom, ic, ic->ic_curchan), sc->sc_csthr,
   2538 		ic->ic_curchan->ic_freq, antdiv, dflantb, RTW_ON)) != 0) {
   2539 		/* XXX condition on powersaving */
   2540 		aprint_error_dev(sc->sc_dev, "phy init failed\n");
   2541 	}
   2542 
   2543 	sc->sc_cur_chan = chan;
   2544 
   2545 	rtw_io_enable(sc, RTW_CR_RE | RTW_CR_TE, 1);
   2546 
   2547 	rtw_resume_ticks(sc);
   2548 
   2549 	return rc;
   2550 }
   2551 
   2552 bool
   2553 rtw_suspend(device_t self, const pmf_qual_t *qual)
   2554 {
   2555 	int rc;
   2556 	struct rtw_softc *sc = device_private(self);
   2557 
   2558 	sc->sc_flags &= ~RTW_F_DK_VALID;
   2559 
   2560 	if (!device_has_power(self))
   2561 		return false;
   2562 
   2563 	/* turn off PHY */
   2564 	if ((rc = rtw_pwrstate(sc, RTW_OFF)) != 0) {
   2565 		aprint_error_dev(self, "failed to turn off PHY (%d)\n", rc);
   2566 		return false;
   2567 	}
   2568 
   2569 	rtw_disable_interrupts(&sc->sc_regs);
   2570 
   2571 	return true;
   2572 }
   2573 
   2574 bool
   2575 rtw_resume(device_t self, const pmf_qual_t *qual)
   2576 {
   2577 	struct rtw_softc *sc = device_private(self);
   2578 
   2579 	/* Power may have been removed, resetting WEP keys.
   2580 	 */
   2581 	sc->sc_flags &= ~RTW_F_DK_VALID;
   2582 	rtw_enable_interrupts(sc);
   2583 
   2584 	return true;
   2585 }
   2586 
   2587 static void
   2588 rtw_transmit_config(struct rtw_regs *regs)
   2589 {
   2590 	uint32_t tcr;
   2591 
   2592 	tcr = RTW_READ(regs, RTW_TCR);
   2593 
   2594 	tcr |= RTW_TCR_CWMIN;
   2595 	tcr &= ~RTW_TCR_MXDMA_MASK;
   2596 	tcr |= RTW_TCR_MXDMA_256;
   2597 	tcr |= RTW_TCR_SAT;		/* send ACK as fast as possible */
   2598 	tcr &= ~RTW_TCR_LBK_MASK;
   2599 	tcr |= RTW_TCR_LBK_NORMAL;	/* normal operating mode */
   2600 
   2601 	/* set short/long retry limits */
   2602 	tcr &= ~(RTW_TCR_SRL_MASK | RTW_TCR_LRL_MASK);
   2603 	tcr |= __SHIFTIN(4, RTW_TCR_SRL_MASK) | __SHIFTIN(4, RTW_TCR_LRL_MASK);
   2604 
   2605 	tcr &= ~RTW_TCR_CRC;	/* NIC appends CRC32 */
   2606 
   2607 	RTW_WRITE(regs, RTW_TCR, tcr);
   2608 	RTW_SYNC(regs, RTW_TCR, RTW_TCR);
   2609 }
   2610 
   2611 static void
   2612 rtw_disable_interrupts(struct rtw_regs *regs)
   2613 {
   2614 	RTW_WRITE16(regs, RTW_IMR, 0);
   2615 	RTW_WBW(regs, RTW_IMR, RTW_ISR);
   2616 	RTW_WRITE16(regs, RTW_ISR, 0xffff);
   2617 	RTW_SYNC(regs, RTW_IMR, RTW_ISR);
   2618 }
   2619 
   2620 static void
   2621 rtw_enable_interrupts(struct rtw_softc *sc)
   2622 {
   2623 	struct rtw_regs *regs = &sc->sc_regs;
   2624 
   2625 	sc->sc_inten = RTW_INTR_RX | RTW_INTR_TX | RTW_INTR_BEACON
   2626 	    | RTW_INTR_ATIMINT;
   2627 	sc->sc_inten |= RTW_INTR_IOERROR | RTW_INTR_TIMEOUT;
   2628 
   2629 	RTW_WRITE16(regs, RTW_IMR, sc->sc_inten);
   2630 	RTW_WBW(regs, RTW_IMR, RTW_ISR);
   2631 	RTW_WRITE16(regs, RTW_ISR, 0xffff);
   2632 	RTW_SYNC(regs, RTW_IMR, RTW_ISR);
   2633 
   2634 	/* XXX necessary? */
   2635 	if (sc->sc_intr_ack != NULL)
   2636 		(*sc->sc_intr_ack)(regs);
   2637 }
   2638 
   2639 static void
   2640 rtw_set_nettype(struct rtw_softc *sc, enum ieee80211_opmode opmode)
   2641 {
   2642 	uint8_t msr;
   2643 
   2644 	/* I'm guessing that MSR is protected as CONFIG[0123] are. */
   2645 	rtw_set_access(&sc->sc_regs, RTW_ACCESS_CONFIG);
   2646 
   2647 	msr = RTW_READ8(&sc->sc_regs, RTW_MSR) & ~RTW_MSR_NETYPE_MASK;
   2648 
   2649 	switch (opmode) {
   2650 	case IEEE80211_M_AHDEMO:
   2651 	case IEEE80211_M_IBSS:
   2652 		msr |= RTW_MSR_NETYPE_ADHOC_OK;
   2653 		break;
   2654 	case IEEE80211_M_HOSTAP:
   2655 		msr |= RTW_MSR_NETYPE_AP_OK;
   2656 		break;
   2657 	case IEEE80211_M_MONITOR:
   2658 		/* XXX */
   2659 		msr |= RTW_MSR_NETYPE_NOLINK;
   2660 		break;
   2661 	case IEEE80211_M_STA:
   2662 		msr |= RTW_MSR_NETYPE_INFRA_OK;
   2663 		break;
   2664 	}
   2665 	RTW_WRITE8(&sc->sc_regs, RTW_MSR, msr);
   2666 
   2667 	rtw_set_access(&sc->sc_regs, RTW_ACCESS_NONE);
   2668 }
   2669 
   2670 #define	rtw_calchash(addr) \
   2671 	(ether_crc32_be((addr), IEEE80211_ADDR_LEN) >> 26)
   2672 
   2673 static void
   2674 rtw_pktfilt_load(struct rtw_softc *sc)
   2675 {
   2676 	struct rtw_regs *regs = &sc->sc_regs;
   2677 	struct ieee80211com *ic = &sc->sc_ic;
   2678 	struct ethercom *ec = &sc->sc_ec;
   2679 	struct ifnet *ifp = &sc->sc_if;
   2680 	int hash;
   2681 	uint32_t hashes[2] = { 0, 0 };
   2682 	struct ether_multi *enm;
   2683 	struct ether_multistep step;
   2684 
   2685 	/* XXX might be necessary to stop Rx/Tx engines while setting filters */
   2686 
   2687 	sc->sc_rcr &= ~RTW_RCR_PKTFILTER_MASK;
   2688 	sc->sc_rcr &= ~(RTW_RCR_MXDMA_MASK | RTW_RCR_RXFTH_MASK);
   2689 
   2690 	sc->sc_rcr |= RTW_RCR_PKTFILTER_DEFAULT;
   2691 	/* MAC auto-reset PHY (huh?) */
   2692 	sc->sc_rcr |= RTW_RCR_ENMARP;
   2693 	/* DMA whole Rx packets, only.  Set Tx DMA burst size to 1024 bytes. */
   2694 	sc->sc_rcr |= RTW_RCR_MXDMA_1024 | RTW_RCR_RXFTH_WHOLE;
   2695 
   2696 	switch (ic->ic_opmode) {
   2697 	case IEEE80211_M_MONITOR:
   2698 		sc->sc_rcr |= RTW_RCR_MONITOR;
   2699 		break;
   2700 	case IEEE80211_M_AHDEMO:
   2701 	case IEEE80211_M_IBSS:
   2702 		/* receive broadcasts in our BSS */
   2703 		sc->sc_rcr |= RTW_RCR_ADD3;
   2704 		break;
   2705 	default:
   2706 		break;
   2707 	}
   2708 
   2709 	ifp->if_flags &= ~IFF_ALLMULTI;
   2710 
   2711 	/*
   2712 	 * Program the 64-bit multicast hash filter.
   2713 	 */
   2714 	ETHER_LOCK(ec);
   2715 	ETHER_FIRST_MULTI(step, ec, enm);
   2716 	while (enm != NULL) {
   2717 		/* XXX */
   2718 		if (memcmp(enm->enm_addrlo, enm->enm_addrhi,
   2719 		    ETHER_ADDR_LEN) != 0) {
   2720 			ifp->if_flags |= IFF_ALLMULTI;
   2721 			break;
   2722 		}
   2723 
   2724 		hash = rtw_calchash(enm->enm_addrlo);
   2725 		hashes[hash >> 5] |= (1 << (hash & 0x1f));
   2726 		ETHER_NEXT_MULTI(step, enm);
   2727 	}
   2728 	ETHER_UNLOCK(ec);
   2729 
   2730 	/* XXX accept all broadcast if scanning */
   2731 	if ((ifp->if_flags & IFF_BROADCAST) != 0)
   2732 		sc->sc_rcr |= RTW_RCR_AB;	/* accept all broadcast */
   2733 
   2734 	if (ifp->if_flags & IFF_PROMISC) {
   2735 		sc->sc_rcr |= RTW_RCR_AB;	/* accept all broadcast */
   2736 		sc->sc_rcr |= RTW_RCR_ACRC32;	/* accept frames failing CRC */
   2737 		sc->sc_rcr |= RTW_RCR_AICV;	/* accept frames failing ICV */
   2738 		ifp->if_flags |= IFF_ALLMULTI;
   2739 	}
   2740 
   2741 	if (ifp->if_flags & IFF_ALLMULTI)
   2742 		hashes[0] = hashes[1] = 0xffffffff;
   2743 
   2744 	if ((hashes[0] | hashes[1]) != 0)
   2745 		sc->sc_rcr |= RTW_RCR_AM;	/* accept multicast */
   2746 
   2747 	RTW_WRITE(regs, RTW_MAR0, hashes[0]);
   2748 	RTW_WRITE(regs, RTW_MAR1, hashes[1]);
   2749 	RTW_WRITE(regs, RTW_RCR, sc->sc_rcr);
   2750 	RTW_SYNC(regs, RTW_MAR0, RTW_RCR); /* RTW_MAR0 < RTW_MAR1 < RTW_RCR */
   2751 
   2752 	DPRINTF(sc, RTW_DEBUG_PKTFILT,
   2753 	    ("%s: RTW_MAR0 %08x RTW_MAR1 %08x RTW_RCR %08x\n",
   2754 	    device_xname(sc->sc_dev), RTW_READ(regs, RTW_MAR0),
   2755 	    RTW_READ(regs, RTW_MAR1), RTW_READ(regs, RTW_RCR)));
   2756 }
   2757 
   2758 static struct mbuf *
   2759 rtw_beacon_alloc(struct rtw_softc *sc, struct ieee80211_node *ni)
   2760 {
   2761 	struct ieee80211com *ic = &sc->sc_ic;
   2762 	struct mbuf *m;
   2763 	struct ieee80211_beacon_offsets	boff;
   2764 
   2765 	if ((m = ieee80211_beacon_alloc(ic, ni, &boff)) != NULL) {
   2766 		RTW_DPRINTF(RTW_DEBUG_BEACON,
   2767 		    ("%s: m %p len %u\n", __func__, m, m->m_len));
   2768 	}
   2769 	return m;
   2770 }
   2771 
   2772 /* Must be called at splnet. */
   2773 static int
   2774 rtw_init(struct ifnet *ifp)
   2775 {
   2776 	struct rtw_softc *sc = (struct rtw_softc *)ifp->if_softc;
   2777 	struct ieee80211com *ic = &sc->sc_ic;
   2778 	struct rtw_regs *regs = &sc->sc_regs;
   2779 	int rc;
   2780 
   2781 	if (device_is_active(sc->sc_dev)) {
   2782 		/* Cancel pending I/O and reset. */
   2783 		rtw_stop(ifp, 0);
   2784 	} else if (!pmf_device_resume(sc->sc_dev, &sc->sc_qual) ||
   2785 		   !device_is_active(sc->sc_dev))
   2786 		return 0;
   2787 
   2788 	DPRINTF(sc, RTW_DEBUG_TUNE, ("%s: channel %d freq %d flags 0x%04x\n",
   2789 	    __func__, ieee80211_chan2ieee(ic, ic->ic_curchan),
   2790 	    ic->ic_curchan->ic_freq, ic->ic_curchan->ic_flags));
   2791 
   2792 	if ((rc = rtw_pwrstate(sc, RTW_OFF)) != 0)
   2793 		goto out;
   2794 
   2795 	if ((rc = rtw_swring_setup(sc)) != 0)
   2796 		goto out;
   2797 
   2798 	rtw_transmit_config(regs);
   2799 
   2800 	rtw_set_access(regs, RTW_ACCESS_CONFIG);
   2801 
   2802 	RTW_WRITE8(regs, RTW_MSR, 0x0);	/* no link */
   2803 	RTW_WBW(regs, RTW_MSR, RTW_BRSR);
   2804 
   2805 	/* long PLCP header, 1Mb/2Mb basic rate */
   2806 	RTW_WRITE16(regs, RTW_BRSR, RTW_BRSR_MBR8180_2MBPS);
   2807 	RTW_SYNC(regs, RTW_BRSR, RTW_BRSR);
   2808 
   2809 	rtw_set_access(regs, RTW_ACCESS_ANAPARM);
   2810 	rtw_set_access(regs, RTW_ACCESS_NONE);
   2811 
   2812 	/* XXX from reference sources */
   2813 	RTW_WRITE(regs, RTW_FEMR, 0xffff);
   2814 	RTW_SYNC(regs, RTW_FEMR, RTW_FEMR);
   2815 
   2816 	rtw_set_rfprog(regs, sc->sc_rfchipid, sc->sc_dev);
   2817 
   2818 	RTW_WRITE8(regs, RTW_PHYDELAY, sc->sc_phydelay);
   2819 	/* from Linux driver */
   2820 	RTW_WRITE8(regs, RTW_CRCOUNT, RTW_CRCOUNT_MAGIC);
   2821 
   2822 	RTW_SYNC(regs, RTW_PHYDELAY, RTW_CRCOUNT);
   2823 
   2824 	rtw_enable_interrupts(sc);
   2825 
   2826 	rtw_pktfilt_load(sc);
   2827 
   2828 	rtw_hwring_setup(sc);
   2829 
   2830 	rtw_wep_setkeys(sc, ic->ic_nw_keys, ic->ic_def_txkey);
   2831 
   2832 	rtw_io_enable(sc, RTW_CR_RE | RTW_CR_TE, 1);
   2833 
   2834 	ifp->if_flags |= IFF_RUNNING;
   2835 	ic->ic_state = IEEE80211_S_INIT;
   2836 
   2837 	RTW_WRITE16(regs, RTW_BSSID16, 0x0);
   2838 	RTW_WRITE(regs, RTW_BSSID32, 0x0);
   2839 
   2840 	rtw_resume_ticks(sc);
   2841 
   2842 	rtw_set_nettype(sc, IEEE80211_M_MONITOR);
   2843 
   2844 	if (ic->ic_opmode == IEEE80211_M_MONITOR)
   2845 		return ieee80211_new_state(ic, IEEE80211_S_RUN, -1);
   2846 	else
   2847 		return ieee80211_new_state(ic, IEEE80211_S_SCAN, -1);
   2848 
   2849 out:
   2850 	aprint_error_dev(sc->sc_dev, "interface not running\n");
   2851 	return rc;
   2852 }
   2853 
   2854 static inline void
   2855 rtw_led_init(struct rtw_regs *regs)
   2856 {
   2857 	uint8_t cfg0, cfg1;
   2858 
   2859 	rtw_set_access(regs, RTW_ACCESS_CONFIG);
   2860 
   2861 	cfg0 = RTW_READ8(regs, RTW_CONFIG0);
   2862 	cfg0 |= RTW_CONFIG0_LEDGPOEN;
   2863 	RTW_WRITE8(regs, RTW_CONFIG0, cfg0);
   2864 
   2865 	cfg1 = RTW_READ8(regs, RTW_CONFIG1);
   2866 	RTW_DPRINTF(RTW_DEBUG_LED,
   2867 	    ("%s: read %" PRIx8 " from reg[CONFIG1]\n", __func__, cfg1));
   2868 
   2869 	cfg1 &= ~RTW_CONFIG1_LEDS_MASK;
   2870 	cfg1 |= RTW_CONFIG1_LEDS_TX_RX;
   2871 	RTW_WRITE8(regs, RTW_CONFIG1, cfg1);
   2872 
   2873 	rtw_set_access(regs, RTW_ACCESS_NONE);
   2874 }
   2875 
   2876 /*
   2877  * IEEE80211_S_INIT:		LED1 off
   2878  *
   2879  * IEEE80211_S_AUTH,
   2880  * IEEE80211_S_ASSOC,
   2881  * IEEE80211_S_SCAN:		LED1 blinks @ 1 Hz, blinks at 5Hz for tx/rx
   2882  *
   2883  * IEEE80211_S_RUN:		LED1 on, blinks @ 5Hz for tx/rx
   2884  */
   2885 static void
   2886 rtw_led_newstate(struct rtw_softc *sc, enum ieee80211_state nstate)
   2887 {
   2888 	struct rtw_led_state *ls;
   2889 
   2890 	ls = &sc->sc_led_state;
   2891 
   2892 	switch (nstate) {
   2893 	case IEEE80211_S_INIT:
   2894 		rtw_led_init(&sc->sc_regs);
   2895 		aprint_debug_dev(sc->sc_dev, "stopping blink\n");
   2896 		callout_stop(&ls->ls_slow_ch);
   2897 		callout_stop(&ls->ls_fast_ch);
   2898 		ls->ls_slowblink = 0;
   2899 		ls->ls_actblink = 0;
   2900 		ls->ls_default = 0;
   2901 		break;
   2902 	case IEEE80211_S_SCAN:
   2903 		aprint_debug_dev(sc->sc_dev, "scheduling blink\n");
   2904 		callout_schedule(&ls->ls_slow_ch, RTW_LED_SLOW_TICKS);
   2905 		callout_schedule(&ls->ls_fast_ch, RTW_LED_FAST_TICKS);
   2906 		/*FALLTHROUGH*/
   2907 	case IEEE80211_S_AUTH:
   2908 	case IEEE80211_S_ASSOC:
   2909 		ls->ls_default = RTW_LED1;
   2910 		ls->ls_actblink = RTW_LED1;
   2911 		ls->ls_slowblink = RTW_LED1;
   2912 		break;
   2913 	case IEEE80211_S_RUN:
   2914 		ls->ls_slowblink = 0;
   2915 		break;
   2916 	}
   2917 	rtw_led_set(ls, &sc->sc_regs, sc->sc_hwverid);
   2918 }
   2919 
   2920 static void
   2921 rtw_led_set(struct rtw_led_state *ls, struct rtw_regs *regs, int hwverid)
   2922 {
   2923 	uint8_t led_condition;
   2924 	bus_size_t ofs;
   2925 	uint8_t mask, newval, val;
   2926 
   2927 	led_condition = ls->ls_default;
   2928 
   2929 	if (ls->ls_state & RTW_LED_S_SLOW)
   2930 		led_condition ^= ls->ls_slowblink;
   2931 	if (ls->ls_state & (RTW_LED_S_RX | RTW_LED_S_TX))
   2932 		led_condition ^= ls->ls_actblink;
   2933 
   2934 	RTW_DPRINTF(RTW_DEBUG_LED,
   2935 	    ("%s: LED condition %" PRIx8 "\n", __func__, led_condition));
   2936 
   2937 	switch (hwverid) {
   2938 	default:
   2939 	case 'F':
   2940 		ofs = RTW_PSR;
   2941 		newval = mask = RTW_PSR_LEDGPO0 | RTW_PSR_LEDGPO1;
   2942 		if (led_condition & RTW_LED0)
   2943 			newval &= ~RTW_PSR_LEDGPO0;
   2944 		if (led_condition & RTW_LED1)
   2945 			newval &= ~RTW_PSR_LEDGPO1;
   2946 		break;
   2947 	case 'D':
   2948 		ofs = RTW_9346CR;
   2949 		mask = RTW_9346CR_EEM_MASK | RTW_9346CR_EEDI | RTW_9346CR_EECS;
   2950 		newval = RTW_9346CR_EEM_PROGRAM;
   2951 		if (led_condition & RTW_LED0)
   2952 			newval |= RTW_9346CR_EEDI;
   2953 		if (led_condition & RTW_LED1)
   2954 			newval |= RTW_9346CR_EECS;
   2955 		break;
   2956 	}
   2957 	val = RTW_READ8(regs, ofs);
   2958 	RTW_DPRINTF(RTW_DEBUG_LED,
   2959 	    ("%s: read %" PRIx8 " from reg[%#02" PRIxPTR "]\n", __func__, val,
   2960 	     (uintptr_t)ofs));
   2961 	val &= ~mask;
   2962 	val |= newval;
   2963 	RTW_WRITE8(regs, ofs, val);
   2964 	RTW_DPRINTF(RTW_DEBUG_LED,
   2965 	    ("%s: wrote %" PRIx8 " to reg[%#02" PRIxPTR "]\n", __func__, val,
   2966 	     (uintptr_t)ofs));
   2967 	RTW_SYNC(regs, ofs, ofs);
   2968 }
   2969 
   2970 static void
   2971 rtw_led_fastblink(void *arg)
   2972 {
   2973 	int ostate, s;
   2974 	struct rtw_softc *sc = (struct rtw_softc *)arg;
   2975 	struct rtw_led_state *ls = &sc->sc_led_state;
   2976 
   2977 	s = splnet();
   2978 	ostate = ls->ls_state;
   2979 	ls->ls_state ^= ls->ls_event;
   2980 
   2981 	if ((ls->ls_event & RTW_LED_S_TX) == 0)
   2982 		ls->ls_state &= ~RTW_LED_S_TX;
   2983 
   2984 	if ((ls->ls_event & RTW_LED_S_RX) == 0)
   2985 		ls->ls_state &= ~RTW_LED_S_RX;
   2986 
   2987 	ls->ls_event = 0;
   2988 
   2989 	if (ostate != ls->ls_state)
   2990 		rtw_led_set(ls, &sc->sc_regs, sc->sc_hwverid);
   2991 	splx(s);
   2992 
   2993 	aprint_debug_dev(sc->sc_dev, "scheduling fast blink\n");
   2994 	callout_schedule(&ls->ls_fast_ch, RTW_LED_FAST_TICKS);
   2995 }
   2996 
   2997 static void
   2998 rtw_led_slowblink(void *arg)
   2999 {
   3000 	int s;
   3001 	struct rtw_softc *sc = (struct rtw_softc *)arg;
   3002 	struct rtw_led_state *ls = &sc->sc_led_state;
   3003 
   3004 	s = splnet();
   3005 	ls->ls_state ^= RTW_LED_S_SLOW;
   3006 	rtw_led_set(ls, &sc->sc_regs, sc->sc_hwverid);
   3007 	splx(s);
   3008 	aprint_debug_dev(sc->sc_dev, "scheduling slow blink\n");
   3009 	callout_schedule(&ls->ls_slow_ch, RTW_LED_SLOW_TICKS);
   3010 }
   3011 
   3012 static void
   3013 rtw_led_detach(struct rtw_led_state *ls)
   3014 {
   3015 	callout_destroy(&ls->ls_fast_ch);
   3016 	callout_destroy(&ls->ls_slow_ch);
   3017 }
   3018 
   3019 static void
   3020 rtw_led_attach(struct rtw_led_state *ls, void *arg)
   3021 {
   3022 	callout_init(&ls->ls_fast_ch, 0);
   3023 	callout_init(&ls->ls_slow_ch, 0);
   3024 	callout_setfunc(&ls->ls_fast_ch, rtw_led_fastblink, arg);
   3025 	callout_setfunc(&ls->ls_slow_ch, rtw_led_slowblink, arg);
   3026 }
   3027 
   3028 static int
   3029 rtw_ioctl(struct ifnet *ifp, u_long cmd, void *data)
   3030 {
   3031 	int rc = 0, s;
   3032 	struct rtw_softc *sc = ifp->if_softc;
   3033 
   3034 	s = splnet();
   3035 	if (cmd == SIOCSIFFLAGS) {
   3036 		if ((rc = ifioctl_common(ifp, cmd, data)) != 0)
   3037 			;
   3038 		else switch (ifp->if_flags & (IFF_UP | IFF_RUNNING)) {
   3039 		case IFF_UP:
   3040 			rc = rtw_init(ifp);
   3041 			RTW_PRINT_REGS(&sc->sc_regs, ifp->if_xname, __func__);
   3042 			break;
   3043 		case IFF_UP | IFF_RUNNING:
   3044 			if (device_activation(sc->sc_dev, DEVACT_LEVEL_DRIVER))
   3045 				rtw_pktfilt_load(sc);
   3046 			RTW_PRINT_REGS(&sc->sc_regs, ifp->if_xname, __func__);
   3047 			break;
   3048 		case IFF_RUNNING:
   3049 			RTW_PRINT_REGS(&sc->sc_regs, ifp->if_xname, __func__);
   3050 			rtw_stop(ifp, 1);
   3051 			break;
   3052 		default:
   3053 			break;
   3054 		}
   3055 	} else if ((rc = ieee80211_ioctl(&sc->sc_ic, cmd, data)) != ENETRESET)
   3056 		;	/* nothing to do */
   3057 	else if (cmd == SIOCADDMULTI || cmd == SIOCDELMULTI) {
   3058 		/* reload packet filter if running */
   3059 		if (ifp->if_flags & IFF_RUNNING)
   3060 			rtw_pktfilt_load(sc);
   3061 		rc = 0;
   3062 	} else if ((ifp->if_flags & IFF_UP) != 0)
   3063 		rc = rtw_init(ifp);
   3064 	else
   3065 		rc = 0;
   3066 	splx(s);
   3067 	return rc;
   3068 }
   3069 
   3070 /* Select a transmit ring with at least one h/w and s/w descriptor free.
   3071  * Return 0 on success, -1 on failure.
   3072  */
   3073 static inline int
   3074 rtw_txring_choose(struct rtw_softc *sc, struct rtw_txsoft_blk **tsbp,
   3075     struct rtw_txdesc_blk **tdbp, int pri)
   3076 {
   3077 	struct rtw_txsoft_blk *tsb;
   3078 	struct rtw_txdesc_blk *tdb;
   3079 
   3080 	KASSERT(pri >= 0 && pri < RTW_NTXPRI);
   3081 
   3082 	tsb = &sc->sc_txsoft_blk[pri];
   3083 	tdb = &sc->sc_txdesc_blk[pri];
   3084 
   3085 	if (SIMPLEQ_EMPTY(&tsb->tsb_freeq) || tdb->tdb_nfree == 0) {
   3086 		if (tsb->tsb_tx_timer == 0)
   3087 			tsb->tsb_tx_timer = 5;
   3088 		*tsbp = NULL;
   3089 		*tdbp = NULL;
   3090 		return -1;
   3091 	}
   3092 	*tsbp = tsb;
   3093 	*tdbp = tdb;
   3094 	return 0;
   3095 }
   3096 
   3097 static inline struct mbuf *
   3098 rtw_80211_dequeue(struct rtw_softc *sc, struct ifqueue *ifq, int pri,
   3099     struct rtw_txsoft_blk **tsbp, struct rtw_txdesc_blk **tdbp,
   3100     struct ieee80211_node **nip, short *if_flagsp)
   3101 {
   3102 	struct mbuf *m;
   3103 
   3104 	if (IF_IS_EMPTY(ifq))
   3105 		return NULL;
   3106 	if (rtw_txring_choose(sc, tsbp, tdbp, pri) == -1) {
   3107 		DPRINTF(sc, RTW_DEBUG_XMIT_RSRC, ("%s: no ring %d descriptor\n",
   3108 		    __func__, pri));
   3109 		*if_flagsp |= IFF_OACTIVE;
   3110 		sc->sc_if.if_timer = 1;
   3111 		return NULL;
   3112 	}
   3113 	IF_DEQUEUE(ifq, m);
   3114 	*nip = M_GETCTX(m, struct ieee80211_node *);
   3115 	M_SETCTX(m, NULL);
   3116 	KASSERT(*nip != NULL);
   3117 	return m;
   3118 }
   3119 
   3120 /* Point *mp at the next 802.11 frame to transmit.  Point *tsbp
   3121  * at the driver's selection of transmit control block for the packet.
   3122  */
   3123 static inline int
   3124 rtw_dequeue(struct ifnet *ifp, struct rtw_txsoft_blk **tsbp,
   3125     struct rtw_txdesc_blk **tdbp, struct mbuf **mp,
   3126     struct ieee80211_node **nip)
   3127 {
   3128 	int pri;
   3129 	struct ether_header *eh;
   3130 	struct mbuf *m0;
   3131 	struct rtw_softc *sc;
   3132 	short *if_flagsp;
   3133 
   3134 	*mp = NULL;
   3135 
   3136 	sc = (struct rtw_softc *)ifp->if_softc;
   3137 
   3138 	DPRINTF(sc, RTW_DEBUG_XMIT,
   3139 	    ("%s: enter %s\n", device_xname(sc->sc_dev), __func__));
   3140 
   3141 	if_flagsp = &ifp->if_flags;
   3142 
   3143 	if (sc->sc_ic.ic_state == IEEE80211_S_RUN &&
   3144 	    (*mp = rtw_80211_dequeue(sc, &sc->sc_beaconq, RTW_TXPRIBCN, tsbp,
   3145 				     tdbp, nip, if_flagsp)) != NULL) {
   3146 		DPRINTF(sc, RTW_DEBUG_XMIT, ("%s: dequeue beacon frame\n",
   3147 		    __func__));
   3148 		return 0;
   3149 	}
   3150 
   3151 	if ((*mp = rtw_80211_dequeue(sc, &sc->sc_ic.ic_mgtq, RTW_TXPRIMD, tsbp,
   3152 				     tdbp, nip, if_flagsp)) != NULL) {
   3153 		DPRINTF(sc, RTW_DEBUG_XMIT, ("%s: dequeue mgt frame\n",
   3154 		    __func__));
   3155 		return 0;
   3156 	}
   3157 
   3158 	if (sc->sc_ic.ic_state != IEEE80211_S_RUN) {
   3159 		DPRINTF(sc, RTW_DEBUG_XMIT, ("%s: not running\n", __func__));
   3160 		return 0;
   3161 	}
   3162 
   3163 	IFQ_POLL(&ifp->if_snd, m0);
   3164 	if (m0 == NULL) {
   3165 		DPRINTF(sc, RTW_DEBUG_XMIT, ("%s: no frame ready\n",
   3166 		    __func__));
   3167 		return 0;
   3168 	}
   3169 
   3170 	pri = ((m0->m_flags & M_PWR_SAV) != 0) ? RTW_TXPRIHI : RTW_TXPRIMD;
   3171 
   3172 	if (rtw_txring_choose(sc, tsbp, tdbp, pri) == -1) {
   3173 		DPRINTF(sc, RTW_DEBUG_XMIT_RSRC, ("%s: no ring %d descriptor\n",
   3174 		    __func__, pri));
   3175 		*if_flagsp |= IFF_OACTIVE;
   3176 		sc->sc_if.if_timer = 1;
   3177 		return 0;
   3178 	}
   3179 
   3180 	IFQ_DEQUEUE(&ifp->if_snd, m0);
   3181 	if (m0 == NULL) {
   3182 		DPRINTF(sc, RTW_DEBUG_XMIT, ("%s: no frame ready\n",
   3183 		    __func__));
   3184 		return 0;
   3185 	}
   3186 	DPRINTF(sc, RTW_DEBUG_XMIT, ("%s: dequeue data frame\n", __func__));
   3187 	ifp->if_opackets++;
   3188 	bpf_mtap(ifp, m0, BPF_D_OUT);
   3189 	eh = mtod(m0, struct ether_header *);
   3190 	*nip = ieee80211_find_txnode(&sc->sc_ic, eh->ether_dhost);
   3191 	if (*nip == NULL) {
   3192 		/* NB: ieee80211_find_txnode does stat+msg */
   3193 		m_freem(m0);
   3194 		return -1;
   3195 	}
   3196 	if ((m0 = ieee80211_encap(&sc->sc_ic, m0, *nip)) == NULL) {
   3197 		DPRINTF(sc, RTW_DEBUG_XMIT, ("%s: encap error\n", __func__));
   3198 		ifp->if_oerrors++;
   3199 		return -1;
   3200 	}
   3201 	DPRINTF(sc, RTW_DEBUG_XMIT, ("%s: leave\n", __func__));
   3202 	*mp = m0;
   3203 	return 0;
   3204 }
   3205 
   3206 static int
   3207 rtw_seg_too_short(bus_dmamap_t dmamap)
   3208 {
   3209 	int i;
   3210 	for (i = 0; i < dmamap->dm_nsegs; i++) {
   3211 		if (dmamap->dm_segs[i].ds_len < 4)
   3212 			return 1;
   3213 	}
   3214 	return 0;
   3215 }
   3216 
   3217 /* TBD factor with atw_start */
   3218 static struct mbuf *
   3219 rtw_dmamap_load_txbuf(bus_dma_tag_t dmat, bus_dmamap_t dmam, struct mbuf *chain,
   3220     u_int ndescfree, device_t dev)
   3221 {
   3222 	int first, rc;
   3223 	struct mbuf *m, *m0;
   3224 
   3225 	m0 = chain;
   3226 
   3227 	/*
   3228 	 * Load the DMA map.  Copy and try (once) again if the packet
   3229 	 * didn't fit in the alloted number of segments.
   3230 	 */
   3231 	for (first = 1;
   3232 	     ((rc = bus_dmamap_load_mbuf(dmat, dmam, m0,
   3233 			  BUS_DMA_WRITE | BUS_DMA_NOWAIT)) != 0 ||
   3234 	      dmam->dm_nsegs > ndescfree || rtw_seg_too_short(dmam)) && first;
   3235 	     first = 0) {
   3236 		if (rc == 0) {
   3237 #ifdef RTW_DIAGxxx
   3238 			if (rtw_seg_too_short(dmam)) {
   3239 				printf("%s: short segment, mbuf lengths:", __func__);
   3240 				for (m = m0; m; m = m->m_next)
   3241 					printf(" %d", m->m_len);
   3242 				printf("\n");
   3243 			}
   3244 #endif
   3245 			bus_dmamap_unload(dmat, dmam);
   3246 		}
   3247 		MGETHDR(m, M_DONTWAIT, MT_DATA);
   3248 		if (m == NULL) {
   3249 			aprint_error_dev(dev, "unable to allocate Tx mbuf\n");
   3250 			break;
   3251 		}
   3252 		if (m0->m_pkthdr.len > MHLEN) {
   3253 			MCLGET(m, M_DONTWAIT);
   3254 			if ((m->m_flags & M_EXT) == 0) {
   3255 				aprint_error_dev(dev,
   3256 				    "cannot allocate Tx cluster\n");
   3257 				m_freem(m);
   3258 				break;
   3259 			}
   3260 		}
   3261 		m_copydata(m0, 0, m0->m_pkthdr.len, mtod(m, void *));
   3262 		m->m_pkthdr.len = m->m_len = m0->m_pkthdr.len;
   3263 		m_freem(m0);
   3264 		m0 = m;
   3265 		m = NULL;
   3266 	}
   3267 	if (rc != 0) {
   3268 		aprint_error_dev(dev, "cannot load Tx buffer, rc = %d\n", rc);
   3269 		m_freem(m0);
   3270 		return NULL;
   3271 	} else if (rtw_seg_too_short(dmam)) {
   3272 		aprint_error_dev(dev,
   3273 		    "cannot load Tx buffer, segment too short\n");
   3274 		bus_dmamap_unload(dmat, dmam);
   3275 		m_freem(m0);
   3276 		return NULL;
   3277 	} else if (dmam->dm_nsegs > ndescfree) {
   3278 		aprint_error_dev(dev, "too many tx segments\n");
   3279 		bus_dmamap_unload(dmat, dmam);
   3280 		m_freem(m0);
   3281 		return NULL;
   3282 	}
   3283 	return m0;
   3284 }
   3285 
   3286 #ifdef RTW_DEBUG
   3287 static void
   3288 rtw_print_txdesc(struct rtw_softc *sc, const char *action,
   3289     struct rtw_txsoft *ts, struct rtw_txdesc_blk *tdb, int desc)
   3290 {
   3291 	struct rtw_txdesc *td = &tdb->tdb_desc[desc];
   3292 	DPRINTF(sc, RTW_DEBUG_XMIT_DESC, ("%s: %p %s txdesc[%d] next %#08x "
   3293 	    "buf %#08x ctl0 %#08x ctl1 %#08x len %#08x\n",
   3294 	    device_xname(sc->sc_dev), ts, action, desc,
   3295 	    le32toh(td->td_buf), le32toh(td->td_next),
   3296 	    le32toh(td->td_ctl0), le32toh(td->td_ctl1),
   3297 	    le32toh(td->td_len)));
   3298 }
   3299 #endif /* RTW_DEBUG */
   3300 
   3301 static void
   3302 rtw_start(struct ifnet *ifp)
   3303 {
   3304 	int desc, i, lastdesc, npkt, rate;
   3305 	uint32_t proto_ctl0, ctl0, ctl1;
   3306 	bus_dmamap_t		dmamap;
   3307 	struct ieee80211com	*ic;
   3308 	struct ieee80211_duration *d0;
   3309 	struct ieee80211_frame_min	*wh;
   3310 	struct ieee80211_node	*ni = NULL;	/* XXX: GCC */
   3311 	struct mbuf		*m0;
   3312 	struct rtw_softc	*sc;
   3313 	struct rtw_txsoft_blk	*tsb = NULL;	/* XXX: GCC */
   3314 	struct rtw_txdesc_blk	*tdb = NULL;	/* XXX: GCC */
   3315 	struct rtw_txsoft	*ts;
   3316 	struct rtw_txdesc	*td;
   3317 	struct ieee80211_key	*k;
   3318 
   3319 	sc = (struct rtw_softc *)ifp->if_softc;
   3320 	ic = &sc->sc_ic;
   3321 
   3322 	DPRINTF(sc, RTW_DEBUG_XMIT,
   3323 	    ("%s: enter %s\n", device_xname(sc->sc_dev), __func__));
   3324 
   3325 	if ((ifp->if_flags & (IFF_RUNNING | IFF_OACTIVE)) != IFF_RUNNING)
   3326 		goto out;
   3327 
   3328 	/* XXX do real rate control */
   3329 	proto_ctl0 = RTW_TXCTL0_RTSRATE_1MBPS;
   3330 
   3331 	if ((ic->ic_flags & IEEE80211_F_SHPREAMBLE) != 0)
   3332 		proto_ctl0 |= RTW_TXCTL0_SPLCP;
   3333 
   3334 	for (;;) {
   3335 		if (rtw_dequeue(ifp, &tsb, &tdb, &m0, &ni) == -1)
   3336 			continue;
   3337 		if (m0 == NULL)
   3338 			break;
   3339 
   3340 		wh = mtod(m0, struct ieee80211_frame_min *);
   3341 
   3342 		if ((wh->i_fc[1] & IEEE80211_FC1_WEP) != 0 &&
   3343 		    (k = ieee80211_crypto_encap(ic, ni, m0)) == NULL) {
   3344 			m_freem(m0);
   3345 			break;
   3346 		} else
   3347 			k = NULL;
   3348 
   3349 		ts = SIMPLEQ_FIRST(&tsb->tsb_freeq);
   3350 
   3351 		dmamap = ts->ts_dmamap;
   3352 
   3353 		m0 = rtw_dmamap_load_txbuf(sc->sc_dmat, dmamap, m0,
   3354 		    tdb->tdb_nfree, sc->sc_dev);
   3355 
   3356 		if (m0 == NULL || dmamap->dm_nsegs == 0) {
   3357 			DPRINTF(sc, RTW_DEBUG_XMIT,
   3358 			    ("%s: fail dmamap load\n", __func__));
   3359 			goto post_dequeue_err;
   3360 		}
   3361 
   3362 		/* Note well: rtw_dmamap_load_txbuf may have created
   3363 		 * a new chain, so we must find the header once
   3364 		 * more.
   3365 		 */
   3366 		wh = mtod(m0, struct ieee80211_frame_min *);
   3367 
   3368 		/* XXX do real rate control */
   3369 		if ((wh->i_fc[0] & IEEE80211_FC0_TYPE_MASK) ==
   3370 		    IEEE80211_FC0_TYPE_MGT)
   3371 			rate = 2;
   3372 		else
   3373 			rate = MAX(2, ieee80211_get_rate(ni));
   3374 
   3375 #ifdef RTW_DEBUG
   3376 		if ((ifp->if_flags & (IFF_DEBUG | IFF_LINK2)) ==
   3377 		    (IFF_DEBUG | IFF_LINK2)) {
   3378 			ieee80211_dump_pkt(mtod(m0, uint8_t *),
   3379 			    (dmamap->dm_nsegs == 1) ? m0->m_pkthdr.len
   3380 						    : sizeof(wh),
   3381 			    rate, 0);
   3382 		}
   3383 #endif /* RTW_DEBUG */
   3384 		ctl0 = proto_ctl0 |
   3385 		    __SHIFTIN(m0->m_pkthdr.len, RTW_TXCTL0_TPKTSIZE_MASK);
   3386 
   3387 		switch (rate) {
   3388 		default:
   3389 		case 2:
   3390 			ctl0 |= RTW_TXCTL0_RATE_1MBPS;
   3391 			break;
   3392 		case 4:
   3393 			ctl0 |= RTW_TXCTL0_RATE_2MBPS;
   3394 			break;
   3395 		case 11:
   3396 			ctl0 |= RTW_TXCTL0_RATE_5MBPS;
   3397 			break;
   3398 		case 22:
   3399 			ctl0 |= RTW_TXCTL0_RATE_11MBPS;
   3400 			break;
   3401 		}
   3402 		/* XXX >= ? Compare after fragmentation? */
   3403 		if (m0->m_pkthdr.len > ic->ic_rtsthreshold)
   3404 			ctl0 |= RTW_TXCTL0_RTSEN;
   3405 
   3406 		/* XXX Sometimes writes a bogus keyid; h/w doesn't
   3407 		 * seem to care, since we don't activate h/w Tx
   3408 		 * encryption.
   3409 		 */
   3410 		if (k != NULL &&
   3411 		    k->wk_cipher->ic_cipher == IEEE80211_CIPHER_WEP) {
   3412 			ctl0 |= __SHIFTIN(k->wk_keyix, RTW_TXCTL0_KEYID_MASK) &
   3413 			    RTW_TXCTL0_KEYID_MASK;
   3414 		}
   3415 
   3416 		if ((wh->i_fc[0] & IEEE80211_FC0_TYPE_MASK) ==
   3417 		    IEEE80211_FC0_TYPE_MGT) {
   3418 			ctl0 &= ~(RTW_TXCTL0_SPLCP | RTW_TXCTL0_RTSEN);
   3419 			if ((wh->i_fc[0] & IEEE80211_FC0_SUBTYPE_MASK) ==
   3420 			    IEEE80211_FC0_SUBTYPE_BEACON)
   3421 				ctl0 |= RTW_TXCTL0_BEACON;
   3422 		}
   3423 
   3424 		if (ieee80211_compute_duration(wh, k, m0->m_pkthdr.len,
   3425 		    ic->ic_flags, ic->ic_fragthreshold,
   3426 		    rate, &ts->ts_d0, &ts->ts_dn, &npkt,
   3427 		    (ifp->if_flags & (IFF_DEBUG | IFF_LINK2)) ==
   3428 		    (IFF_DEBUG | IFF_LINK2)) == -1) {
   3429 			DPRINTF(sc, RTW_DEBUG_XMIT,
   3430 			    ("%s: fail compute duration\n", __func__));
   3431 			goto post_load_err;
   3432 		}
   3433 
   3434 		d0 = &ts->ts_d0;
   3435 
   3436 		*(uint16_t*)wh->i_dur = htole16(d0->d_data_dur);
   3437 
   3438 		ctl1 = __SHIFTIN(d0->d_plcp_len, RTW_TXCTL1_LENGTH_MASK) |
   3439 		    __SHIFTIN(d0->d_rts_dur, RTW_TXCTL1_RTSDUR_MASK);
   3440 
   3441 		if (d0->d_residue)
   3442 			ctl1 |= RTW_TXCTL1_LENGEXT;
   3443 
   3444 		/* TBD fragmentation */
   3445 
   3446 		ts->ts_first = tdb->tdb_next;
   3447 
   3448 		rtw_txdescs_sync(tdb, ts->ts_first, dmamap->dm_nsegs,
   3449 		    BUS_DMASYNC_PREWRITE);
   3450 
   3451 		KASSERT(ts->ts_first < tdb->tdb_ndesc);
   3452 
   3453 		bpf_mtap3(ic->ic_rawbpf, m0, BPF_D_OUT);
   3454 
   3455 		if (sc->sc_radiobpf != NULL) {
   3456 			struct rtw_tx_radiotap_header *rt = &sc->sc_txtap;
   3457 
   3458 			rt->rt_rate = rate;
   3459 
   3460 			bpf_mtap2(sc->sc_radiobpf, rt, sizeof(sc->sc_txtapu),
   3461 			    m0, BPF_D_OUT);
   3462 		}
   3463 
   3464 		for (i = 0, lastdesc = desc = ts->ts_first;
   3465 		     i < dmamap->dm_nsegs;
   3466 		     i++, desc = RTW_NEXT_IDX(tdb, desc)) {
   3467 			if (dmamap->dm_segs[i].ds_len > RTW_TXLEN_LENGTH_MASK) {
   3468 				DPRINTF(sc, RTW_DEBUG_XMIT_DESC,
   3469 				    ("%s: seg too long\n", __func__));
   3470 				goto post_load_err;
   3471 			}
   3472 			td = &tdb->tdb_desc[desc];
   3473 			td->td_ctl0 = htole32(ctl0);
   3474 			td->td_ctl1 = htole32(ctl1);
   3475 			td->td_buf = htole32(dmamap->dm_segs[i].ds_addr);
   3476 			td->td_len = htole32(dmamap->dm_segs[i].ds_len);
   3477 			td->td_next = htole32(RTW_NEXT_DESC(tdb, desc));
   3478 			if (i != 0)
   3479 				td->td_ctl0 |= htole32(RTW_TXCTL0_OWN);
   3480 			lastdesc = desc;
   3481 #ifdef RTW_DEBUG
   3482 			rtw_print_txdesc(sc, "load", ts, tdb, desc);
   3483 #endif /* RTW_DEBUG */
   3484 		}
   3485 
   3486 		KASSERT(desc < tdb->tdb_ndesc);
   3487 
   3488 		ts->ts_ni = ni;
   3489 		KASSERT(ni != NULL);
   3490 		ts->ts_mbuf = m0;
   3491 		ts->ts_last = lastdesc;
   3492 		tdb->tdb_desc[ts->ts_last].td_ctl0 |= htole32(RTW_TXCTL0_LS);
   3493 		tdb->tdb_desc[ts->ts_first].td_ctl0 |=
   3494 		   htole32(RTW_TXCTL0_FS);
   3495 
   3496 #ifdef RTW_DEBUG
   3497 		rtw_print_txdesc(sc, "FS on", ts, tdb, ts->ts_first);
   3498 		rtw_print_txdesc(sc, "LS on", ts, tdb, ts->ts_last);
   3499 #endif /* RTW_DEBUG */
   3500 
   3501 		tdb->tdb_nfree -= dmamap->dm_nsegs;
   3502 		tdb->tdb_next = desc;
   3503 
   3504 		rtw_txdescs_sync(tdb, ts->ts_first, dmamap->dm_nsegs,
   3505 		    BUS_DMASYNC_PREREAD | BUS_DMASYNC_PREWRITE);
   3506 
   3507 		tdb->tdb_desc[ts->ts_first].td_ctl0 |=
   3508 		    htole32(RTW_TXCTL0_OWN);
   3509 
   3510 #ifdef RTW_DEBUG
   3511 		rtw_print_txdesc(sc, "OWN on", ts, tdb, ts->ts_first);
   3512 #endif /* RTW_DEBUG */
   3513 
   3514 		rtw_txdescs_sync(tdb, ts->ts_first, 1,
   3515 		    BUS_DMASYNC_PREREAD | BUS_DMASYNC_PREWRITE);
   3516 
   3517 		SIMPLEQ_REMOVE_HEAD(&tsb->tsb_freeq, ts_q);
   3518 		SIMPLEQ_INSERT_TAIL(&tsb->tsb_dirtyq, ts, ts_q);
   3519 
   3520 		if (tsb != &sc->sc_txsoft_blk[RTW_TXPRIBCN])
   3521 			sc->sc_led_state.ls_event |= RTW_LED_S_TX;
   3522 		tsb->tsb_tx_timer = 5;
   3523 		ifp->if_timer = 1;
   3524 		rtw_tx_kick(&sc->sc_regs, tsb->tsb_poll);
   3525 	}
   3526 out:
   3527 	DPRINTF(sc, RTW_DEBUG_XMIT, ("%s: leave\n", __func__));
   3528 	return;
   3529 post_load_err:
   3530 	bus_dmamap_unload(sc->sc_dmat, dmamap);
   3531 	m_freem(m0);
   3532 post_dequeue_err:
   3533 	ieee80211_free_node(ni);
   3534 	return;
   3535 }
   3536 
   3537 static void
   3538 rtw_idle(struct rtw_regs *regs)
   3539 {
   3540 	int active;
   3541 	uint8_t tppoll;
   3542 
   3543 	/* request stop DMA; wait for packets to stop transmitting. */
   3544 
   3545 	RTW_WRITE8(regs, RTW_TPPOLL, RTW_TPPOLL_SALL);
   3546 	RTW_WBR(regs, RTW_TPPOLL, RTW_TPPOLL);
   3547 
   3548 	for (active = 0; active < 300 &&
   3549 	     (tppoll = RTW_READ8(regs, RTW_TPPOLL) & RTW_TPPOLL_ACTIVE) != 0;
   3550 	     active++)
   3551 		DELAY(10);
   3552 	printf("%s: transmit DMA idle in %dus, tppoll %02" PRIx8 "\n", __func__,
   3553 	    active * 10, tppoll);
   3554 }
   3555 
   3556 static void
   3557 rtw_watchdog(struct ifnet *ifp)
   3558 {
   3559 	int pri, tx_timeouts = 0;
   3560 	struct rtw_softc *sc;
   3561 	struct rtw_txsoft_blk *tsb;
   3562 
   3563 	sc = ifp->if_softc;
   3564 
   3565 	ifp->if_timer = 0;
   3566 
   3567 	if (!device_is_active(sc->sc_dev))
   3568 		return;
   3569 
   3570 	for (pri = 0; pri < RTW_NTXPRI; pri++) {
   3571 		tsb = &sc->sc_txsoft_blk[pri];
   3572 
   3573 		if (tsb->tsb_tx_timer == 0)
   3574 			continue;
   3575 		else if (--tsb->tsb_tx_timer == 0) {
   3576 			if (SIMPLEQ_EMPTY(&tsb->tsb_dirtyq))
   3577 				continue;
   3578 			else if (rtw_collect_txring(sc, tsb,
   3579 			    &sc->sc_txdesc_blk[pri], 0))
   3580 				continue;
   3581 			printf("%s: transmit timeout, priority %d\n",
   3582 			    ifp->if_xname, pri);
   3583 			ifp->if_oerrors++;
   3584 			if (pri != RTW_TXPRIBCN)
   3585 				tx_timeouts++;
   3586 		} else
   3587 			ifp->if_timer = 1;
   3588 	}
   3589 
   3590 	if (tx_timeouts > 0) {
   3591 		/* Stop Tx DMA, disable xmtr, flush Tx rings, enable xmtr,
   3592 		 * reset s/w tx-ring pointers, and start transmission.
   3593 		 *
   3594 		 * TBD Stop/restart just the broken rings?
   3595 		 */
   3596 		rtw_idle(&sc->sc_regs);
   3597 		rtw_io_enable(sc, RTW_CR_RE | RTW_CR_TE, 0);
   3598 		rtw_txdescs_reset(sc);
   3599 		rtw_io_enable(sc, RTW_CR_RE | RTW_CR_TE, 1);
   3600 		rtw_start(ifp);
   3601 	}
   3602 	ieee80211_watchdog(&sc->sc_ic);
   3603 	return;
   3604 }
   3605 
   3606 static void
   3607 rtw_next_scan(void *arg)
   3608 {
   3609 	struct ieee80211com *ic = arg;
   3610 	int s;
   3611 
   3612 	/* don't call rtw_start w/o network interrupts blocked */
   3613 	s = splnet();
   3614 	if (ic->ic_state == IEEE80211_S_SCAN)
   3615 		ieee80211_next_scan(ic);
   3616 	splx(s);
   3617 }
   3618 
   3619 static void
   3620 rtw_join_bss(struct rtw_softc *sc, uint8_t *bssid, uint16_t intval0)
   3621 {
   3622 	uint16_t bcnitv, bintritv, intval;
   3623 	int i;
   3624 	struct rtw_regs *regs = &sc->sc_regs;
   3625 
   3626 	for (i = 0; i < IEEE80211_ADDR_LEN; i++)
   3627 		RTW_WRITE8(regs, RTW_BSSID + i, bssid[i]);
   3628 
   3629 	RTW_SYNC(regs, RTW_BSSID16, RTW_BSSID32);
   3630 
   3631 	rtw_set_access(regs, RTW_ACCESS_CONFIG);
   3632 
   3633 	intval = MIN(intval0, __SHIFTOUT_MASK(RTW_BCNITV_BCNITV_MASK));
   3634 
   3635 	bcnitv = RTW_READ16(regs, RTW_BCNITV) & ~RTW_BCNITV_BCNITV_MASK;
   3636 	bcnitv |= __SHIFTIN(intval, RTW_BCNITV_BCNITV_MASK);
   3637 	RTW_WRITE16(regs, RTW_BCNITV, bcnitv);
   3638 	/* interrupt host 1ms before the TBTT */
   3639 	bintritv = RTW_READ16(regs, RTW_BINTRITV) & ~RTW_BINTRITV_BINTRITV;
   3640 	bintritv |= __SHIFTIN(1000, RTW_BINTRITV_BINTRITV);
   3641 	RTW_WRITE16(regs, RTW_BINTRITV, bintritv);
   3642 	/* magic from Linux */
   3643 	RTW_WRITE16(regs, RTW_ATIMWND, __SHIFTIN(1, RTW_ATIMWND_ATIMWND));
   3644 	RTW_WRITE16(regs, RTW_ATIMTRITV, __SHIFTIN(2, RTW_ATIMTRITV_ATIMTRITV));
   3645 	rtw_set_access(regs, RTW_ACCESS_NONE);
   3646 
   3647 	rtw_io_enable(sc, RTW_CR_RE | RTW_CR_TE, 1);
   3648 }
   3649 
   3650 /* Synchronize the hardware state with the software state. */
   3651 static int
   3652 rtw_newstate(struct ieee80211com *ic, enum ieee80211_state nstate, int arg)
   3653 {
   3654 	struct ifnet *ifp = ic->ic_ifp;
   3655 	struct rtw_softc *sc = (struct rtw_softc *)ifp->if_softc;
   3656 	enum ieee80211_state ostate;
   3657 	int error;
   3658 
   3659 	ostate = ic->ic_state;
   3660 
   3661 	aprint_debug_dev(sc->sc_dev, "%s: l.%d\n", __func__, __LINE__);
   3662 	rtw_led_newstate(sc, nstate);
   3663 
   3664 	aprint_debug_dev(sc->sc_dev, "%s: l.%d\n", __func__, __LINE__);
   3665 	if (nstate == IEEE80211_S_INIT) {
   3666 		callout_stop(&sc->sc_scan_ch);
   3667 		sc->sc_cur_chan = IEEE80211_CHAN_ANY;
   3668 		return (*sc->sc_mtbl.mt_newstate)(ic, nstate, arg);
   3669 	}
   3670 
   3671 	if (ostate == IEEE80211_S_INIT && nstate != IEEE80211_S_INIT)
   3672 		rtw_pwrstate(sc, RTW_ON);
   3673 
   3674 	if ((error = rtw_tune(sc)) != 0)
   3675 		return error;
   3676 
   3677 	switch (nstate) {
   3678 	case IEEE80211_S_INIT:
   3679 		panic("%s: unexpected state IEEE80211_S_INIT\n", __func__);
   3680 		break;
   3681 	case IEEE80211_S_SCAN:
   3682 		if (ostate != IEEE80211_S_SCAN) {
   3683 			(void)memset(ic->ic_bss->ni_bssid, 0,
   3684 			    IEEE80211_ADDR_LEN);
   3685 			rtw_set_nettype(sc, IEEE80211_M_MONITOR);
   3686 		}
   3687 
   3688 		callout_reset(&sc->sc_scan_ch, rtw_dwelltime * hz / 1000,
   3689 		    rtw_next_scan, ic);
   3690 
   3691 		break;
   3692 	case IEEE80211_S_RUN:
   3693 		switch (ic->ic_opmode) {
   3694 		case IEEE80211_M_HOSTAP:
   3695 		case IEEE80211_M_IBSS:
   3696 			rtw_set_nettype(sc, IEEE80211_M_MONITOR);
   3697 			/*FALLTHROUGH*/
   3698 		case IEEE80211_M_AHDEMO:
   3699 		case IEEE80211_M_STA:
   3700 			rtw_join_bss(sc, ic->ic_bss->ni_bssid,
   3701 			    ic->ic_bss->ni_intval);
   3702 			break;
   3703 		case IEEE80211_M_MONITOR:
   3704 			break;
   3705 		}
   3706 		rtw_set_nettype(sc, ic->ic_opmode);
   3707 		break;
   3708 	case IEEE80211_S_ASSOC:
   3709 	case IEEE80211_S_AUTH:
   3710 		break;
   3711 	}
   3712 
   3713 	if (nstate != IEEE80211_S_SCAN)
   3714 		callout_stop(&sc->sc_scan_ch);
   3715 
   3716 	return (*sc->sc_mtbl.mt_newstate)(ic, nstate, arg);
   3717 }
   3718 
   3719 /* Extend a 32-bit TSF timestamp to a 64-bit timestamp. */
   3720 static uint64_t
   3721 rtw_tsf_extend(struct rtw_regs *regs, uint32_t rstamp)
   3722 {
   3723 	uint32_t tsftl, tsfth;
   3724 
   3725 	tsfth = RTW_READ(regs, RTW_TSFTRH);
   3726 	tsftl = RTW_READ(regs, RTW_TSFTRL);
   3727 	if (tsftl < rstamp)	/* Compensate for rollover. */
   3728 		tsfth--;
   3729 	return ((uint64_t)tsfth << 32) | rstamp;
   3730 }
   3731 
   3732 static void
   3733 rtw_recv_mgmt(struct ieee80211com *ic, struct mbuf *m,
   3734     struct ieee80211_node *ni, int subtype, int rssi, uint32_t rstamp)
   3735 {
   3736 	struct ifnet *ifp = ic->ic_ifp;
   3737 	struct rtw_softc *sc = (struct rtw_softc *)ifp->if_softc;
   3738 
   3739 	(*sc->sc_mtbl.mt_recv_mgmt)(ic, m, ni, subtype, rssi, rstamp);
   3740 
   3741 	switch (subtype) {
   3742 	case IEEE80211_FC0_SUBTYPE_PROBE_RESP:
   3743 	case IEEE80211_FC0_SUBTYPE_BEACON:
   3744 		if (ic->ic_opmode == IEEE80211_M_IBSS &&
   3745 		    ic->ic_state == IEEE80211_S_RUN &&
   3746 		    device_is_active(sc->sc_dev)) {
   3747 			uint64_t tsf = rtw_tsf_extend(&sc->sc_regs, rstamp);
   3748 			if (le64toh(ni->ni_tstamp.tsf) >= tsf)
   3749 				(void)ieee80211_ibss_merge(ni);
   3750 		}
   3751 		break;
   3752 	default:
   3753 		break;
   3754 	}
   3755 	return;
   3756 }
   3757 
   3758 static struct ieee80211_node *
   3759 rtw_node_alloc(struct ieee80211_node_table *nt)
   3760 {
   3761 	struct ifnet *ifp = nt->nt_ic->ic_ifp;
   3762 	struct rtw_softc *sc = (struct rtw_softc *)ifp->if_softc;
   3763 	struct ieee80211_node *ni = (*sc->sc_mtbl.mt_node_alloc)(nt);
   3764 
   3765 	DPRINTF(sc, RTW_DEBUG_NODE,
   3766 	    ("%s: alloc node %p\n", device_xname(sc->sc_dev), ni));
   3767 	return ni;
   3768 }
   3769 
   3770 static void
   3771 rtw_node_free(struct ieee80211_node *ni)
   3772 {
   3773 	struct ieee80211com *ic = ni->ni_ic;
   3774 	struct ifnet *ifp = ic->ic_ifp;
   3775 	struct rtw_softc *sc = (struct rtw_softc *)ifp->if_softc;
   3776 
   3777 	DPRINTF(sc, RTW_DEBUG_NODE,
   3778 	    ("%s: freeing node %p %s\n", device_xname(sc->sc_dev), ni,
   3779 	    ether_sprintf(ni->ni_bssid)));
   3780 	(*sc->sc_mtbl.mt_node_free)(ni);
   3781 }
   3782 
   3783 static int
   3784 rtw_media_change(struct ifnet *ifp)
   3785 {
   3786 	int error;
   3787 
   3788 	error = ieee80211_media_change(ifp);
   3789 	if (error == ENETRESET) {
   3790 		if ((ifp->if_flags & (IFF_RUNNING | IFF_UP)) ==
   3791 		    (IFF_RUNNING | IFF_UP))
   3792 			rtw_init(ifp);		/* XXX lose error */
   3793 		error = 0;
   3794 	}
   3795 	return error;
   3796 }
   3797 
   3798 static void
   3799 rtw_media_status(struct ifnet *ifp, struct ifmediareq *imr)
   3800 {
   3801 	struct rtw_softc *sc = ifp->if_softc;
   3802 
   3803 	if (!device_is_active(sc->sc_dev)) {
   3804 		imr->ifm_active = IFM_IEEE80211 | IFM_NONE;
   3805 		imr->ifm_status = 0;
   3806 		return;
   3807 	}
   3808 	ieee80211_media_status(ifp, imr);
   3809 }
   3810 
   3811 static inline void
   3812 rtw_setifprops(struct ifnet *ifp, const char *dvname, void *softc)
   3813 {
   3814 	(void)strlcpy(ifp->if_xname, dvname, IFNAMSIZ);
   3815 	ifp->if_softc = softc;
   3816 	ifp->if_flags = IFF_SIMPLEX | IFF_BROADCAST | IFF_MULTICAST;
   3817 	ifp->if_ioctl = rtw_ioctl;
   3818 	ifp->if_start = rtw_start;
   3819 	ifp->if_watchdog = rtw_watchdog;
   3820 	ifp->if_init = rtw_init;
   3821 	ifp->if_stop = rtw_stop;
   3822 }
   3823 
   3824 static inline void
   3825 rtw_set80211props(struct ieee80211com *ic)
   3826 {
   3827 	int nrate;
   3828 	ic->ic_phytype = IEEE80211_T_DS;
   3829 	ic->ic_opmode = IEEE80211_M_STA;
   3830 	ic->ic_caps = IEEE80211_C_PMGT | IEEE80211_C_IBSS |
   3831 	    IEEE80211_C_HOSTAP | IEEE80211_C_MONITOR | IEEE80211_C_WEP;
   3832 
   3833 	nrate = 0;
   3834 	ic->ic_sup_rates[IEEE80211_MODE_11B].rs_rates[nrate++] =
   3835 	    IEEE80211_RATE_BASIC | 2;
   3836 	ic->ic_sup_rates[IEEE80211_MODE_11B].rs_rates[nrate++] =
   3837 	    IEEE80211_RATE_BASIC | 4;
   3838 	ic->ic_sup_rates[IEEE80211_MODE_11B].rs_rates[nrate++] = 11;
   3839 	ic->ic_sup_rates[IEEE80211_MODE_11B].rs_rates[nrate++] = 22;
   3840 	ic->ic_sup_rates[IEEE80211_MODE_11B].rs_nrates = nrate;
   3841 }
   3842 
   3843 static inline void
   3844 rtw_set80211methods(struct rtw_mtbl *mtbl, struct ieee80211com *ic)
   3845 {
   3846 	mtbl->mt_newstate = ic->ic_newstate;
   3847 	ic->ic_newstate = rtw_newstate;
   3848 
   3849 	mtbl->mt_recv_mgmt = ic->ic_recv_mgmt;
   3850 	ic->ic_recv_mgmt = rtw_recv_mgmt;
   3851 
   3852 	mtbl->mt_node_free = ic->ic_node_free;
   3853 	ic->ic_node_free = rtw_node_free;
   3854 
   3855 	mtbl->mt_node_alloc = ic->ic_node_alloc;
   3856 	ic->ic_node_alloc = rtw_node_alloc;
   3857 
   3858 	ic->ic_crypto.cs_key_delete = rtw_key_delete;
   3859 	ic->ic_crypto.cs_key_set = rtw_key_set;
   3860 	ic->ic_crypto.cs_key_update_begin = rtw_key_update_begin;
   3861 	ic->ic_crypto.cs_key_update_end = rtw_key_update_end;
   3862 }
   3863 
   3864 static inline void
   3865 rtw_init_radiotap(struct rtw_softc *sc)
   3866 {
   3867 	uint32_t present;
   3868 
   3869 	memset(&sc->sc_rxtapu, 0, sizeof(sc->sc_rxtapu));
   3870 	sc->sc_rxtap.rr_ihdr.it_len = htole16(sizeof(sc->sc_rxtapu));
   3871 
   3872 	if (sc->sc_rfchipid == RTW_RFCHIPID_PHILIPS)
   3873 		present = htole32(RTW_PHILIPS_RX_RADIOTAP_PRESENT);
   3874 	else
   3875 		present = htole32(RTW_RX_RADIOTAP_PRESENT);
   3876 	sc->sc_rxtap.rr_ihdr.it_present = present;
   3877 
   3878 	memset(&sc->sc_txtapu, 0, sizeof(sc->sc_txtapu));
   3879 	sc->sc_txtap.rt_ihdr.it_len = htole16(sizeof(sc->sc_txtapu));
   3880 	sc->sc_txtap.rt_ihdr.it_present = htole32(RTW_TX_RADIOTAP_PRESENT);
   3881 }
   3882 
   3883 static int
   3884 rtw_txsoft_blk_setup(struct rtw_txsoft_blk *tsb, u_int qlen)
   3885 {
   3886 	SIMPLEQ_INIT(&tsb->tsb_dirtyq);
   3887 	SIMPLEQ_INIT(&tsb->tsb_freeq);
   3888 	tsb->tsb_ndesc = qlen;
   3889 	tsb->tsb_desc = malloc(qlen * sizeof(*tsb->tsb_desc), M_DEVBUF,
   3890 	    M_WAITOK);
   3891 	return 0;
   3892 }
   3893 
   3894 static void
   3895 rtw_txsoft_blk_cleanup_all(struct rtw_softc *sc)
   3896 {
   3897 	int pri;
   3898 	struct rtw_txsoft_blk *tsb;
   3899 
   3900 	for (pri = 0; pri < RTW_NTXPRI; pri++) {
   3901 		tsb = &sc->sc_txsoft_blk[pri];
   3902 		free(tsb->tsb_desc, M_DEVBUF);
   3903 		tsb->tsb_desc = NULL;
   3904 	}
   3905 }
   3906 
   3907 static int
   3908 rtw_txsoft_blk_setup_all(struct rtw_softc *sc)
   3909 {
   3910 	int pri, rc = 0;
   3911 	int qlen[RTW_NTXPRI] =
   3912 	     {RTW_TXQLENLO, RTW_TXQLENMD, RTW_TXQLENHI, RTW_TXQLENBCN};
   3913 	struct rtw_txsoft_blk *tsbs;
   3914 
   3915 	tsbs = sc->sc_txsoft_blk;
   3916 
   3917 	for (pri = 0; pri < RTW_NTXPRI; pri++) {
   3918 		rc = rtw_txsoft_blk_setup(&tsbs[pri], qlen[pri]);
   3919 		if (rc != 0)
   3920 			break;
   3921 	}
   3922 	tsbs[RTW_TXPRILO].tsb_poll = RTW_TPPOLL_LPQ | RTW_TPPOLL_SLPQ;
   3923 	tsbs[RTW_TXPRIMD].tsb_poll = RTW_TPPOLL_NPQ | RTW_TPPOLL_SNPQ;
   3924 	tsbs[RTW_TXPRIHI].tsb_poll = RTW_TPPOLL_HPQ | RTW_TPPOLL_SHPQ;
   3925 	tsbs[RTW_TXPRIBCN].tsb_poll = RTW_TPPOLL_BQ | RTW_TPPOLL_SBQ;
   3926 	return rc;
   3927 }
   3928 
   3929 static void
   3930 rtw_txdesc_blk_setup(struct rtw_txdesc_blk *tdb, struct rtw_txdesc *desc,
   3931     u_int ndesc, bus_addr_t ofs, bus_addr_t physbase)
   3932 {
   3933 	tdb->tdb_ndesc = ndesc;
   3934 	tdb->tdb_desc = desc;
   3935 	tdb->tdb_physbase = physbase;
   3936 	tdb->tdb_ofs = ofs;
   3937 
   3938 	(void)memset(tdb->tdb_desc, 0,
   3939 	    sizeof(tdb->tdb_desc[0]) * tdb->tdb_ndesc);
   3940 
   3941 	rtw_txdesc_blk_init(tdb);
   3942 	tdb->tdb_next = 0;
   3943 }
   3944 
   3945 static void
   3946 rtw_txdesc_blk_setup_all(struct rtw_softc *sc)
   3947 {
   3948 	rtw_txdesc_blk_setup(&sc->sc_txdesc_blk[RTW_TXPRILO],
   3949 	    &sc->sc_descs->hd_txlo[0], RTW_NTXDESCLO,
   3950 	    RTW_RING_OFFSET(hd_txlo), RTW_RING_BASE(sc, hd_txlo));
   3951 
   3952 	rtw_txdesc_blk_setup(&sc->sc_txdesc_blk[RTW_TXPRIMD],
   3953 	    &sc->sc_descs->hd_txmd[0], RTW_NTXDESCMD,
   3954 	    RTW_RING_OFFSET(hd_txmd), RTW_RING_BASE(sc, hd_txmd));
   3955 
   3956 	rtw_txdesc_blk_setup(&sc->sc_txdesc_blk[RTW_TXPRIHI],
   3957 	    &sc->sc_descs->hd_txhi[0], RTW_NTXDESCHI,
   3958 	    RTW_RING_OFFSET(hd_txhi), RTW_RING_BASE(sc, hd_txhi));
   3959 
   3960 	rtw_txdesc_blk_setup(&sc->sc_txdesc_blk[RTW_TXPRIBCN],
   3961 	    &sc->sc_descs->hd_bcn[0], RTW_NTXDESCBCN,
   3962 	    RTW_RING_OFFSET(hd_bcn), RTW_RING_BASE(sc, hd_bcn));
   3963 }
   3964 
   3965 static struct rtw_rf *
   3966 rtw_rf_attach(struct rtw_softc *sc, enum rtw_rfchipid rfchipid, int digphy)
   3967 {
   3968 	rtw_rf_write_t rf_write;
   3969 	struct rtw_rf *rf;
   3970 
   3971 	switch (rfchipid) {
   3972 	default:
   3973 		rf_write = rtw_rf_hostwrite;
   3974 		break;
   3975 	case RTW_RFCHIPID_INTERSIL:
   3976 	case RTW_RFCHIPID_PHILIPS:
   3977 	case RTW_RFCHIPID_GCT:	/* XXX a guess */
   3978 	case RTW_RFCHIPID_RFMD:
   3979 		rf_write = (rtw_host_rfio) ? rtw_rf_hostwrite : rtw_rf_macwrite;
   3980 		break;
   3981 	}
   3982 
   3983 	switch (rfchipid) {
   3984 	case RTW_RFCHIPID_GCT:
   3985 		rf = rtw_grf5101_create(&sc->sc_regs, rf_write, 0);
   3986 		sc->sc_pwrstate_cb = rtw_maxim_pwrstate;
   3987 		break;
   3988 	case RTW_RFCHIPID_MAXIM:
   3989 		rf = rtw_max2820_create(&sc->sc_regs, rf_write, 0);
   3990 		sc->sc_pwrstate_cb = rtw_maxim_pwrstate;
   3991 		break;
   3992 	case RTW_RFCHIPID_PHILIPS:
   3993 		rf = rtw_sa2400_create(&sc->sc_regs, rf_write, digphy);
   3994 		sc->sc_pwrstate_cb = rtw_philips_pwrstate;
   3995 		break;
   3996 	case RTW_RFCHIPID_RFMD:
   3997 		/* XXX RFMD has no RF constructor */
   3998 		sc->sc_pwrstate_cb = rtw_rfmd_pwrstate;
   3999 		/*FALLTHROUGH*/
   4000 	default:
   4001 		return NULL;
   4002 	}
   4003 	rf->rf_continuous_tx_cb =
   4004 	    (rtw_continuous_tx_cb_t)rtw_continuous_tx_enable;
   4005 	rf->rf_continuous_tx_arg = (void *)sc;
   4006 	return rf;
   4007 }
   4008 
   4009 /* Revision C and later use a different PHY delay setting than
   4010  * revisions A and B.
   4011  */
   4012 static uint8_t
   4013 rtw_check_phydelay(struct rtw_regs *regs, uint32_t old_rcr)
   4014 {
   4015 #define REVAB (RTW_RCR_MXDMA_UNLIMITED | RTW_RCR_AICV)
   4016 #define REVC (REVAB | RTW_RCR_RXFTH_WHOLE)
   4017 
   4018 	uint8_t phydelay = __SHIFTIN(0x6, RTW_PHYDELAY_PHYDELAY);
   4019 
   4020 	RTW_WRITE(regs, RTW_RCR, REVAB);
   4021 	RTW_WBW(regs, RTW_RCR, RTW_RCR);
   4022 	RTW_WRITE(regs, RTW_RCR, REVC);
   4023 
   4024 	RTW_WBR(regs, RTW_RCR, RTW_RCR);
   4025 	if ((RTW_READ(regs, RTW_RCR) & REVC) == REVC)
   4026 		phydelay |= RTW_PHYDELAY_REVC_MAGIC;
   4027 
   4028 	RTW_WRITE(regs, RTW_RCR, old_rcr);	/* restore RCR */
   4029 	RTW_SYNC(regs, RTW_RCR, RTW_RCR);
   4030 
   4031 	return phydelay;
   4032 #undef REVC
   4033 }
   4034 
   4035 void
   4036 rtw_attach(struct rtw_softc *sc)
   4037 {
   4038 	struct ifnet *ifp = &sc->sc_if;
   4039 	struct ieee80211com *ic = &sc->sc_ic;
   4040 	struct rtw_txsoft_blk *tsb;
   4041 	int pri, rc;
   4042 
   4043 	pmf_self_suspensor_init(sc->sc_dev, &sc->sc_suspensor, &sc->sc_qual);
   4044 
   4045 	rtw_cipher_wep = ieee80211_cipher_wep;
   4046 	rtw_cipher_wep.ic_decap = rtw_wep_decap;
   4047 
   4048 	NEXT_ATTACH_STATE(sc, DETACHED);
   4049 
   4050 	sc->sc_soft_ih = softint_establish(SOFTINT_NET, rtw_softintr, sc);
   4051 	if (sc->sc_soft_ih == NULL) {
   4052 		aprint_error_dev(sc->sc_dev, "could not establish softint\n");
   4053 		goto err;
   4054 	}
   4055 
   4056 	switch (RTW_READ(&sc->sc_regs, RTW_TCR) & RTW_TCR_HWVERID_MASK) {
   4057 	case RTW_TCR_HWVERID_F:
   4058 		sc->sc_hwverid = 'F';
   4059 		break;
   4060 	case RTW_TCR_HWVERID_D:
   4061 		sc->sc_hwverid = 'D';
   4062 		break;
   4063 	default:
   4064 		sc->sc_hwverid = '?';
   4065 		break;
   4066 	}
   4067 	aprint_verbose_dev(sc->sc_dev, "hardware version %c\n",
   4068 	    sc->sc_hwverid);
   4069 
   4070 	rc = bus_dmamem_alloc(sc->sc_dmat, sizeof(struct rtw_descs),
   4071 	    RTW_DESC_ALIGNMENT, 0, &sc->sc_desc_segs, 1, &sc->sc_desc_nsegs,
   4072 	    0);
   4073 
   4074 	if (rc != 0) {
   4075 		aprint_error_dev(sc->sc_dev,
   4076 		    "could not allocate hw descriptors, error %d\n", rc);
   4077 		goto err;
   4078 	}
   4079 
   4080 	NEXT_ATTACH_STATE(sc, FINISH_DESC_ALLOC);
   4081 
   4082 	rc = bus_dmamem_map(sc->sc_dmat, &sc->sc_desc_segs,
   4083 	    sc->sc_desc_nsegs, sizeof(struct rtw_descs),
   4084 	    (void **)&sc->sc_descs, BUS_DMA_COHERENT);
   4085 
   4086 	if (rc != 0) {
   4087 		aprint_error_dev(sc->sc_dev,
   4088 		    "could not map hw descriptors, error %d\n", rc);
   4089 		goto err;
   4090 	}
   4091 	NEXT_ATTACH_STATE(sc, FINISH_DESC_MAP);
   4092 
   4093 	rc = bus_dmamap_create(sc->sc_dmat, sizeof(struct rtw_descs), 1,
   4094 	    sizeof(struct rtw_descs), 0, 0, &sc->sc_desc_dmamap);
   4095 
   4096 	if (rc != 0) {
   4097 		aprint_error_dev(sc->sc_dev,
   4098 		    "could not create DMA map for hw descriptors, error %d\n",
   4099 		    rc);
   4100 		goto err;
   4101 	}
   4102 	NEXT_ATTACH_STATE(sc, FINISH_DESCMAP_CREATE);
   4103 
   4104 	sc->sc_rxdesc_blk.rdb_dmat = sc->sc_dmat;
   4105 	sc->sc_rxdesc_blk.rdb_dmamap = sc->sc_desc_dmamap;
   4106 
   4107 	for (pri = 0; pri < RTW_NTXPRI; pri++) {
   4108 		sc->sc_txdesc_blk[pri].tdb_dmat = sc->sc_dmat;
   4109 		sc->sc_txdesc_blk[pri].tdb_dmamap = sc->sc_desc_dmamap;
   4110 	}
   4111 
   4112 	rc = bus_dmamap_load(sc->sc_dmat, sc->sc_desc_dmamap, sc->sc_descs,
   4113 	    sizeof(struct rtw_descs), NULL, 0);
   4114 
   4115 	if (rc != 0) {
   4116 		aprint_error_dev(sc->sc_dev,
   4117 		    "could not load DMA map for hw descriptors, error %d\n",
   4118 		    rc);
   4119 		goto err;
   4120 	}
   4121 	NEXT_ATTACH_STATE(sc, FINISH_DESCMAP_LOAD);
   4122 
   4123 	if (rtw_txsoft_blk_setup_all(sc) != 0)
   4124 		goto err;
   4125 	NEXT_ATTACH_STATE(sc, FINISH_TXCTLBLK_SETUP);
   4126 
   4127 	rtw_txdesc_blk_setup_all(sc);
   4128 
   4129 	NEXT_ATTACH_STATE(sc, FINISH_TXDESCBLK_SETUP);
   4130 
   4131 	sc->sc_rxdesc_blk.rdb_desc = &sc->sc_descs->hd_rx[0];
   4132 
   4133 	for (pri = 0; pri < RTW_NTXPRI; pri++) {
   4134 		tsb = &sc->sc_txsoft_blk[pri];
   4135 
   4136 		if ((rc = rtw_txdesc_dmamaps_create(sc->sc_dmat,
   4137 		    &tsb->tsb_desc[0], tsb->tsb_ndesc)) != 0) {
   4138 			aprint_error_dev(sc->sc_dev,
   4139 			    "could not load DMA map for hw tx descriptors, "
   4140 			    "error %d\n", rc);
   4141 			goto err;
   4142 		}
   4143 	}
   4144 
   4145 	NEXT_ATTACH_STATE(sc, FINISH_TXMAPS_CREATE);
   4146 	if ((rc = rtw_rxdesc_dmamaps_create(sc->sc_dmat, &sc->sc_rxsoft[0],
   4147 					    RTW_RXQLEN)) != 0) {
   4148 		aprint_error_dev(sc->sc_dev,
   4149 		    "could not load DMA map for hw rx descriptors, error %d\n",
   4150 		    rc);
   4151 		goto err;
   4152 	}
   4153 	NEXT_ATTACH_STATE(sc, FINISH_RXMAPS_CREATE);
   4154 
   4155 	/* Reset the chip to a known state. */
   4156 	if (rtw_reset(sc) != 0)
   4157 		goto err;
   4158 	NEXT_ATTACH_STATE(sc, FINISH_RESET);
   4159 
   4160 	sc->sc_rcr = RTW_READ(&sc->sc_regs, RTW_RCR);
   4161 
   4162 	if ((sc->sc_rcr & RTW_RCR_9356SEL) != 0)
   4163 		sc->sc_flags |= RTW_F_9356SROM;
   4164 
   4165 	if (rtw_srom_read(&sc->sc_regs, sc->sc_flags, &sc->sc_srom,
   4166 	    sc->sc_dev) != 0)
   4167 		goto err;
   4168 
   4169 	NEXT_ATTACH_STATE(sc, FINISH_READ_SROM);
   4170 
   4171 	if (rtw_srom_parse(&sc->sc_srom, &sc->sc_flags, &sc->sc_csthr,
   4172 	    &sc->sc_rfchipid, &sc->sc_rcr, &sc->sc_locale,
   4173 	    sc->sc_dev) != 0) {
   4174 		aprint_error_dev(sc->sc_dev,
   4175 		    "attach failed, malformed serial ROM\n");
   4176 		goto err;
   4177 	}
   4178 
   4179 	aprint_verbose_dev(sc->sc_dev, "%s PHY\n",
   4180 	    ((sc->sc_flags & RTW_F_DIGPHY) != 0) ? "digital" : "analog");
   4181 
   4182 	aprint_verbose_dev(sc->sc_dev, "carrier-sense threshold %u\n",
   4183 	    sc->sc_csthr);
   4184 
   4185 	NEXT_ATTACH_STATE(sc, FINISH_PARSE_SROM);
   4186 
   4187 	sc->sc_rf = rtw_rf_attach(sc, sc->sc_rfchipid,
   4188 	    sc->sc_flags & RTW_F_DIGPHY);
   4189 
   4190 	if (sc->sc_rf == NULL) {
   4191 		aprint_verbose_dev(sc->sc_dev,
   4192 		    "attach failed, could not attach RF\n");
   4193 		goto err;
   4194 	}
   4195 
   4196 	NEXT_ATTACH_STATE(sc, FINISH_RF_ATTACH);
   4197 
   4198 	sc->sc_phydelay = rtw_check_phydelay(&sc->sc_regs, sc->sc_rcr);
   4199 
   4200 	RTW_DPRINTF(RTW_DEBUG_ATTACH,
   4201 	    ("%s: PHY delay %d\n", device_xname(sc->sc_dev), sc->sc_phydelay));
   4202 
   4203 	if (sc->sc_locale == RTW_LOCALE_UNKNOWN)
   4204 		rtw_identify_country(&sc->sc_regs, &sc->sc_locale);
   4205 
   4206 	rtw_init_channels(sc->sc_locale, &sc->sc_ic.ic_channels, sc->sc_dev);
   4207 
   4208 	if (rtw_identify_sta(&sc->sc_regs, &sc->sc_ic.ic_myaddr,
   4209 	    sc->sc_dev) != 0)
   4210 		goto err;
   4211 	NEXT_ATTACH_STATE(sc, FINISH_ID_STA);
   4212 
   4213 	rtw_setifprops(ifp, device_xname(sc->sc_dev), (void*)sc);
   4214 
   4215 	IFQ_SET_READY(&ifp->if_snd);
   4216 
   4217 	sc->sc_ic.ic_ifp = ifp;
   4218 	rtw_set80211props(&sc->sc_ic);
   4219 
   4220 	rtw_led_attach(&sc->sc_led_state, (void *)sc);
   4221 	NEXT_ATTACH_STATE(sc, FINISH_LED_ATTACH);
   4222 
   4223 	/*
   4224 	 * Call MI attach routines.
   4225 	 */
   4226 	rc = if_initialize(ifp);
   4227 	if (rc != 0) {
   4228 		aprint_error_dev(sc->sc_dev, "if_initialize failed(%d)\n", rc);
   4229 		goto err;
   4230 	}
   4231 	ieee80211_ifattach(ic);
   4232 	/* Use common softint-based if_input */
   4233 	ifp->if_percpuq = if_percpuq_create(ifp);
   4234 	if_register(ifp);
   4235 
   4236 	rtw_set80211methods(&sc->sc_mtbl, &sc->sc_ic);
   4237 
   4238 	/* possibly we should fill in our own sc_send_prresp, since
   4239 	 * the RTL8180 is probably sending probe responses in ad hoc
   4240 	 * mode.
   4241 	 */
   4242 
   4243 	/* complete initialization */
   4244 	ieee80211_media_init(&sc->sc_ic, rtw_media_change, rtw_media_status);
   4245 	callout_init(&sc->sc_scan_ch, 0);
   4246 
   4247 	rtw_init_radiotap(sc);
   4248 
   4249 	bpf_attach2(ifp, DLT_IEEE802_11_RADIO,
   4250 	    sizeof(struct ieee80211_frame) + 64, &sc->sc_radiobpf);
   4251 
   4252 	NEXT_ATTACH_STATE(sc, FINISHED);
   4253 
   4254 	ieee80211_announce(ic);
   4255 	return;
   4256 err:
   4257 	rtw_detach(sc);
   4258 	return;
   4259 }
   4260 
   4261 int
   4262 rtw_detach(struct rtw_softc *sc)
   4263 {
   4264 	struct ifnet *ifp = &sc->sc_if;
   4265 	int pri, s;
   4266 
   4267 	s = splnet();
   4268 
   4269 	switch (sc->sc_attach_state) {
   4270 	case FINISHED:
   4271 		rtw_stop(ifp, 1);
   4272 
   4273 		pmf_device_deregister(sc->sc_dev);
   4274 		callout_stop(&sc->sc_scan_ch);
   4275 		ieee80211_ifdetach(&sc->sc_ic);
   4276 		if_detach(ifp);
   4277 		/*FALLTHROUGH*/
   4278 	case FINISH_LED_ATTACH:
   4279 		rtw_led_detach(&sc->sc_led_state);
   4280 		/*FALLTHROUGH*/
   4281 	case FINISH_ID_STA:
   4282 	case FINISH_RF_ATTACH:
   4283 		rtw_rf_destroy(sc->sc_rf);
   4284 		sc->sc_rf = NULL;
   4285 		/*FALLTHROUGH*/
   4286 	case FINISH_PARSE_SROM:
   4287 	case FINISH_READ_SROM:
   4288 		rtw_srom_free(&sc->sc_srom);
   4289 		/*FALLTHROUGH*/
   4290 	case FINISH_RESET:
   4291 	case FINISH_RXMAPS_CREATE:
   4292 		rtw_rxdesc_dmamaps_destroy(sc->sc_dmat, &sc->sc_rxsoft[0],
   4293 		    RTW_RXQLEN);
   4294 		/*FALLTHROUGH*/
   4295 	case FINISH_TXMAPS_CREATE:
   4296 		for (pri = 0; pri < RTW_NTXPRI; pri++) {
   4297 			rtw_txdesc_dmamaps_destroy(sc->sc_dmat,
   4298 			    sc->sc_txsoft_blk[pri].tsb_desc,
   4299 			    sc->sc_txsoft_blk[pri].tsb_ndesc);
   4300 		}
   4301 		/*FALLTHROUGH*/
   4302 	case FINISH_TXDESCBLK_SETUP:
   4303 	case FINISH_TXCTLBLK_SETUP:
   4304 		rtw_txsoft_blk_cleanup_all(sc);
   4305 		/*FALLTHROUGH*/
   4306 	case FINISH_DESCMAP_LOAD:
   4307 		bus_dmamap_unload(sc->sc_dmat, sc->sc_desc_dmamap);
   4308 		/*FALLTHROUGH*/
   4309 	case FINISH_DESCMAP_CREATE:
   4310 		bus_dmamap_destroy(sc->sc_dmat, sc->sc_desc_dmamap);
   4311 		/*FALLTHROUGH*/
   4312 	case FINISH_DESC_MAP:
   4313 		bus_dmamem_unmap(sc->sc_dmat, (void *)sc->sc_descs,
   4314 		    sizeof(struct rtw_descs));
   4315 		/*FALLTHROUGH*/
   4316 	case FINISH_DESC_ALLOC:
   4317 		bus_dmamem_free(sc->sc_dmat, &sc->sc_desc_segs,
   4318 		    sc->sc_desc_nsegs);
   4319 		/*FALLTHROUGH*/
   4320 	case DETACHED:
   4321 		if (sc->sc_soft_ih != NULL) {
   4322 			softint_disestablish(sc->sc_soft_ih);
   4323 			sc->sc_soft_ih = NULL;
   4324 		}
   4325 		NEXT_ATTACH_STATE(sc, DETACHED);
   4326 		break;
   4327 	}
   4328 	splx(s);
   4329 	return 0;
   4330 }
   4331