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