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