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