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