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