Home | History | Annotate | Line # | Download | only in ic
ath.c revision 1.39
      1 /*	$NetBSD: ath.c,v 1.39 2004/09/28 11:34:37 yamt Exp $	*/
      2 
      3 /*-
      4  * Copyright (c) 2002-2004 Sam Leffler, Errno Consulting
      5  * All rights reserved.
      6  *
      7  * Redistribution and use in source and binary forms, with or without
      8  * modification, are permitted provided that the following conditions
      9  * are met:
     10  * 1. Redistributions of source code must retain the above copyright
     11  *    notice, this list of conditions and the following disclaimer,
     12  *    without modification.
     13  * 2. Redistributions in binary form must reproduce at minimum a disclaimer
     14  *    similar to the "NO WARRANTY" disclaimer below ("Disclaimer") and any
     15  *    redistribution must be conditioned upon including a substantially
     16  *    similar Disclaimer requirement for further binary redistribution.
     17  * 3. Neither the names of the above-listed copyright holders nor the names
     18  *    of any contributors may be used to endorse or promote products derived
     19  *    from this software without specific prior written permission.
     20  *
     21  * Alternatively, this software may be distributed under the terms of the
     22  * GNU General Public License ("GPL") version 2 as published by the Free
     23  * Software Foundation.
     24  *
     25  * NO WARRANTY
     26  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
     27  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
     28  * LIMITED TO, THE IMPLIED WARRANTIES OF NONINFRINGEMENT, MERCHANTIBILITY
     29  * AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
     30  * THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR SPECIAL, EXEMPLARY,
     31  * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
     32  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
     33  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER
     34  * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
     35  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
     36  * THE POSSIBILITY OF SUCH DAMAGES.
     37  */
     38 
     39 #include <sys/cdefs.h>
     40 #ifdef __FreeBSD__
     41 __FBSDID("$FreeBSD: src/sys/dev/ath/if_ath.c,v 1.54 2004/04/05 04:42:42 sam Exp $");
     42 #endif
     43 #ifdef __NetBSD__
     44 __KERNEL_RCSID(0, "$NetBSD: ath.c,v 1.39 2004/09/28 11:34:37 yamt Exp $");
     45 #endif
     46 
     47 /*
     48  * Driver for the Atheros Wireless LAN controller.
     49  *
     50  * This software is derived from work of Atsushi Onoe; his contribution
     51  * is greatly appreciated.
     52  */
     53 
     54 #include "opt_inet.h"
     55 
     56 #ifdef __NetBSD__
     57 #include "bpfilter.h"
     58 #endif /* __NetBSD__ */
     59 
     60 #include <sys/param.h>
     61 #include <sys/systm.h>
     62 #include <sys/types.h>
     63 #include <sys/sysctl.h>
     64 #include <sys/mbuf.h>
     65 #include <sys/malloc.h>
     66 #include <sys/lock.h>
     67 #ifdef __FreeBSD__
     68 #include <sys/mutex.h>
     69 #endif
     70 #include <sys/kernel.h>
     71 #include <sys/socket.h>
     72 #include <sys/sockio.h>
     73 #include <sys/errno.h>
     74 #include <sys/callout.h>
     75 #ifdef __FreeBSD__
     76 #include <sys/bus.h>
     77 #else
     78 #include <machine/bus.h>
     79 #endif
     80 #include <sys/endian.h>
     81 
     82 #include <machine/bus.h>
     83 
     84 #include <net/if.h>
     85 #include <net/if_dl.h>
     86 #include <net/if_media.h>
     87 #include <net/if_arp.h>
     88 #ifdef __FreeBSD__
     89 #include <net/ethernet.h>
     90 #else
     91 #include <net/if_ether.h>
     92 #endif
     93 #include <net/if_llc.h>
     94 
     95 #include <net80211/ieee80211_var.h>
     96 #include <net80211/ieee80211_compat.h>
     97 
     98 #if NBPFILTER > 0
     99 #include <net/bpf.h>
    100 #endif
    101 
    102 #ifdef INET
    103 #include <netinet/in.h>
    104 #endif
    105 
    106 #include <dev/ic/athcompat.h>
    107 
    108 #define	AR_DEBUG
    109 #ifdef __FreeBSD__
    110 #include <dev/ath/if_athvar.h>
    111 #include <contrib/dev/ath/ah_desc.h>
    112 #else
    113 #include <dev/ic/athvar.h>
    114 #include <../contrib/sys/dev/ic/athhal_desc.h>
    115 #endif
    116 
    117 /* unaligned little endian access */
    118 #define LE_READ_2(p)							\
    119 	((u_int16_t)							\
    120 	 ((((u_int8_t *)(p))[0]      ) | (((u_int8_t *)(p))[1] <<  8)))
    121 #define LE_READ_4(p)							\
    122 	((u_int32_t)							\
    123 	 ((((u_int8_t *)(p))[0]      ) | (((u_int8_t *)(p))[1] <<  8) |	\
    124 	  (((u_int8_t *)(p))[2] << 16) | (((u_int8_t *)(p))[3] << 24)))
    125 
    126 #ifdef __FreeBSD__
    127 static void	ath_init(void *);
    128 #else
    129 static int	ath_init(struct ifnet *);
    130 #endif
    131 static int	ath_init1(struct ath_softc *);
    132 static int	ath_intr1(struct ath_softc *);
    133 static void	ath_stop(struct ifnet *);
    134 static void	ath_start(struct ifnet *);
    135 static void	ath_reset(struct ath_softc *);
    136 static int	ath_media_change(struct ifnet *);
    137 static void	ath_watchdog(struct ifnet *);
    138 static int	ath_ioctl(struct ifnet *, u_long, caddr_t);
    139 static void	ath_fatal_proc(void *, int);
    140 static void	ath_rxorn_proc(void *, int);
    141 static void	ath_bmiss_proc(void *, int);
    142 static void	ath_initkeytable(struct ath_softc *);
    143 static void	ath_mode_init(struct ath_softc *);
    144 static int	ath_beacon_alloc(struct ath_softc *, struct ieee80211_node *);
    145 static void	ath_beacon_proc(struct ath_softc *, int);
    146 static void	ath_beacon_free(struct ath_softc *);
    147 static void	ath_beacon_config(struct ath_softc *);
    148 static int	ath_desc_alloc(struct ath_softc *);
    149 static void	ath_desc_free(struct ath_softc *);
    150 static struct ieee80211_node *ath_node_alloc(struct ieee80211com *);
    151 static void	ath_node_free(struct ieee80211com *, struct ieee80211_node *);
    152 static void	ath_node_copy(struct ieee80211com *,
    153 			struct ieee80211_node *, const struct ieee80211_node *);
    154 static u_int8_t	ath_node_getrssi(struct ieee80211com *,
    155 			struct ieee80211_node *);
    156 static int	ath_rxbuf_init(struct ath_softc *, struct ath_buf *);
    157 static void	ath_rx_proc(void *, int);
    158 static int	ath_tx_start(struct ath_softc *, struct ieee80211_node *,
    159 			     struct ath_buf *, struct mbuf *);
    160 static void	ath_tx_proc(void *, int);
    161 static int	ath_chan_set(struct ath_softc *, struct ieee80211_channel *);
    162 static void	ath_draintxq(struct ath_softc *);
    163 static void	ath_stoprecv(struct ath_softc *);
    164 static int	ath_startrecv(struct ath_softc *);
    165 static void	ath_next_scan(void *);
    166 static void	ath_calibrate(void *);
    167 static int	ath_newstate(struct ieee80211com *, enum ieee80211_state, int);
    168 static void	ath_newassoc(struct ieee80211com *,
    169 			struct ieee80211_node *, int);
    170 static int	ath_getchannels(struct ath_softc *, u_int cc, HAL_BOOL outdoor,
    171 			HAL_BOOL xchanmode);
    172 
    173 static int	ath_rate_setup(struct ath_softc *sc, u_int mode);
    174 static void	ath_setcurmode(struct ath_softc *, enum ieee80211_phymode);
    175 static void	ath_rate_ctl_reset(struct ath_softc *, enum ieee80211_state);
    176 static void	ath_rate_ctl(void *, struct ieee80211_node *);
    177 static void	ath_recv_mgmt(struct ieee80211com *, struct mbuf *,
    178 			struct ieee80211_node *, int, int, u_int32_t);
    179 
    180 #ifdef __NetBSD__
    181 int	ath_enable(struct ath_softc *);
    182 void	ath_disable(struct ath_softc *);
    183 void	ath_power(int, void *);
    184 #endif
    185 
    186 #ifdef __FreeBSD__
    187 SYSCTL_DECL(_hw_ath);
    188 /* XXX validate sysctl values */
    189 SYSCTL_INT(_hw_ath, OID_AUTO, dwell, CTLFLAG_RW, &ath_dwelltime,
    190 	    0, "channel dwell time (ms) for AP/station scanning");
    191 SYSCTL_INT(_hw_ath, OID_AUTO, calibrate, CTLFLAG_RW, &ath_calinterval,
    192 	    0, "chip calibration interval (secs)");
    193 SYSCTL_INT(_hw_ath, OID_AUTO, outdoor, CTLFLAG_RD, &ath_outdoor,
    194 	    0, "enable/disable outdoor operation");
    195 TUNABLE_INT("hw.ath.outdoor", &ath_outdoor);
    196 SYSCTL_INT(_hw_ath, OID_AUTO, countrycode, CTLFLAG_RD, &ath_countrycode,
    197 	    0, "country code");
    198 TUNABLE_INT("hw.ath.countrycode", &ath_countrycode);
    199 SYSCTL_INT(_hw_ath, OID_AUTO, regdomain, CTLFLAG_RD, &ath_regdomain,
    200 	    0, "regulatory domain");
    201 #endif /* __FreeBSD__ */
    202 
    203 #ifdef __NetBSD__
    204 static int ath_dwelltime_nodenum, ath_calibrate_nodenum, ath_outdoor_nodenum,
    205            ath_countrycode_nodenum, ath_regdomain_nodenum, ath_debug_nodenum;
    206 #endif /* __NetBSD__ */
    207 
    208 static	int ath_dwelltime = 200;		/* 5 channels/second */
    209 static	int ath_calinterval = 30;		/* calibrate every 30 secs */
    210 static	int ath_outdoor = AH_TRUE;		/* outdoor operation */
    211 static	int ath_xchanmode = AH_TRUE;		/* enable extended channels */
    212 static	int ath_countrycode = CTRY_DEFAULT;	/* country code */
    213 static	int ath_regdomain = 0;			/* regulatory domain */
    214 
    215 #ifdef AR_DEBUG
    216 int	ath_debug = 0;
    217 #ifdef __FreeBSD__
    218 SYSCTL_INT(_hw_ath, OID_AUTO, debug, CTLFLAG_RW, &ath_debug,
    219 	    0, "control debugging printfs");
    220 TUNABLE_INT("hw.ath.debug", &ath_debug);
    221 #endif /* __FreeBSD__ */
    222 #define	IFF_DUMPPKTS(_ifp, _m) \
    223 	((ath_debug & _m) || \
    224 	    ((_ifp)->if_flags & (IFF_DEBUG|IFF_LINK2)) == (IFF_DEBUG|IFF_LINK2))
    225 static	void ath_printrxbuf(struct ath_buf *bf, int);
    226 static	void ath_printtxbuf(struct ath_buf *bf, int);
    227 enum {
    228 	ATH_DEBUG_XMIT		= 0x00000001,	/* basic xmit operation */
    229 	ATH_DEBUG_XMIT_DESC	= 0x00000002,	/* xmit descriptors */
    230 	ATH_DEBUG_RECV		= 0x00000004,	/* basic recv operation */
    231 	ATH_DEBUG_RECV_DESC	= 0x00000008,	/* recv descriptors */
    232 	ATH_DEBUG_RATE		= 0x00000010,	/* rate control */
    233 	ATH_DEBUG_RESET		= 0x00000020,	/* reset processing */
    234 	ATH_DEBUG_MODE		= 0x00000040,	/* mode init/setup */
    235 	ATH_DEBUG_BEACON 	= 0x00000080,	/* beacon handling */
    236 	ATH_DEBUG_WATCHDOG 	= 0x00000100,	/* watchdog timeout */
    237 	ATH_DEBUG_INTR		= 0x00001000,	/* ISR */
    238 	ATH_DEBUG_TX_PROC	= 0x00002000,	/* tx ISR proc */
    239 	ATH_DEBUG_RX_PROC	= 0x00004000,	/* rx ISR proc */
    240 	ATH_DEBUG_BEACON_PROC	= 0x00008000,	/* beacon ISR proc */
    241 	ATH_DEBUG_CALIBRATE	= 0x00010000,	/* periodic calibration */
    242 	ATH_DEBUG_ANY		= 0xffffffff
    243 };
    244 #define	DPRINTF(_m,X)	if (ath_debug & (_m)) printf X
    245 #else
    246 #define	IFF_DUMPPKTS(_ifp, _m) \
    247 	(((_ifp)->if_flags & (IFF_DEBUG|IFF_LINK2)) == (IFF_DEBUG|IFF_LINK2))
    248 #define	DPRINTF(_m, X)
    249 #endif
    250 
    251 #ifdef __NetBSD__
    252 int
    253 ath_activate(struct device *self, enum devact act)
    254 {
    255 	struct ath_softc *sc = (struct ath_softc *)self;
    256 	int rv = 0, s;
    257 
    258 	s = splnet();
    259 	switch (act) {
    260 	case DVACT_ACTIVATE:
    261 		rv = EOPNOTSUPP;
    262 		break;
    263 	case DVACT_DEACTIVATE:
    264 		if_deactivate(&sc->sc_ic.ic_if);
    265 		break;
    266 	}
    267 	splx(s);
    268 	return rv;
    269 }
    270 
    271 int
    272 ath_enable(struct ath_softc *sc)
    273 {
    274 	if (ATH_IS_ENABLED(sc) == 0) {
    275 		if (sc->sc_enable != NULL && (*sc->sc_enable)(sc) != 0) {
    276 			printf("%s: device enable failed\n",
    277 				sc->sc_dev.dv_xname);
    278 			return (EIO);
    279 		}
    280 		sc->sc_flags |= ATH_ENABLED;
    281 	}
    282 	return (0);
    283 }
    284 
    285 void
    286 ath_disable(struct ath_softc *sc)
    287 {
    288 	if (!ATH_IS_ENABLED(sc))
    289 		return;
    290 	if (sc->sc_disable != NULL)
    291 		(*sc->sc_disable)(sc);
    292 	sc->sc_flags &= ~ATH_ENABLED;
    293 }
    294 
    295 static int
    296 sysctl_ath_verify(SYSCTLFN_ARGS)
    297 {
    298 	int error, t;
    299 	struct sysctlnode node;
    300 
    301 	node = *rnode;
    302 	t = *(int*)rnode->sysctl_data;
    303 	node.sysctl_data = &t;
    304 	error = sysctl_lookup(SYSCTLFN_CALL(&node));
    305 	if (error || newp == NULL)
    306 		return (error);
    307 
    308 	DPRINTF(ATH_DEBUG_ANY, ("%s: t = %d, nodenum = %d, rnodenum = %d\n",
    309 	    __func__, t, node.sysctl_num, rnode->sysctl_num));
    310 
    311 	if (node.sysctl_num == ath_dwelltime_nodenum) {
    312 		if (t <= 0)
    313 			return (EINVAL);
    314 	} else if (node.sysctl_num == ath_calibrate_nodenum) {
    315 		if (t <= 0)
    316 			return (EINVAL);
    317 #ifdef AR_DEBUG
    318 	} else if (node.sysctl_num == ath_debug_nodenum) {
    319 		;		/* Accept any vaule */
    320 #endif /* AR_DEBUG */
    321 	} else
    322 		return (EINVAL);
    323 
    324 	*(int*)rnode->sysctl_data = t;
    325 
    326 	return (0);
    327 }
    328 
    329 /*
    330  * Setup sysctl(3) MIB, ath.*.
    331  *
    332  * TBD condition CTLFLAG_PERMANENT on being an LKM or not
    333  */
    334 SYSCTL_SETUP(sysctl_ath, "sysctl ath subtree setup")
    335 {
    336 	int rc, ath_node_num;
    337 	struct sysctlnode *node;
    338 
    339 	if ((rc = sysctl_createv(clog, 0, NULL, NULL,
    340 	    CTLFLAG_PERMANENT, CTLTYPE_NODE, "hw", NULL,
    341 	    NULL, 0, NULL, 0, CTL_HW, CTL_EOL)) != 0)
    342 		goto err;
    343 
    344 	if ((rc = sysctl_createv(clog, 0, NULL, &node,
    345 	    CTLFLAG_PERMANENT, CTLTYPE_NODE, "ath",
    346 	    SYSCTL_DESCR("ath information and options"),
    347 	    NULL, 0, NULL, 0, CTL_HW, CTL_CREATE, CTL_EOL)) != 0)
    348 		goto err;
    349 
    350 	ath_node_num = node->sysctl_num;
    351 
    352 	/* channel dwell time (ms) for AP/station scanning */
    353 	if ((rc = sysctl_createv(clog, 0, NULL, &node,
    354 	    CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
    355 	    CTLTYPE_INT, "dwell",
    356 	    SYSCTL_DESCR("Channel dwell time (ms) for AP/station scanning"),
    357 	    sysctl_ath_verify, 0, &ath_dwelltime,
    358 	    0, CTL_HW, ath_node_num, CTL_CREATE,
    359 	    CTL_EOL)) != 0)
    360 		goto err;
    361 
    362 	ath_dwelltime_nodenum = node->sysctl_num;
    363 
    364 	/* chip calibration interval (secs) */
    365 	if ((rc = sysctl_createv(clog, 0, NULL, &node,
    366 	    CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
    367 	    CTLTYPE_INT, "calibrate",
    368 	    SYSCTL_DESCR("Chip calibration interval (secs)"), sysctl_ath_verify,
    369 	    0, &ath_calinterval, 0, CTL_HW,
    370 	    ath_node_num, CTL_CREATE, CTL_EOL)) != 0)
    371 		goto err;
    372 
    373 	ath_calibrate_nodenum = node->sysctl_num;
    374 
    375 	/* enable/disable outdoor operation */
    376 	if ((rc = sysctl_createv(clog, 0, NULL, &node,
    377 	    CTLFLAG_PERMANENT|CTLFLAG_READWRITE, CTLTYPE_INT,
    378 	    "outdoor", SYSCTL_DESCR("Enable/disable outdoor operation"),
    379 	    NULL, 0, &ath_outdoor, 0,
    380 	    CTL_HW, ath_node_num, CTL_CREATE,
    381 	    CTL_EOL)) != 0)
    382 		goto err;
    383 
    384 	ath_outdoor_nodenum = node->sysctl_num;
    385 
    386 	/* country code */
    387 	if ((rc = sysctl_createv(clog, 0, NULL, &node,
    388 	    CTLFLAG_PERMANENT|CTLFLAG_READWRITE, CTLTYPE_INT,
    389 	    "countrycode", SYSCTL_DESCR("Country code"),
    390 	    NULL, 0, &ath_countrycode, 0,
    391 	    CTL_HW, ath_node_num, CTL_CREATE,
    392 	    CTL_EOL)) != 0)
    393 		goto err;
    394 
    395 	ath_countrycode_nodenum = node->sysctl_num;
    396 
    397 	/* regulatory domain */
    398 	if ((rc = sysctl_createv(clog, 0, NULL, &node,
    399 	    CTLFLAG_PERMANENT|CTLFLAG_READONLY, CTLTYPE_INT,
    400 	    "regdomain", SYSCTL_DESCR("Regulatory domain"),
    401 	    NULL, 0, &ath_regdomain, 0,
    402 	    CTL_HW, ath_node_num, CTL_CREATE,
    403 	    CTL_EOL)) != 0)
    404 		goto err;
    405 
    406 	ath_regdomain_nodenum = node->sysctl_num;
    407 
    408 #ifdef AR_DEBUG
    409 
    410 	/* control debugging printfs */
    411 	if ((rc = sysctl_createv(clog, 0, NULL, &node,
    412 	    CTLFLAG_PERMANENT|CTLFLAG_READWRITE, CTLTYPE_INT,
    413 	    "debug", SYSCTL_DESCR("Enable/disable ath debugging output"),
    414 	    sysctl_ath_verify, 0, &ath_debug, 0,
    415 	    CTL_HW, ath_node_num, CTL_CREATE,
    416 	    CTL_EOL)) != 0)
    417 		goto err;
    418 
    419 	ath_debug_nodenum = node->sysctl_num;
    420 
    421 #endif /* AR_DEBUG */
    422 	return;
    423 err:
    424 	printf("%s: sysctl_createv failed (rc = %d)\n", __func__, rc);
    425 }
    426 #endif /* __NetBSD__ */
    427 
    428 int
    429 ath_attach(u_int16_t devid, struct ath_softc *sc)
    430 {
    431 	struct ieee80211com *ic = &sc->sc_ic;
    432 	struct ifnet *ifp = &ic->ic_if;
    433 	struct ath_hal *ah;
    434 	HAL_STATUS status;
    435 	HAL_TXQ_INFO qinfo;
    436 	int error = 0;
    437 
    438 	DPRINTF(ATH_DEBUG_ANY, ("%s: devid 0x%x\n", __func__, devid));
    439 
    440 #ifdef __FreeBSD__
    441 	/* set these up early for if_printf use */
    442 	if_initname(ifp, device_get_name(sc->sc_dev),
    443 	    device_get_unit(sc->sc_dev));
    444 #else
    445 	memcpy(ifp->if_xname, sc->sc_dev.dv_xname, IFNAMSIZ);
    446 #endif
    447 
    448 	ah = ath_hal_attach(devid, sc, sc->sc_st, sc->sc_sh, &status);
    449 	if (ah == NULL) {
    450 		if_printf(ifp, "unable to attach hardware; HAL status %u\n",
    451 			status);
    452 		error = ENXIO;
    453 		goto bad;
    454 	}
    455 	if (ah->ah_abi != HAL_ABI_VERSION) {
    456 		if_printf(ifp, "HAL ABI mismatch detected (0x%x != 0x%x)\n",
    457 			ah->ah_abi, HAL_ABI_VERSION);
    458 		error = ENXIO;
    459 		goto bad;
    460 	}
    461 	if_printf(ifp, "mac %d.%d phy %d.%d",
    462 		ah->ah_macVersion, ah->ah_macRev,
    463 		ah->ah_phyRev >> 4, ah->ah_phyRev & 0xf);
    464 	if (ah->ah_analog5GhzRev)
    465 		printf(" 5ghz radio %d.%d",
    466 			ah->ah_analog5GhzRev >> 4, ah->ah_analog5GhzRev & 0xf);
    467 	if (ah->ah_analog2GhzRev)
    468 		printf(" 2ghz radio %d.%d",
    469 			ah->ah_analog2GhzRev >> 4, ah->ah_analog2GhzRev & 0xf);
    470 	printf("\n");
    471 	sc->sc_ah = ah;
    472 	sc->sc_invalid = 0;	/* ready to go, enable interrupt handling */
    473 
    474 	/*
    475 	 * Collect the channel list using the default country
    476 	 * code and including outdoor channels.  The 802.11 layer
    477 	 * is resposible for filtering this list based on settings
    478 	 * like the phy mode.
    479 	 */
    480 	error = ath_getchannels(sc, ath_countrycode, ath_outdoor,
    481 	    ath_xchanmode);
    482 	if (error != 0)
    483 		goto bad;
    484 	/*
    485 	 * Copy these back; they are set as a side effect
    486 	 * of constructing the channel list.
    487 	 */
    488 	ath_hal_getregdomain(ah, &ath_regdomain);
    489 	ath_hal_getcountrycode(ah, &ath_countrycode);
    490 
    491 	/*
    492 	 * Setup rate tables for all potential media types.
    493 	 */
    494 	ath_rate_setup(sc, IEEE80211_MODE_11A);
    495 	ath_rate_setup(sc, IEEE80211_MODE_11B);
    496 	ath_rate_setup(sc, IEEE80211_MODE_11G);
    497 	ath_rate_setup(sc, IEEE80211_MODE_TURBO);
    498 
    499 	error = ath_desc_alloc(sc);
    500 	if (error != 0) {
    501 		if_printf(ifp, "failed to allocate descriptors: %d\n", error);
    502 		goto bad;
    503 	}
    504 	ATH_CALLOUT_INIT(&sc->sc_scan_ch);
    505 	ATH_CALLOUT_INIT(&sc->sc_cal_ch);
    506 
    507 #ifdef __FreeBSD__
    508 	ATH_TXBUF_LOCK_INIT(sc);
    509 	ATH_TXQ_LOCK_INIT(sc);
    510 #endif
    511 
    512 	ATH_TASK_INIT(&sc->sc_txtask, ath_tx_proc, sc);
    513 	ATH_TASK_INIT(&sc->sc_rxtask, ath_rx_proc, sc);
    514 	ATH_TASK_INIT(&sc->sc_rxorntask, ath_rxorn_proc, sc);
    515 	ATH_TASK_INIT(&sc->sc_fataltask, ath_fatal_proc, sc);
    516 	ATH_TASK_INIT(&sc->sc_bmisstask, ath_bmiss_proc, sc);
    517 
    518 	/*
    519 	 * For now just pre-allocate one data queue and one
    520 	 * beacon queue.  Note that the HAL handles resetting
    521 	 * them at the needed time.  Eventually we'll want to
    522 	 * allocate more tx queues for splitting management
    523 	 * frames and for QOS support.
    524 	 */
    525 	sc->sc_bhalq = ath_hal_setuptxqueue(ah,HAL_TX_QUEUE_BEACON,NULL);
    526 	if (sc->sc_bhalq == (u_int) -1) {
    527 		if_printf(ifp, "unable to setup a beacon xmit queue!\n");
    528 		goto bad2;
    529 	}
    530 
    531 	memset(&qinfo, 0, sizeof(qinfo));
    532 	qinfo.tqi_subtype = HAL_WME_AC_BE;
    533 	sc->sc_txhalq = ath_hal_setuptxqueue(ah, HAL_TX_QUEUE_DATA, &qinfo);
    534 	if (sc->sc_txhalq == (u_int) -1) {
    535 		if_printf(ifp, "unable to setup a data xmit queue!\n");
    536 		goto bad2;
    537 	}
    538 
    539 	ifp->if_softc = sc;
    540 	ifp->if_flags = IFF_SIMPLEX | IFF_BROADCAST | IFF_MULTICAST;
    541 	ifp->if_start = ath_start;
    542 	ifp->if_watchdog = ath_watchdog;
    543 	ifp->if_ioctl = ath_ioctl;
    544 	ifp->if_init = ath_init;
    545 #ifdef __FreeBSD__
    546 	ifp->if_snd.ifq_maxlen = IFQ_MAXLEN;
    547 #else
    548 #if 0
    549 	ifp->if_stop = ath_stop;		/* XXX */
    550 #endif
    551 	IFQ_SET_READY(&ifp->if_snd);
    552 #endif
    553 
    554 	ic->ic_softc = sc;
    555 	ic->ic_newassoc = ath_newassoc;
    556 	/* XXX not right but it's not used anywhere important */
    557 	ic->ic_phytype = IEEE80211_T_OFDM;
    558 	ic->ic_opmode = IEEE80211_M_STA;
    559 	ic->ic_caps = IEEE80211_C_WEP		/* wep supported */
    560 		| IEEE80211_C_IBSS		/* ibss, nee adhoc, mode */
    561 		| IEEE80211_C_HOSTAP		/* hostap mode */
    562 		| IEEE80211_C_MONITOR		/* monitor mode */
    563 		| IEEE80211_C_SHPREAMBLE	/* short preamble supported */
    564 		;
    565 
    566 	/* get mac address from hardware */
    567 	ath_hal_getmac(ah, ic->ic_myaddr);
    568 
    569 #ifdef __NetBSD__
    570 	if_attach(ifp);
    571 #endif
    572 	/* call MI attach routine. */
    573 	ieee80211_ifattach(ifp);
    574 	/* override default methods */
    575 	ic->ic_node_alloc = ath_node_alloc;
    576 	sc->sc_node_free = ic->ic_node_free;
    577 	ic->ic_node_free = ath_node_free;
    578 	sc->sc_node_copy = ic->ic_node_copy;
    579 	ic->ic_node_copy = ath_node_copy;
    580 	ic->ic_node_getrssi = ath_node_getrssi;
    581 	sc->sc_newstate = ic->ic_newstate;
    582 	ic->ic_newstate = ath_newstate;
    583 	sc->sc_recv_mgmt = ic->ic_recv_mgmt;
    584 	ic->ic_recv_mgmt = ath_recv_mgmt;
    585 
    586 	/* complete initialization */
    587 	ieee80211_media_init(ifp, ath_media_change, ieee80211_media_status);
    588 
    589 #if NBPFILTER > 0
    590 	bpfattach2(ifp, DLT_IEEE802_11_RADIO,
    591 		sizeof(struct ieee80211_frame) + sizeof(sc->sc_tx_th),
    592 		&sc->sc_drvbpf);
    593 #endif
    594 	/*
    595 	 * Initialize constant fields.
    596 	 * XXX make header lengths a multiple of 32-bits so subsequent
    597 	 *     headers are properly aligned; this is a kludge to keep
    598 	 *     certain applications happy.
    599 	 *
    600 	 * NB: the channel is setup each time we transition to the
    601 	 *     RUN state to avoid filling it in for each frame.
    602 	 */
    603 	sc->sc_tx_th_len = roundup(sizeof(sc->sc_tx_th), sizeof(u_int32_t));
    604 	sc->sc_tx_th.wt_ihdr.it_len = htole16(sc->sc_tx_th_len);
    605 	sc->sc_tx_th.wt_ihdr.it_present = htole32(ATH_TX_RADIOTAP_PRESENT);
    606 
    607 	sc->sc_rx_th_len = roundup(sizeof(sc->sc_rx_th), sizeof(u_int32_t));
    608 	sc->sc_rx_th.wr_ihdr.it_len = htole16(sc->sc_rx_th_len);
    609 	sc->sc_rx_th.wr_ihdr.it_present = htole32(ATH_RX_RADIOTAP_PRESENT);
    610 
    611 #ifdef __NetBSD__
    612 	sc->sc_flags |= ATH_ATTACHED;
    613 	/*
    614 	 * Make sure the interface is shutdown during reboot.
    615 	 */
    616 	sc->sc_sdhook = shutdownhook_establish(ath_shutdown, sc);
    617 	if (sc->sc_sdhook == NULL)
    618 		printf("%s: WARNING: unable to establish shutdown hook\n",
    619 			sc->sc_dev.dv_xname);
    620 	sc->sc_powerhook = powerhook_establish(ath_power, sc);
    621 	if (sc->sc_powerhook == NULL)
    622 		printf("%s: WARNING: unable to establish power hook\n",
    623 			sc->sc_dev.dv_xname);
    624 #endif
    625 	return 0;
    626 bad2:
    627 	ath_desc_free(sc);
    628 bad:
    629 	if (ah)
    630 		ath_hal_detach(ah);
    631 	sc->sc_invalid = 1;
    632 	return error;
    633 }
    634 
    635 int
    636 ath_detach(struct ath_softc *sc)
    637 {
    638 	struct ifnet *ifp = &sc->sc_ic.ic_if;
    639 	ath_softc_critsect_decl(s);
    640 
    641 	if ((sc->sc_flags & ATH_ATTACHED) == 0)
    642 		return (0);
    643 	DPRINTF(ATH_DEBUG_ANY, ("%s: if_flags %x\n", __func__, ifp->if_flags));
    644 
    645 	ath_softc_critsect_begin(sc, s);
    646 	ath_stop(ifp);
    647 #if NBPFILTER > 0
    648 	bpfdetach(ifp);
    649 #endif
    650 	ath_desc_free(sc);
    651 	ath_hal_detach(sc->sc_ah);
    652 	ieee80211_ifdetach(ifp);
    653 #ifdef __NetBSD__
    654 	if_detach(ifp);
    655 #endif /* __NetBSD__ */
    656 	ath_softc_critsect_end(sc, s);
    657 #ifdef __NetBSD__
    658 	powerhook_disestablish(sc->sc_powerhook);
    659 	shutdownhook_disestablish(sc->sc_sdhook);
    660 #endif /* __NetBSD__ */
    661 #ifdef __FreeBSD__
    662 
    663 	ATH_TXBUF_LOCK_DESTROY(sc);
    664 	ATH_TXQ_LOCK_DESTROY(sc);
    665 
    666 #endif /* __FreeBSD__ */
    667 	return 0;
    668 }
    669 
    670 #ifdef __NetBSD__
    671 void
    672 ath_power(int why, void *arg)
    673 {
    674 	struct ath_softc *sc = arg;
    675 	int s;
    676 
    677 	DPRINTF(ATH_DEBUG_ANY, ("ath_power(%d)\n", why));
    678 
    679 	s = splnet();
    680 	switch (why) {
    681 	case PWR_SUSPEND:
    682 	case PWR_STANDBY:
    683 		ath_suspend(sc, why);
    684 		break;
    685 	case PWR_RESUME:
    686 		ath_resume(sc, why);
    687 		break;
    688 	case PWR_SOFTSUSPEND:
    689 	case PWR_SOFTSTANDBY:
    690 	case PWR_SOFTRESUME:
    691 		break;
    692 	}
    693 	splx(s);
    694 }
    695 #endif
    696 
    697 void
    698 ath_suspend(struct ath_softc *sc, int why)
    699 {
    700 	struct ifnet *ifp = &sc->sc_ic.ic_if;
    701 
    702 	DPRINTF(ATH_DEBUG_ANY, ("%s: if_flags %x\n", __func__, ifp->if_flags));
    703 
    704 	ath_stop(ifp);
    705 	if (sc->sc_power != NULL)
    706 		(*sc->sc_power)(sc, why);
    707 }
    708 
    709 void
    710 ath_resume(struct ath_softc *sc, int why)
    711 {
    712 	struct ifnet *ifp = &sc->sc_ic.ic_if;
    713 
    714 	DPRINTF(ATH_DEBUG_ANY, ("%s: if_flags %x\n", __func__, ifp->if_flags));
    715 
    716 	if (ifp->if_flags & IFF_UP) {
    717 		ath_init(ifp);
    718 #if 0
    719 		(void)ath_intr(sc);
    720 #endif
    721 		if (sc->sc_power != NULL)
    722 			(*sc->sc_power)(sc, why);
    723 		if (ifp->if_flags & IFF_RUNNING)
    724 			ath_start(ifp);
    725 	}
    726 }
    727 
    728 #ifdef __NetBSD__
    729 void
    730 ath_shutdown(void *arg)
    731 {
    732 	struct ath_softc *sc = arg;
    733 
    734 	ath_stop(&sc->sc_ic.ic_if);
    735 }
    736 #else
    737 void
    738 ath_shutdown(struct ath_softc *sc)
    739 {
    740 #if 1
    741 	return;
    742 #else
    743 	struct ifnet *ifp = &sc->sc_ic.ic_if;
    744 
    745 	DPRINTF(ATH_DEBUG_ANY, ("%s: if_flags %x\n", __func__, ifp->if_flags));
    746 
    747 	ath_stop(ifp);
    748 #endif
    749 }
    750 #endif
    751 
    752 #ifdef __NetBSD__
    753 int
    754 ath_intr(void *arg)
    755 {
    756 	return ath_intr1((struct ath_softc *)arg);
    757 }
    758 #else
    759 void
    760 ath_intr(void *arg)
    761 {
    762 	(void)ath_intr1((struct ath_softc *)arg);
    763 }
    764 #endif
    765 
    766 static int
    767 ath_intr1(struct ath_softc *sc)
    768 {
    769 	struct ieee80211com *ic = &sc->sc_ic;
    770 	struct ifnet *ifp = &ic->ic_if;
    771 	struct ath_hal *ah = sc->sc_ah;
    772 	HAL_INT status;
    773 
    774 	if (sc->sc_invalid) {
    775 		/*
    776 		 * The hardware is not ready/present, don't touch anything.
    777 		 * Note this can happen early on if the IRQ is shared.
    778 		 */
    779 		DPRINTF(ATH_DEBUG_ANY, ("%s: invalid; ignored\n", __func__));
    780 		return 0;
    781 	}
    782 	if (!ath_hal_intrpend(ah))		/* shared irq, not for us */
    783 		return 0;
    784 	if ((ifp->if_flags & (IFF_RUNNING|IFF_UP)) != (IFF_RUNNING|IFF_UP)) {
    785 		DPRINTF(ATH_DEBUG_ANY, ("%s: if_flags 0x%x\n",
    786 			__func__, ifp->if_flags));
    787 		ath_hal_getisr(ah, &status);	/* clear ISR */
    788 		ath_hal_intrset(ah, 0);		/* disable further intr's */
    789 		return 1; /* XXX */
    790 	}
    791 	ath_hal_getisr(ah, &status);		/* NB: clears ISR too */
    792 	DPRINTF(ATH_DEBUG_INTR, ("%s: status 0x%x\n", __func__, status));
    793 	status &= sc->sc_imask;			/* discard unasked for bits */
    794 	if (status & HAL_INT_FATAL) {
    795 		sc->sc_stats.ast_hardware++;
    796 		ath_hal_intrset(ah, 0);		/* disable intr's until reset */
    797 		ATH_TASK_RUN_OR_ENQUEUE(&sc->sc_fataltask);
    798 	} else if (status & HAL_INT_RXORN) {
    799 		sc->sc_stats.ast_rxorn++;
    800 		ath_hal_intrset(ah, 0);		/* disable intr's until reset */
    801 		ATH_TASK_RUN_OR_ENQUEUE(&sc->sc_rxorntask);
    802 	} else {
    803 		if (status & HAL_INT_RXEOL) {
    804 			/*
    805 			 * NB: the hardware should re-read the link when
    806 			 *     RXE bit is written, but it doesn't work at
    807 			 *     least on older hardware revs.
    808 			 */
    809 			sc->sc_stats.ast_rxeol++;
    810 			sc->sc_rxlink = NULL;
    811 		}
    812 		if (status & HAL_INT_TXURN) {
    813 			sc->sc_stats.ast_txurn++;
    814 			/* bump tx trigger level */
    815 			ath_hal_updatetxtriglevel(ah, AH_TRUE);
    816 		}
    817 		if (status & HAL_INT_RX)
    818 			ATH_TASK_RUN_OR_ENQUEUE(&sc->sc_rxtask);
    819 		if (status & HAL_INT_TX)
    820 			ATH_TASK_RUN_OR_ENQUEUE(&sc->sc_txtask);
    821 		if (status & HAL_INT_SWBA) {
    822 			/*
    823 			 * Handle beacon transmission directly; deferring
    824 			 * this is too slow to meet timing constraints
    825 			 * under load.
    826 			 */
    827 			ath_beacon_proc(sc, 0);
    828 		}
    829 		if (status & HAL_INT_BMISS) {
    830 			sc->sc_stats.ast_bmiss++;
    831 			ATH_TASK_RUN_OR_ENQUEUE(&sc->sc_bmisstask);
    832 		}
    833 	}
    834 	return 1;
    835 }
    836 
    837 static void
    838 ath_fatal_proc(void *arg, int pending)
    839 {
    840 	struct ath_softc *sc = arg;
    841 
    842 	device_printf(sc->sc_dev, "hardware error; resetting\n");
    843 	ath_reset(sc);
    844 }
    845 
    846 static void
    847 ath_rxorn_proc(void *arg, int pending)
    848 {
    849 	struct ath_softc *sc = arg;
    850 
    851 	device_printf(sc->sc_dev, "rx FIFO overrun; resetting\n");
    852 	ath_reset(sc);
    853 }
    854 
    855 static void
    856 ath_bmiss_proc(void *arg, int pending)
    857 {
    858 	struct ath_softc *sc = arg;
    859 	struct ieee80211com *ic = &sc->sc_ic;
    860 
    861 	DPRINTF(ATH_DEBUG_ANY, ("%s: pending %u\n", __func__, pending));
    862 	if (ic->ic_opmode != IEEE80211_M_STA)
    863 		return;
    864 	if (ic->ic_state == IEEE80211_S_RUN) {
    865 		/*
    866 		 * Rather than go directly to scan state, try to
    867 		 * reassociate first.  If that fails then the state
    868 		 * machine will drop us into scanning after timing
    869 		 * out waiting for a probe response.
    870 		 */
    871 		ieee80211_new_state(ic, IEEE80211_S_ASSOC, -1);
    872 	}
    873 }
    874 
    875 static u_int
    876 ath_chan2flags(struct ieee80211com *ic, struct ieee80211_channel *chan)
    877 {
    878 	enum ieee80211_phymode mode = ieee80211_chan2mode(ic, chan);
    879 
    880 	switch (mode) {
    881 	case IEEE80211_MODE_AUTO:
    882 		return 0;
    883 	case IEEE80211_MODE_11A:
    884 		return CHANNEL_A;
    885 	case IEEE80211_MODE_11B:
    886 		return CHANNEL_B;
    887 	case IEEE80211_MODE_11G:
    888 		return CHANNEL_PUREG;
    889 	case IEEE80211_MODE_TURBO:
    890 		return CHANNEL_T;
    891 	default:
    892 		panic("%s: unsupported mode %d\n", __func__, mode);
    893 		return 0;
    894 	}
    895 }
    896 
    897 #ifdef __NetBSD__
    898 static int
    899 ath_init(struct ifnet *ifp)
    900 {
    901 	return ath_init1((struct ath_softc *)ifp->if_softc);
    902 }
    903 #else
    904 static void
    905 ath_init(void *arg)
    906 {
    907 	(void)ath_init1((struct ath_softc *)arg);
    908 }
    909 #endif
    910 
    911 static int
    912 ath_init1(struct ath_softc *sc)
    913 {
    914 	struct ieee80211com *ic = &sc->sc_ic;
    915 	struct ifnet *ifp = &ic->ic_if;
    916 	struct ieee80211_node *ni;
    917 	enum ieee80211_phymode mode;
    918 	struct ath_hal *ah = sc->sc_ah;
    919 	HAL_STATUS status;
    920 	HAL_CHANNEL hchan;
    921 	int error = 0;
    922 	ath_softc_critsect_decl(s);
    923 
    924 	DPRINTF(ATH_DEBUG_ANY, ("%s: if_flags 0x%x\n",
    925 		__func__, ifp->if_flags));
    926 
    927 #ifdef __NetBSD__
    928 	if ((error = ath_enable(sc)) != 0)
    929 		return error;
    930 #endif
    931 
    932 	ath_softc_critsect_begin(sc, s);
    933 	/*
    934 	 * Stop anything previously setup.  This is safe
    935 	 * whether this is the first time through or not.
    936 	 */
    937 	ath_stop(ifp);
    938 
    939 	/*
    940 	 * The basic interface to setting the hardware in a good
    941 	 * state is ``reset''.  On return the hardware is known to
    942 	 * be powered up and with interrupts disabled.  This must
    943 	 * be followed by initialization of the appropriate bits
    944 	 * and then setup of the interrupt mask.
    945 	 */
    946 	hchan.channel = ic->ic_ibss_chan->ic_freq;
    947 	hchan.channelFlags = ath_chan2flags(ic, ic->ic_ibss_chan);
    948 	if (!ath_hal_reset(ah, ic->ic_opmode, &hchan, AH_FALSE, &status)) {
    949 		if_printf(ifp, "unable to reset hardware; hal status %u\n",
    950 			status);
    951 		error = EIO;
    952 		goto done;
    953 	}
    954 
    955 	/*
    956 	 * Setup the hardware after reset: the key cache
    957 	 * is filled as needed and the receive engine is
    958 	 * set going.  Frame transmit is handled entirely
    959 	 * in the frame output path; there's nothing to do
    960 	 * here except setup the interrupt mask.
    961 	 */
    962 	if (ic->ic_flags & IEEE80211_F_PRIVACY)
    963 		ath_initkeytable(sc);
    964 	if ((error = ath_startrecv(sc)) != 0) {
    965 		if_printf(ifp, "unable to start recv logic\n");
    966 		goto done;
    967 	}
    968 
    969 	/*
    970 	 * Enable interrupts.
    971 	 */
    972 	sc->sc_imask = HAL_INT_RX | HAL_INT_TX
    973 		  | HAL_INT_RXEOL | HAL_INT_RXORN
    974 		  | HAL_INT_FATAL | HAL_INT_GLOBAL;
    975 	ath_hal_intrset(ah, sc->sc_imask);
    976 
    977 	ifp->if_flags |= IFF_RUNNING;
    978 	ic->ic_state = IEEE80211_S_INIT;
    979 
    980 	/*
    981 	 * The hardware should be ready to go now so it's safe
    982 	 * to kick the 802.11 state machine as it's likely to
    983 	 * immediately call back to us to send mgmt frames.
    984 	 */
    985 	ni = ic->ic_bss;
    986 	ni->ni_chan = ic->ic_ibss_chan;
    987 	mode = ieee80211_chan2mode(ic, ni->ni_chan);
    988 	if (mode != sc->sc_curmode)
    989 		ath_setcurmode(sc, mode);
    990 	if (ic->ic_opmode != IEEE80211_M_MONITOR)
    991 		ieee80211_new_state(ic, IEEE80211_S_SCAN, -1);
    992 	else
    993 		ieee80211_new_state(ic, IEEE80211_S_RUN, -1);
    994 done:
    995 	ath_softc_critsect_end(sc, s);
    996 	return error;
    997 }
    998 
    999 static void
   1000 ath_stop(struct ifnet *ifp)
   1001 {
   1002 	struct ieee80211com *ic = (struct ieee80211com *) ifp;
   1003 	struct ath_softc *sc = ifp->if_softc;
   1004 	struct ath_hal *ah = sc->sc_ah;
   1005 	ath_softc_critsect_decl(s);
   1006 
   1007 	DPRINTF(ATH_DEBUG_ANY, ("%s: invalid %u if_flags 0x%x\n",
   1008 		__func__, sc->sc_invalid, ifp->if_flags));
   1009 
   1010 	ath_softc_critsect_begin(sc, s);
   1011 	if (ifp->if_flags & IFF_RUNNING) {
   1012 		/*
   1013 		 * Shutdown the hardware and driver:
   1014 		 *    disable interrupts
   1015 		 *    turn off timers
   1016 		 *    clear transmit machinery
   1017 		 *    clear receive machinery
   1018 		 *    drain and release tx queues
   1019 		 *    reclaim beacon resources
   1020 		 *    reset 802.11 state machine
   1021 		 *    power down hardware
   1022 		 *
   1023 		 * Note that some of this work is not possible if the
   1024 		 * hardware is gone (invalid).
   1025 		 */
   1026 		ifp->if_flags &= ~IFF_RUNNING;
   1027 		ifp->if_timer = 0;
   1028 		if (!sc->sc_invalid)
   1029 			ath_hal_intrset(ah, 0);
   1030 		ath_draintxq(sc);
   1031 		if (!sc->sc_invalid)
   1032 			ath_stoprecv(sc);
   1033 		else
   1034 			sc->sc_rxlink = NULL;
   1035 #ifdef __FreeBSD__
   1036 		IF_DRAIN(&ifp->if_snd);
   1037 #else
   1038 		IF_PURGE(&ifp->if_snd);
   1039 #endif
   1040 		ath_beacon_free(sc);
   1041 		ieee80211_new_state(ic, IEEE80211_S_INIT, -1);
   1042 		if (!sc->sc_invalid) {
   1043 			ath_hal_setpower(ah, HAL_PM_FULL_SLEEP, 0);
   1044 		}
   1045 #ifdef __NetBSD__
   1046 		ath_disable(sc);
   1047 #endif
   1048 	}
   1049 	ath_softc_critsect_end(sc, s);
   1050 }
   1051 
   1052 /*
   1053  * Reset the hardware w/o losing operational state.  This is
   1054  * basically a more efficient way of doing ath_stop, ath_init,
   1055  * followed by state transitions to the current 802.11
   1056  * operational state.  Used to recover from errors rx overrun
   1057  * and to reset the hardware when rf gain settings must be reset.
   1058  */
   1059 static void
   1060 ath_reset(struct ath_softc *sc)
   1061 {
   1062 	struct ieee80211com *ic = &sc->sc_ic;
   1063 	struct ifnet *ifp = &ic->ic_if;
   1064 	struct ath_hal *ah = sc->sc_ah;
   1065 	struct ieee80211_channel *c;
   1066 	HAL_STATUS status;
   1067 	HAL_CHANNEL hchan;
   1068 
   1069 	/*
   1070 	 * Convert to a HAL channel description with the flags
   1071 	 * constrained to reflect the current operating mode.
   1072 	 */
   1073 	c = ic->ic_ibss_chan;
   1074 	hchan.channel = c->ic_freq;
   1075 	hchan.channelFlags = ath_chan2flags(ic, c);
   1076 
   1077 	ath_hal_intrset(ah, 0);		/* disable interrupts */
   1078 	ath_draintxq(sc);		/* stop xmit side */
   1079 	ath_stoprecv(sc);		/* stop recv side */
   1080 	/* NB: indicate channel change so we do a full reset */
   1081 	if (!ath_hal_reset(ah, ic->ic_opmode, &hchan, AH_TRUE, &status))
   1082 		if_printf(ifp, "%s: unable to reset hardware; hal status %u\n",
   1083 			__func__, status);
   1084 	ath_hal_intrset(ah, sc->sc_imask);
   1085 	if (ath_startrecv(sc) != 0)	/* restart recv */
   1086 		if_printf(ifp, "%s: unable to start recv logic\n", __func__);
   1087 	ath_start(ifp);			/* restart xmit */
   1088 	if (ic->ic_state == IEEE80211_S_RUN)
   1089 		ath_beacon_config(sc);	/* restart beacons */
   1090 }
   1091 
   1092 static void
   1093 ath_start(struct ifnet *ifp)
   1094 {
   1095 	struct ath_softc *sc = ifp->if_softc;
   1096 	struct ath_hal *ah = sc->sc_ah;
   1097 	struct ieee80211com *ic = &sc->sc_ic;
   1098 	struct ieee80211_node *ni;
   1099 	struct ath_buf *bf;
   1100 	struct mbuf *m;
   1101 	struct ieee80211_frame *wh;
   1102 	ath_txbuf_critsect_decl(s);
   1103 
   1104 	if ((ifp->if_flags & IFF_RUNNING) == 0 || sc->sc_invalid)
   1105 		return;
   1106 	for (;;) {
   1107 		/*
   1108 		 * Grab a TX buffer and associated resources.
   1109 		 */
   1110 		ath_txbuf_critsect_begin(sc, s);
   1111 		bf = TAILQ_FIRST(&sc->sc_txbuf);
   1112 		if (bf != NULL)
   1113 			TAILQ_REMOVE(&sc->sc_txbuf, bf, bf_list);
   1114 		ath_txbuf_critsect_end(sc, s);
   1115 		if (bf == NULL) {
   1116 			DPRINTF(ATH_DEBUG_ANY, ("%s: out of xmit buffers\n",
   1117 				__func__));
   1118 			sc->sc_stats.ast_tx_qstop++;
   1119 			ifp->if_flags |= IFF_OACTIVE;
   1120 			break;
   1121 		}
   1122 		/*
   1123 		 * Poll the management queue for frames; they
   1124 		 * have priority over normal data frames.
   1125 		 */
   1126 		IF_DEQUEUE(&ic->ic_mgtq, m);
   1127 		if (m == NULL) {
   1128 			/*
   1129 			 * No data frames go out unless we're associated.
   1130 			 */
   1131 			if (ic->ic_state != IEEE80211_S_RUN) {
   1132 				DPRINTF(ATH_DEBUG_ANY,
   1133 					("%s: ignore data packet, state %u\n",
   1134 					__func__, ic->ic_state));
   1135 				sc->sc_stats.ast_tx_discard++;
   1136 				ath_txbuf_critsect_begin(sc, s);
   1137 				TAILQ_INSERT_TAIL(&sc->sc_txbuf, bf, bf_list);
   1138 				ath_txbuf_critsect_end(sc, s);
   1139 				break;
   1140 			}
   1141 			IF_DEQUEUE(&ifp->if_snd, m);
   1142 			if (m == NULL) {
   1143 				ath_txbuf_critsect_begin(sc, s);
   1144 				TAILQ_INSERT_TAIL(&sc->sc_txbuf, bf, bf_list);
   1145 				ath_txbuf_critsect_end(sc, s);
   1146 				break;
   1147 			}
   1148 			ifp->if_opackets++;
   1149 
   1150 #ifdef __NetBSD__
   1151 #if NBPFILTER > 0
   1152 			if (ifp->if_bpf)
   1153 				bpf_mtap(ifp->if_bpf, m);
   1154 #endif
   1155 #endif
   1156 #ifdef __FreeBSD__
   1157 			BPF_MTAP(ifp, m);
   1158 #endif
   1159 			/*
   1160 			 * Encapsulate the packet in prep for transmission.
   1161 			 */
   1162 			m = ieee80211_encap(ifp, m, &ni);
   1163 			if (m == NULL) {
   1164 				DPRINTF(ATH_DEBUG_ANY,
   1165 					("%s: encapsulation failure\n",
   1166 					__func__));
   1167 				sc->sc_stats.ast_tx_encap++;
   1168 				goto bad;
   1169 			}
   1170 			wh = mtod(m, struct ieee80211_frame *);
   1171 		} else {
   1172 			/*
   1173 			 * Hack!  The referenced node pointer is in the
   1174 			 * rcvif field of the packet header.  This is
   1175 			 * placed there by ieee80211_mgmt_output because
   1176 			 * we need to hold the reference with the frame
   1177 			 * and there's no other way (other than packet
   1178 			 * tags which we consider too expensive to use)
   1179 			 * to pass it along.
   1180 			 */
   1181 			ni = (struct ieee80211_node *) m->m_pkthdr.rcvif;
   1182 			m->m_pkthdr.rcvif = NULL;
   1183 
   1184 			wh = mtod(m, struct ieee80211_frame *);
   1185 			if ((wh->i_fc[0] & IEEE80211_FC0_SUBTYPE_MASK) ==
   1186 			    IEEE80211_FC0_SUBTYPE_PROBE_RESP) {
   1187 				/* fill time stamp */
   1188 				u_int64_t tsf;
   1189 				u_int32_t *tstamp;
   1190 
   1191 				tsf = ath_hal_gettsf64(ah);
   1192 				/* XXX: adjust 100us delay to xmit */
   1193 				tsf += 100;
   1194 				tstamp = (u_int32_t *)&wh[1];
   1195 				tstamp[0] = htole32(tsf & 0xffffffff);
   1196 				tstamp[1] = htole32(tsf >> 32);
   1197 			}
   1198 			sc->sc_stats.ast_tx_mgmt++;
   1199 		}
   1200 
   1201 		if (ath_tx_start(sc, ni, bf, m)) {
   1202 	bad:
   1203 			ath_txbuf_critsect_begin(sc, s);
   1204 			TAILQ_INSERT_TAIL(&sc->sc_txbuf, bf, bf_list);
   1205 			ath_txbuf_critsect_end(sc, s);
   1206 			ifp->if_oerrors++;
   1207 			if (ni != NULL)
   1208 				ieee80211_release_node(ic, ni);
   1209 			continue;
   1210 		}
   1211 
   1212 		sc->sc_tx_timer = 5;
   1213 		ifp->if_timer = 1;
   1214 	}
   1215 }
   1216 
   1217 static int
   1218 ath_media_change(struct ifnet *ifp)
   1219 {
   1220 	int error;
   1221 
   1222 	error = ieee80211_media_change(ifp);
   1223 	if (error == ENETRESET) {
   1224 		if ((ifp->if_flags & (IFF_RUNNING|IFF_UP)) ==
   1225 		    (IFF_RUNNING|IFF_UP))
   1226 			ath_init(ifp);		/* XXX lose error */
   1227 		error = 0;
   1228 	}
   1229 	return error;
   1230 }
   1231 
   1232 static void
   1233 ath_watchdog(struct ifnet *ifp)
   1234 {
   1235 	struct ath_softc *sc = ifp->if_softc;
   1236 	struct ieee80211com *ic = &sc->sc_ic;
   1237 
   1238 	ifp->if_timer = 0;
   1239 	if ((ifp->if_flags & IFF_RUNNING) == 0 || sc->sc_invalid)
   1240 		return;
   1241 	if (sc->sc_tx_timer) {
   1242 		if (--sc->sc_tx_timer == 0) {
   1243 			if_printf(ifp, "device timeout\n");
   1244 			ath_reset(sc);
   1245 			ifp->if_oerrors++;
   1246 			sc->sc_stats.ast_watchdog++;
   1247 			return;
   1248 		}
   1249 		ifp->if_timer = 1;
   1250 	}
   1251 	if (ic->ic_fixed_rate == -1) {
   1252 		/*
   1253 		 * Run the rate control algorithm if we're not
   1254 		 * locked at a fixed rate.
   1255 		 */
   1256 		if (ic->ic_opmode == IEEE80211_M_STA)
   1257 			ath_rate_ctl(sc, ic->ic_bss);
   1258 		else
   1259 			ieee80211_iterate_nodes(ic, ath_rate_ctl, sc);
   1260 	}
   1261 	ieee80211_watchdog(ifp);
   1262 }
   1263 
   1264 static int
   1265 ath_ioctl(struct ifnet *ifp, u_long cmd, caddr_t data)
   1266 {
   1267 	struct ath_softc *sc = ifp->if_softc;
   1268 	struct ifreq *ifr = (struct ifreq *)data;
   1269 	int error = 0;
   1270 	ath_softc_critsect_decl(s);
   1271 
   1272 	ath_softc_critsect_begin(sc, s);
   1273 	switch (cmd) {
   1274 	case SIOCSIFFLAGS:
   1275 		if (ifp->if_flags & IFF_UP) {
   1276 			if (ifp->if_flags & IFF_RUNNING) {
   1277 				/*
   1278 				 * To avoid rescanning another access point,
   1279 				 * do not call ath_init() here.  Instead,
   1280 				 * only reflect promisc mode settings.
   1281 				 */
   1282 				ath_mode_init(sc);
   1283 			} else {
   1284 				/*
   1285 				 * Beware of being called during detach to
   1286 				 * reset promiscuous mode.  In that case we
   1287 				 * will still be marked UP but not RUNNING.
   1288 				 * However trying to re-init the interface
   1289 				 * is the wrong thing to do as we've already
   1290 				 * torn down much of our state.  There's
   1291 				 * probably a better way to deal with this.
   1292 				 */
   1293 				if (!sc->sc_invalid)
   1294 					ath_init(ifp);	/* XXX lose error */
   1295 			}
   1296 		} else
   1297 			ath_stop(ifp);
   1298 		break;
   1299 	case SIOCADDMULTI:
   1300 	case SIOCDELMULTI:
   1301 #ifdef __FreeBSD__
   1302 		/*
   1303 		 * The upper layer has already installed/removed
   1304 		 * the multicast address(es), just recalculate the
   1305 		 * multicast filter for the card.
   1306 		 */
   1307 		if (ifp->if_flags & IFF_RUNNING)
   1308 			ath_mode_init(sc);
   1309 #endif
   1310 #ifdef __NetBSD__
   1311 		error = (cmd == SIOCADDMULTI) ?
   1312 		    ether_addmulti(ifr, &sc->sc_ic.ic_ec) :
   1313 		    ether_delmulti(ifr, &sc->sc_ic.ic_ec);
   1314 		if (error == ENETRESET) {
   1315 			if (ifp->if_flags & IFF_RUNNING)
   1316 				ath_mode_init(sc);
   1317 			error = 0;
   1318 		}
   1319 #endif
   1320 		break;
   1321 	case SIOCGATHSTATS:
   1322 		error = copyout(&sc->sc_stats,
   1323 				ifr->ifr_data, sizeof (sc->sc_stats));
   1324 		break;
   1325 	case SIOCGATHDIAG: {
   1326 #if 0	/* XXX punt */
   1327 		struct ath_diag *ad = (struct ath_diag *)data;
   1328 		struct ath_hal *ah = sc->sc_ah;
   1329 		void *data;
   1330 		u_int size;
   1331 
   1332 		if (ath_hal_getdiagstate(ah, ad->ad_id, &data, &size)) {
   1333 			if (size < ad->ad_size)
   1334 				ad->ad_size = size;
   1335 			if (data)
   1336 				error = copyout(data, ad->ad_data, ad->ad_size);
   1337 		} else
   1338 			error = EINVAL;
   1339 #else
   1340 		error = EINVAL;
   1341 #endif
   1342 		break;
   1343 	}
   1344 	default:
   1345 		error = ieee80211_ioctl(ifp, cmd, data);
   1346 		if (error == ENETRESET) {
   1347 			if ((ifp->if_flags & (IFF_RUNNING|IFF_UP)) ==
   1348 			    (IFF_RUNNING|IFF_UP))
   1349 				ath_init(ifp);		/* XXX lose error */
   1350 			error = 0;
   1351 		}
   1352 		break;
   1353 	}
   1354 	ath_softc_critsect_end(sc, s);
   1355 	return error;
   1356 }
   1357 
   1358 /*
   1359  * Fill the hardware key cache with key entries.
   1360  */
   1361 static void
   1362 ath_initkeytable(struct ath_softc *sc)
   1363 {
   1364 	struct ieee80211com *ic = &sc->sc_ic;
   1365 	struct ath_hal *ah = sc->sc_ah;
   1366 	int i;
   1367 
   1368 	/* XXX maybe should reset all keys when !WEPON */
   1369 	for (i = 0; i < IEEE80211_WEP_NKID; i++) {
   1370 		struct ieee80211_wepkey *k = &ic->ic_nw_keys[i];
   1371 		if (k->wk_len == 0)
   1372 			ath_hal_keyreset(ah, i);
   1373 		else {
   1374 			HAL_KEYVAL hk;
   1375 
   1376 			memset(&hk, 0, sizeof(hk));
   1377 			hk.kv_type = HAL_CIPHER_WEP;
   1378 			hk.kv_len = k->wk_len;
   1379 			memcpy(hk.kv_val, k->wk_key, k->wk_len);
   1380 			/* XXX return value */
   1381 			ath_hal_keyset(ah, i, &hk);
   1382 		}
   1383 	}
   1384 }
   1385 
   1386 static void
   1387 ath_mcastfilter_accum(caddr_t dl, u_int32_t (*mfilt)[2])
   1388 {
   1389 	u_int32_t val;
   1390 	u_int8_t pos;
   1391 
   1392 	val = LE_READ_4(dl + 0);
   1393 	pos = (val >> 18) ^ (val >> 12) ^ (val >> 6) ^ val;
   1394 	val = LE_READ_4(dl + 3);
   1395 	pos ^= (val >> 18) ^ (val >> 12) ^ (val >> 6) ^ val;
   1396 	pos &= 0x3f;
   1397 	(*mfilt)[pos / 32] |= (1 << (pos % 32));
   1398 }
   1399 
   1400 #ifdef __FreeBSD__
   1401 static void
   1402 ath_mcastfilter_compute(struct ath_softc *sc, u_int32_t (*mfilt)[2])
   1403 {
   1404 	struct ieee80211com *ic = &sc->sc_ic;
   1405 	struct ifnet *ifp = &ic->ic_if;
   1406 	struct ifmultiaddr *ifma;
   1407 
   1408 	TAILQ_FOREACH(ifma, &ifp->if_multiaddrs, ifma_link) {
   1409 		caddr_t dl;
   1410 
   1411 		/* calculate XOR of eight 6bit values */
   1412 		dl = LLADDR((struct sockaddr_dl *) ifma->ifma_addr);
   1413 		ath_mcastfilter_accum(dl, &mfilt);
   1414 	}
   1415 }
   1416 #else
   1417 static void
   1418 ath_mcastfilter_compute(struct ath_softc *sc, u_int32_t (*mfilt)[2])
   1419 {
   1420 	struct ifnet *ifp = &sc->sc_ic.ic_if;
   1421 	struct ether_multi *enm;
   1422 	struct ether_multistep estep;
   1423 
   1424 	ETHER_FIRST_MULTI(estep, &sc->sc_ic.ic_ec, enm);
   1425 	while (enm != NULL) {
   1426 		/* XXX Punt on ranges. */
   1427 		if (!IEEE80211_ADDR_EQ(enm->enm_addrlo, enm->enm_addrhi)) {
   1428 			(*mfilt)[0] = (*mfilt)[1] = ~((u_int32_t)0);
   1429 			ifp->if_flags |= IFF_ALLMULTI;
   1430 			return;
   1431 		}
   1432 		ath_mcastfilter_accum(enm->enm_addrlo, mfilt);
   1433 		ETHER_NEXT_MULTI(estep, enm);
   1434 	}
   1435 	ifp->if_flags &= ~IFF_ALLMULTI;
   1436 }
   1437 #endif
   1438 
   1439 /*
   1440  * Calculate the receive filter according to the
   1441  * operating mode and state:
   1442  *
   1443  * o always accept unicast, broadcast, and multicast traffic
   1444  * o maintain current state of phy error reception
   1445  * o probe request frames are accepted only when operating in
   1446  *   hostap, adhoc, or monitor modes
   1447  * o enable promiscuous mode according to the interface state
   1448  * o accept beacons:
   1449  *   - when operating in adhoc mode so the 802.11 layer creates
   1450  *     node table entries for peers,
   1451  *   - when operating in station mode for collecting rssi data when
   1452  *     the station is otherwise quiet, or
   1453  *   - when scanning
   1454  */
   1455 static u_int32_t
   1456 ath_calcrxfilter(struct ath_softc *sc)
   1457 {
   1458 	struct ieee80211com *ic = &sc->sc_ic;
   1459 	struct ath_hal *ah = sc->sc_ah;
   1460 	struct ifnet *ifp = &ic->ic_if;
   1461 	u_int32_t rfilt;
   1462 
   1463 	rfilt = (ath_hal_getrxfilter(ah) & HAL_RX_FILTER_PHYERR)
   1464 	      | HAL_RX_FILTER_UCAST | HAL_RX_FILTER_BCAST | HAL_RX_FILTER_MCAST;
   1465 	if (ic->ic_opmode != IEEE80211_M_STA)
   1466 		rfilt |= HAL_RX_FILTER_PROBEREQ;
   1467 	if (ic->ic_opmode != IEEE80211_M_AHDEMO)
   1468 		rfilt |= HAL_RX_FILTER_BEACON;
   1469 	if (ifp->if_flags & IFF_PROMISC)
   1470 		rfilt |= HAL_RX_FILTER_PROM;
   1471 	return rfilt;
   1472 }
   1473 
   1474 static void
   1475 ath_mode_init(struct ath_softc *sc)
   1476 {
   1477 #ifdef __FreeBSD__
   1478 	struct ieee80211com *ic = &sc->sc_ic;
   1479 #endif
   1480 	struct ath_hal *ah = sc->sc_ah;
   1481 	u_int32_t rfilt, mfilt[2];
   1482 
   1483 	/* configure rx filter */
   1484 	rfilt = ath_calcrxfilter(sc);
   1485 	ath_hal_setrxfilter(ah, rfilt);
   1486 
   1487 	/* configure operational mode */
   1488 	ath_hal_setopmode(ah);
   1489 
   1490 	/* calculate and install multicast filter */
   1491 #ifdef __FreeBSD__
   1492 	if ((ic->ic_if.if_flags & IFF_ALLMULTI) == 0) {
   1493 		mfilt[0] = mfilt[1] = 0;
   1494 		ath_mcastfilter_compute(sc, &mfilt);
   1495 	} else {
   1496 		mfilt[0] = mfilt[1] = ~0;
   1497 	}
   1498 #endif
   1499 #ifdef __NetBSD__
   1500 	mfilt[0] = mfilt[1] = 0;
   1501 	ath_mcastfilter_compute(sc, &mfilt);
   1502 #endif
   1503 	ath_hal_setmcastfilter(ah, mfilt[0], mfilt[1]);
   1504 	DPRINTF(ATH_DEBUG_MODE, ("%s: RX filter 0x%x, MC filter %08x:%08x\n",
   1505 		__func__, rfilt, mfilt[0], mfilt[1]));
   1506 }
   1507 
   1508 #ifdef __FreeBSD__
   1509 static void
   1510 ath_mbuf_load_cb(void *arg, bus_dma_segment_t *seg, int nseg, bus_size_t mapsize, int error)
   1511 {
   1512 	struct ath_buf *bf = arg;
   1513 
   1514 	KASSERT(nseg <= ATH_MAX_SCATTER,
   1515 		("ath_mbuf_load_cb: too many DMA segments %u", nseg));
   1516 	bf->bf_mapsize = mapsize;
   1517 	bf->bf_nseg = nseg;
   1518 	bcopy(seg, bf->bf_segs, nseg * sizeof (seg[0]));
   1519 }
   1520 #endif /* __FreeBSD__ */
   1521 
   1522 static struct mbuf *
   1523 ath_getmbuf(int flags, int type, u_int pktlen)
   1524 {
   1525 	struct mbuf *m;
   1526 
   1527 	KASSERT(pktlen <= MCLBYTES, ("802.11 packet too large: %u", pktlen));
   1528 #ifdef __FreeBSD__
   1529 	if (pktlen <= MHLEN)
   1530 		MGETHDR(m, flags, type);
   1531 	else
   1532 		m = m_getcl(flags, type, M_PKTHDR);
   1533 #else
   1534 	MGETHDR(m, flags, type);
   1535 	if (m != NULL && pktlen > MHLEN) {
   1536 		MCLGET(m, flags);
   1537 		if ((m->m_flags & M_EXT) == 0) {
   1538 			m_free(m);
   1539 			m = NULL;
   1540 		}
   1541 	}
   1542 #endif
   1543 	return m;
   1544 }
   1545 
   1546 static int
   1547 ath_beacon_alloc(struct ath_softc *sc, struct ieee80211_node *ni)
   1548 {
   1549 	struct ieee80211com *ic = &sc->sc_ic;
   1550 	struct ifnet *ifp = &ic->ic_if;
   1551 	struct ath_hal *ah = sc->sc_ah;
   1552 	struct ieee80211_frame *wh;
   1553 	struct ath_buf *bf;
   1554 	struct ath_desc *ds;
   1555 	struct mbuf *m;
   1556 	int error, pktlen;
   1557 	u_int8_t *frm, rate;
   1558 	u_int16_t capinfo;
   1559 	struct ieee80211_rateset *rs;
   1560 	const HAL_RATE_TABLE *rt;
   1561 	u_int flags;
   1562 
   1563 	bf = sc->sc_bcbuf;
   1564 	if (bf->bf_m != NULL) {
   1565 		bus_dmamap_unload(sc->sc_dmat, bf->bf_dmamap);
   1566 		m_freem(bf->bf_m);
   1567 		bf->bf_m = NULL;
   1568 		bf->bf_node = NULL;
   1569 	}
   1570 	/*
   1571 	 * NB: the beacon data buffer must be 32-bit aligned;
   1572 	 * we assume the mbuf routines will return us something
   1573 	 * with this alignment (perhaps should assert).
   1574 	 */
   1575 	rs = &ni->ni_rates;
   1576 	pktlen = sizeof (struct ieee80211_frame)
   1577 	       + 8 + 2 + 2 + 2+ni->ni_esslen + 2+rs->rs_nrates + 3 + 6;
   1578 	if (rs->rs_nrates > IEEE80211_RATE_SIZE)
   1579 		pktlen += 2;
   1580 	m = ath_getmbuf(M_DONTWAIT, MT_DATA, pktlen);
   1581 	if (m == NULL) {
   1582 		DPRINTF(ATH_DEBUG_BEACON,
   1583 			("%s: cannot get mbuf/cluster; size %u\n",
   1584 			__func__, pktlen));
   1585 		sc->sc_stats.ast_be_nombuf++;
   1586 		return ENOMEM;
   1587 	}
   1588 
   1589 	wh = mtod(m, struct ieee80211_frame *);
   1590 	wh->i_fc[0] = IEEE80211_FC0_VERSION_0 | IEEE80211_FC0_TYPE_MGT |
   1591 	    IEEE80211_FC0_SUBTYPE_BEACON;
   1592 	wh->i_fc[1] = IEEE80211_FC1_DIR_NODS;
   1593 	*(u_int16_t *)wh->i_dur = 0;
   1594 	memcpy(wh->i_addr1, ifp->if_broadcastaddr, IEEE80211_ADDR_LEN);
   1595 	memcpy(wh->i_addr2, ic->ic_myaddr, IEEE80211_ADDR_LEN);
   1596 	memcpy(wh->i_addr3, ni->ni_bssid, IEEE80211_ADDR_LEN);
   1597 	*(u_int16_t *)wh->i_seq = 0;
   1598 
   1599 	/*
   1600 	 * beacon frame format
   1601 	 *	[8] time stamp
   1602 	 *	[2] beacon interval
   1603 	 *	[2] cabability information
   1604 	 *	[tlv] ssid
   1605 	 *	[tlv] supported rates
   1606 	 *	[tlv] parameter set (IBSS)
   1607 	 *	[tlv] extended supported rates
   1608 	 */
   1609 	frm = (u_int8_t *)&wh[1];
   1610 	memset(frm, 0, 8);	/* timestamp is set by hardware */
   1611 	frm += 8;
   1612 	*(u_int16_t *)frm = htole16(ni->ni_intval);
   1613 	frm += 2;
   1614 	if (ic->ic_opmode == IEEE80211_M_IBSS)
   1615 		capinfo = IEEE80211_CAPINFO_IBSS;
   1616 	else
   1617 		capinfo = IEEE80211_CAPINFO_ESS;
   1618 	if (ic->ic_flags & IEEE80211_F_PRIVACY)
   1619 		capinfo |= IEEE80211_CAPINFO_PRIVACY;
   1620 	if ((ic->ic_flags & IEEE80211_F_SHPREAMBLE) &&
   1621 	    IEEE80211_IS_CHAN_2GHZ(ni->ni_chan))
   1622 		capinfo |= IEEE80211_CAPINFO_SHORT_PREAMBLE;
   1623 	if (ic->ic_flags & IEEE80211_F_SHSLOT)
   1624 		capinfo |= IEEE80211_CAPINFO_SHORT_SLOTTIME;
   1625 	*(u_int16_t *)frm = htole16(capinfo);
   1626 	frm += 2;
   1627 	*frm++ = IEEE80211_ELEMID_SSID;
   1628 	*frm++ = ni->ni_esslen;
   1629 	memcpy(frm, ni->ni_essid, ni->ni_esslen);
   1630 	frm += ni->ni_esslen;
   1631 	frm = ieee80211_add_rates(frm, rs);
   1632 	*frm++ = IEEE80211_ELEMID_DSPARMS;
   1633 	*frm++ = 1;
   1634 	*frm++ = ieee80211_chan2ieee(ic, ni->ni_chan);
   1635 	if (ic->ic_opmode == IEEE80211_M_IBSS) {
   1636 		*frm++ = IEEE80211_ELEMID_IBSSPARMS;
   1637 		*frm++ = 2;
   1638 		*frm++ = 0; *frm++ = 0;		/* TODO: ATIM window */
   1639 	} else {
   1640 		/* TODO: TIM */
   1641 		*frm++ = IEEE80211_ELEMID_TIM;
   1642 		*frm++ = 4;	/* length */
   1643 		*frm++ = 0;	/* DTIM count */
   1644 		*frm++ = 1;	/* DTIM period */
   1645 		*frm++ = 0;	/* bitmap control */
   1646 		*frm++ = 0;	/* Partial Virtual Bitmap (variable length) */
   1647 	}
   1648 	frm = ieee80211_add_xrates(frm, rs);
   1649 	m->m_pkthdr.len = m->m_len = frm - mtod(m, u_int8_t *);
   1650 	KASSERT(m->m_pkthdr.len <= pktlen,
   1651 		("beacon bigger than expected, len %u calculated %u",
   1652 		m->m_pkthdr.len, pktlen));
   1653 
   1654 	DPRINTF(ATH_DEBUG_BEACON, ("%s: m %p len %u\n", __func__, m, m->m_len));
   1655 	error = ath_buf_dmamap_load_mbuf(sc->sc_dmat, bf, m, BUS_DMA_NOWAIT);
   1656 	if (error != 0) {
   1657 		m_freem(m);
   1658 		return error;
   1659 	}
   1660 	KASSERT(bf->bf_nseg == 1,
   1661 		("%s: multi-segment packet; nseg %u", __func__, bf->bf_nseg));
   1662 	bf->bf_m = m;
   1663 
   1664 	/* setup descriptors */
   1665 	ds = bf->bf_desc;
   1666 
   1667 	if (ic->ic_opmode == IEEE80211_M_IBSS)
   1668 		ds->ds_link = bf->bf_daddr;	/* link to self */
   1669 	else
   1670 		ds->ds_link = 0;
   1671 	ds->ds_data = bf->bf_segs[0].ds_addr;
   1672 
   1673 	DPRINTF(ATH_DEBUG_ANY, ("%s: segaddr %p seglen %u\n", __func__,
   1674 	    (caddr_t)bf->bf_segs[0].ds_addr, (u_int)bf->bf_segs[0].ds_len));
   1675 
   1676 	/*
   1677 	 * Calculate rate code.
   1678 	 * XXX everything at min xmit rate
   1679 	 */
   1680 	rt = sc->sc_currates;
   1681 	KASSERT(rt != NULL, ("no rate table, mode %u", sc->sc_curmode));
   1682 	if (ic->ic_flags & IEEE80211_F_SHPREAMBLE)
   1683 		rate = rt->info[0].rateCode | rt->info[0].shortPreamble;
   1684 	else
   1685 		rate = rt->info[0].rateCode;
   1686 
   1687 	flags = HAL_TXDESC_NOACK;
   1688 	if (ic->ic_opmode == IEEE80211_M_IBSS)
   1689 		flags |= HAL_TXDESC_VEOL;
   1690 
   1691 	if (!ath_hal_setuptxdesc(ah, ds
   1692 		, m->m_pkthdr.len + IEEE80211_CRC_LEN	/* packet length */
   1693 		, sizeof(struct ieee80211_frame)	/* header length */
   1694 		, HAL_PKT_TYPE_BEACON		/* Atheros packet type */
   1695 		, 0x20				/* txpower XXX */
   1696 		, rate, 1			/* series 0 rate/tries */
   1697 		, HAL_TXKEYIX_INVALID		/* no encryption */
   1698 		, 0				/* antenna mode */
   1699 		, flags				/* no ack for beacons */
   1700 		, 0				/* rts/cts rate */
   1701 		, 0				/* rts/cts duration */
   1702 	)) {
   1703 		printf("%s: ath_hal_setuptxdesc failed\n", __func__);
   1704 		return -1;
   1705 	}
   1706 	/* NB: beacon's BufLen must be a multiple of 4 bytes */
   1707 	/* XXX verify mbuf data area covers this roundup */
   1708 	if (!ath_hal_filltxdesc(ah, ds
   1709 		, roundup(bf->bf_segs[0].ds_len, 4)	/* buffer length */
   1710 		, AH_TRUE				/* first segment */
   1711 		, AH_TRUE				/* last segment */
   1712 	)) {
   1713 		printf("%s: ath_hal_filltxdesc failed\n", __func__);
   1714 		return -1;
   1715 	}
   1716 
   1717 	/* XXX it is not appropriate to bus_dmamap_sync? -dcy */
   1718 
   1719 	return 0;
   1720 }
   1721 
   1722 static void
   1723 ath_beacon_proc(struct ath_softc *sc, int pending)
   1724 {
   1725 	struct ieee80211com *ic = &sc->sc_ic;
   1726 	struct ath_buf *bf = sc->sc_bcbuf;
   1727 	struct ath_hal *ah = sc->sc_ah;
   1728 
   1729 	DPRINTF(ATH_DEBUG_BEACON_PROC, ("%s: pending %u\n", __func__, pending));
   1730 	if (ic->ic_opmode == IEEE80211_M_STA ||
   1731 	    bf == NULL || bf->bf_m == NULL) {
   1732 		DPRINTF(ATH_DEBUG_ANY, ("%s: ic_flags=%x bf=%p bf_m=%p\n",
   1733 			__func__, ic->ic_flags, bf, bf ? bf->bf_m : NULL));
   1734 		return;
   1735 	}
   1736 	/* TODO: update beacon to reflect PS poll state */
   1737 	if (!ath_hal_stoptxdma(ah, sc->sc_bhalq)) {
   1738 		DPRINTF(ATH_DEBUG_ANY, ("%s: beacon queue %u did not stop?\n",
   1739 			__func__, sc->sc_bhalq));
   1740 		/* NB: the HAL still stops DMA, so proceed */
   1741 	}
   1742 	ath_buf_dmamap_sync(sc->sc_dmat, bf, BUS_DMASYNC_PREWRITE);
   1743 
   1744 	ath_hal_puttxbuf(ah, sc->sc_bhalq, bf->bf_daddr);
   1745 	ath_hal_txstart(ah, sc->sc_bhalq);
   1746 	DPRINTF(ATH_DEBUG_BEACON_PROC,
   1747 		("%s: TXDP%u = %p (%p)\n", __func__,
   1748 		sc->sc_bhalq, (caddr_t)bf->bf_daddr, bf->bf_desc));
   1749 }
   1750 
   1751 static void
   1752 ath_beacon_free(struct ath_softc *sc)
   1753 {
   1754 	struct ath_buf *bf = sc->sc_bcbuf;
   1755 
   1756 	if (bf->bf_m != NULL) {
   1757 		bus_dmamap_unload(sc->sc_dmat, bf->bf_dmamap);
   1758 		m_freem(bf->bf_m);
   1759 		bf->bf_m = NULL;
   1760 		bf->bf_node = NULL;
   1761 	}
   1762 }
   1763 
   1764 /*
   1765  * Configure the beacon and sleep timers.
   1766  *
   1767  * When operating as an AP this resets the TSF and sets
   1768  * up the hardware to notify us when we need to issue beacons.
   1769  *
   1770  * When operating in station mode this sets up the beacon
   1771  * timers according to the timestamp of the last received
   1772  * beacon and the current TSF, configures PCF and DTIM
   1773  * handling, programs the sleep registers so the hardware
   1774  * will wakeup in time to receive beacons, and configures
   1775  * the beacon miss handling so we'll receive a BMISS
   1776  * interrupt when we stop seeing beacons from the AP
   1777  * we've associated with.
   1778  */
   1779 static void
   1780 ath_beacon_config(struct ath_softc *sc)
   1781 {
   1782 	struct ath_hal *ah = sc->sc_ah;
   1783 	struct ieee80211com *ic = &sc->sc_ic;
   1784 	struct ieee80211_node *ni = ic->ic_bss;
   1785 	u_int32_t nexttbtt, intval;
   1786 
   1787 	nexttbtt = (LE_READ_4(ni->ni_tstamp + 4) << 22) |
   1788 	    (LE_READ_4(ni->ni_tstamp) >> 10);
   1789 	DPRINTF(ATH_DEBUG_BEACON, ("%s: nexttbtt=%u\n", __func__, nexttbtt));
   1790 	nexttbtt += ni->ni_intval;
   1791 	intval = ni->ni_intval & HAL_BEACON_PERIOD;
   1792 	if (ic->ic_opmode == IEEE80211_M_STA) {
   1793 		HAL_BEACON_STATE bs;
   1794 		u_int32_t bmisstime;
   1795 
   1796 		/* NB: no PCF support right now */
   1797 		memset(&bs, 0, sizeof(bs));
   1798 		/*
   1799 		 * Reset our tsf so the hardware will update the
   1800 		 * tsf register to reflect timestamps found in
   1801 		 * received beacons.
   1802 		 */
   1803 		bs.bs_intval = intval | HAL_BEACON_RESET_TSF;
   1804 		bs.bs_nexttbtt = nexttbtt;
   1805 		bs.bs_dtimperiod = bs.bs_intval;
   1806 		bs.bs_nextdtim = nexttbtt;
   1807 		/*
   1808 		 * Calculate the number of consecutive beacons to miss
   1809 		 * before taking a BMISS interrupt.  The configuration
   1810 		 * is specified in ms, so we need to convert that to
   1811 		 * TU's and then calculate based on the beacon interval.
   1812 		 * Note that we clamp the result to at most 10 beacons.
   1813 		 */
   1814 		bmisstime = (ic->ic_bmisstimeout * 1000) / 1024;
   1815 		bs.bs_bmissthreshold = howmany(bmisstime,ni->ni_intval);
   1816 		if (bs.bs_bmissthreshold > 10)
   1817 			bs.bs_bmissthreshold = 10;
   1818 		else if (bs.bs_bmissthreshold <= 0)
   1819 			bs.bs_bmissthreshold = 1;
   1820 
   1821 		/*
   1822 		 * Calculate sleep duration.  The configuration is
   1823 		 * given in ms.  We insure a multiple of the beacon
   1824 		 * period is used.  Also, if the sleep duration is
   1825 		 * greater than the DTIM period then it makes senses
   1826 		 * to make it a multiple of that.
   1827 		 *
   1828 		 * XXX fixed at 100ms
   1829 		 */
   1830 		bs.bs_sleepduration =
   1831 			roundup((100 * 1000) / 1024, bs.bs_intval);
   1832 		if (bs.bs_sleepduration > bs.bs_dtimperiod)
   1833 			bs.bs_sleepduration = roundup(bs.bs_sleepduration, bs.bs_dtimperiod);
   1834 
   1835 		DPRINTF(ATH_DEBUG_BEACON,
   1836 			("%s: intval %u nexttbtt %u dtim %u nextdtim %u bmiss %u sleep %u\n"
   1837 			, __func__
   1838 			, bs.bs_intval
   1839 			, bs.bs_nexttbtt
   1840 			, bs.bs_dtimperiod
   1841 			, bs.bs_nextdtim
   1842 			, bs.bs_bmissthreshold
   1843 			, bs.bs_sleepduration
   1844 		));
   1845 		ath_hal_intrset(ah, 0);
   1846 		ath_hal_beacontimers(ah, &bs, 0/*XXX*/, 0, 0);
   1847 		sc->sc_imask |= HAL_INT_BMISS;
   1848 		ath_hal_intrset(ah, sc->sc_imask);
   1849 	} else {
   1850 		ath_hal_intrset(ah, 0);
   1851 		sc->sc_imask |= HAL_INT_SWBA;	/* beacon prepare */
   1852 		intval |= HAL_BEACON_ENA;
   1853 		switch (ic->ic_opmode) {
   1854 		/* No beacons in monitor, ad hoc-demo modes. */
   1855 		case IEEE80211_M_MONITOR:
   1856 		case IEEE80211_M_AHDEMO:
   1857 			intval &= ~HAL_BEACON_ENA;
   1858 			/*FALLTHROUGH*/
   1859 		/* In IBSS mode, I am uncertain how SWBA interrupts
   1860 		 * work, so I just turn them off and use a self-linked
   1861 		 * descriptor.
   1862 		 */
   1863 		case IEEE80211_M_IBSS:
   1864 			sc->sc_imask &= ~HAL_INT_SWBA;
   1865 			nexttbtt = ni->ni_intval;
   1866 			/*FALLTHROUGH*/
   1867 		case IEEE80211_M_HOSTAP:
   1868 		default:
   1869 			if (nexttbtt == ni->ni_intval)
   1870 				intval |= HAL_BEACON_RESET_TSF;
   1871 			break;
   1872 		}
   1873 		DPRINTF(ATH_DEBUG_BEACON, ("%s: intval %u nexttbtt %u\n",
   1874 			__func__, ni->ni_intval, nexttbtt));
   1875 		ath_hal_beaconinit(ah, nexttbtt, intval);
   1876 		ath_hal_intrset(ah, sc->sc_imask);
   1877 		if (ic->ic_opmode == IEEE80211_M_IBSS)
   1878 			ath_beacon_proc(sc, 0);
   1879 	}
   1880 }
   1881 
   1882 #ifdef __FreeBSD__
   1883 static void
   1884 ath_load_cb(void *arg, bus_dma_segment_t *segs, int nsegs, int error)
   1885 {
   1886 	bus_addr_t *paddr = (bus_addr_t*) arg;
   1887 	*paddr = segs->ds_addr;
   1888 }
   1889 #endif
   1890 
   1891 #ifdef __FreeBSD__
   1892 static int
   1893 ath_desc_alloc(struct ath_softc *sc)
   1894 {
   1895 	int i, bsize, error;
   1896 	struct ath_desc *ds;
   1897 	struct ath_buf *bf;
   1898 
   1899 	/* allocate descriptors */
   1900 	sc->sc_desc_len = sizeof(struct ath_desc) *
   1901 				(ATH_TXBUF * ATH_TXDESC + ATH_RXBUF + 1);
   1902 	error = bus_dmamap_create(sc->sc_dmat, BUS_DMA_NOWAIT, &sc->sc_ddmamap);
   1903 	if (error != 0)
   1904 		return error;
   1905 
   1906 	error = bus_dmamem_alloc(sc->sc_dmat, (void**) &sc->sc_desc,
   1907 				 BUS_DMA_NOWAIT, &sc->sc_ddmamap);
   1908 
   1909 	if (error != 0)
   1910 		goto fail0;
   1911 
   1912 	error = bus_dmamap_load(sc->sc_dmat, sc->sc_ddmamap,
   1913 				sc->sc_desc, sc->sc_desc_len,
   1914 				ath_load_cb, &sc->sc_desc_paddr,
   1915 				BUS_DMA_NOWAIT);
   1916 	if (error != 0)
   1917 		goto fail1;
   1918 
   1919 	ds = sc->sc_desc;
   1920 	DPRINTF(ATH_DEBUG_ANY, ("%s: DMA map: %p (%lu) -> %p (%lu)\n",
   1921 	    __func__, ds, (u_long) sc->sc_desc_len, (caddr_t) sc->sc_desc_paddr,
   1922 	    /*XXX*/ (u_long) sc->sc_desc_len));
   1923 
   1924 	/* allocate buffers */
   1925 	bsize = sizeof(struct ath_buf) * (ATH_TXBUF + ATH_RXBUF + 1);
   1926 	bf = malloc(bsize, M_DEVBUF, M_NOWAIT | M_ZERO);
   1927 	if (bf == NULL) {
   1928 		printf("%s: unable to allocate Tx/Rx buffers\n",
   1929 		    sc->sc_dev.dv_xname);
   1930 		error = -1;
   1931 		goto fail2;
   1932 	}
   1933 	sc->sc_bufptr = bf;
   1934 
   1935 	TAILQ_INIT(&sc->sc_rxbuf);
   1936 	for (i = 0; i < ATH_RXBUF; i++, bf++, ds++) {
   1937 		bf->bf_desc = ds;
   1938 		bf->bf_daddr = sc->sc_desc_paddr +
   1939 		    ((caddr_t)ds - (caddr_t)sc->sc_desc);
   1940 		error = bus_dmamap_create(sc->sc_dmat, BUS_DMA_NOWAIT,
   1941 					  &bf->bf_dmamap);
   1942 		if (error != 0)
   1943 			break;
   1944 		TAILQ_INSERT_TAIL(&sc->sc_rxbuf, bf, bf_list);
   1945 	}
   1946 
   1947 	TAILQ_INIT(&sc->sc_txbuf);
   1948 	for (i = 0; i < ATH_TXBUF; i++, bf++, ds += ATH_TXDESC) {
   1949 		bf->bf_desc = ds;
   1950 		bf->bf_daddr = sc->sc_desc_paddr +
   1951 		    ((caddr_t)ds - (caddr_t)sc->sc_desc);
   1952 		error = bus_dmamap_create(sc->sc_dmat, BUS_DMA_NOWAIT,
   1953 					  &bf->bf_dmamap);
   1954 		if (error != 0)
   1955 			break;
   1956 		TAILQ_INSERT_TAIL(&sc->sc_txbuf, bf, bf_list);
   1957 	}
   1958 	TAILQ_INIT(&sc->sc_txq);
   1959 
   1960 	/* beacon buffer */
   1961 	bf->bf_desc = ds;
   1962 	bf->bf_daddr = sc->sc_desc_paddr + ((caddr_t)ds - (caddr_t)sc->sc_desc);
   1963 	error = bus_dmamap_create(sc->sc_dmat, BUS_DMA_NOWAIT, &bf->bf_dmamap);
   1964 	if (error != 0)
   1965 		return error;
   1966 	sc->sc_bcbuf = bf;
   1967 	return 0;
   1968 
   1969 fail2:
   1970 	bus_dmamap_unload(sc->sc_dmat, sc->sc_ddmamap);
   1971 fail1:
   1972 	bus_dmamem_free(sc->sc_dmat, sc->sc_desc, sc->sc_ddmamap);
   1973 fail0:
   1974 	bus_dmamap_destroy(sc->sc_dmat, sc->sc_ddmamap);
   1975 	sc->sc_ddmamap = NULL;
   1976 	return error;
   1977 }
   1978 #else
   1979 static int
   1980 ath_desc_alloc(struct ath_softc *sc)
   1981 {
   1982 	int i, bsize, error = -1;
   1983 	struct ath_desc *ds;
   1984 	struct ath_buf *bf;
   1985 
   1986 	/* allocate descriptors */
   1987 	sc->sc_desc_len = sizeof(struct ath_desc) *
   1988 				(ATH_TXBUF * ATH_TXDESC + ATH_RXBUF + 1);
   1989 	if ((error = bus_dmamem_alloc(sc->sc_dmat, sc->sc_desc_len, PAGE_SIZE,
   1990 	    0, &sc->sc_dseg, 1, &sc->sc_dnseg, 0)) != 0) {
   1991 		printf("%s: unable to allocate control data, error = %d\n",
   1992 		    sc->sc_dev.dv_xname, error);
   1993 		goto fail0;
   1994 	}
   1995 
   1996 	if ((error = bus_dmamem_map(sc->sc_dmat, &sc->sc_dseg, sc->sc_dnseg,
   1997 	    sc->sc_desc_len, (caddr_t *)&sc->sc_desc, BUS_DMA_COHERENT)) != 0) {
   1998 		printf("%s: unable to map control data, error = %d\n",
   1999 		    sc->sc_dev.dv_xname, error);
   2000 		goto fail1;
   2001 	}
   2002 
   2003 	if ((error = bus_dmamap_create(sc->sc_dmat, sc->sc_desc_len, 1,
   2004 	    sc->sc_desc_len, 0, 0, &sc->sc_ddmamap)) != 0) {
   2005 		printf("%s: unable to create control data DMA map, "
   2006 		    "error = %d\n", sc->sc_dev.dv_xname, error);
   2007 		goto fail2;
   2008 	}
   2009 
   2010 	if ((error = bus_dmamap_load(sc->sc_dmat, sc->sc_ddmamap, sc->sc_desc,
   2011 	    sc->sc_desc_len, NULL, 0)) != 0) {
   2012 		printf("%s: unable to load control data DMA map, error = %d\n",
   2013 		    sc->sc_dev.dv_xname, error);
   2014 		goto fail3;
   2015 	}
   2016 
   2017 	ds = sc->sc_desc;
   2018 	sc->sc_desc_paddr = sc->sc_ddmamap->dm_segs[0].ds_addr;
   2019 
   2020 	DPRINTF(ATH_DEBUG_XMIT_DESC|ATH_DEBUG_RECV_DESC,
   2021 	    ("ath_desc_alloc: DMA map: %p (%lu) -> %p (%lu)\n",
   2022 	    ds, (u_long)sc->sc_desc_len,
   2023 	    (caddr_t) sc->sc_desc_paddr, /*XXX*/ (u_long) sc->sc_desc_len));
   2024 
   2025 	/* allocate buffers */
   2026 	bsize = sizeof(struct ath_buf) * (ATH_TXBUF + ATH_RXBUF + 1);
   2027 	bf = malloc(bsize, M_DEVBUF, M_NOWAIT | M_ZERO);
   2028 	if (bf == NULL) {
   2029 		printf("%s: unable to allocate Tx/Rx buffers\n",
   2030 		    sc->sc_dev.dv_xname);
   2031 		error = ENOMEM;
   2032 		goto fail3;
   2033 	}
   2034 	sc->sc_bufptr = bf;
   2035 
   2036 	TAILQ_INIT(&sc->sc_rxbuf);
   2037 	for (i = 0; i < ATH_RXBUF; i++, bf++, ds++) {
   2038 		bf->bf_desc = ds;
   2039 		bf->bf_daddr = sc->sc_desc_paddr +
   2040 		    ((caddr_t)ds - (caddr_t)sc->sc_desc);
   2041 		if ((error = bus_dmamap_create(sc->sc_dmat, MCLBYTES, 1,
   2042 		    MCLBYTES, 0, 0, &bf->bf_dmamap)) != 0) {
   2043 			printf("%s: unable to create Rx dmamap, error = %d\n",
   2044 			    sc->sc_dev.dv_xname, error);
   2045 			goto fail4;
   2046 		}
   2047 		TAILQ_INSERT_TAIL(&sc->sc_rxbuf, bf, bf_list);
   2048 	}
   2049 
   2050 	TAILQ_INIT(&sc->sc_txbuf);
   2051 	for (i = 0; i < ATH_TXBUF; i++, bf++, ds += ATH_TXDESC) {
   2052 		bf->bf_desc = ds;
   2053 		bf->bf_daddr = sc->sc_desc_paddr +
   2054 		    ((caddr_t)ds - (caddr_t)sc->sc_desc);
   2055 		if ((error = bus_dmamap_create(sc->sc_dmat, MCLBYTES,
   2056 		    ATH_TXDESC, MCLBYTES, 0, 0, &bf->bf_dmamap)) != 0) {
   2057 			printf("%s: unable to create Tx dmamap, error = %d\n",
   2058 			    sc->sc_dev.dv_xname, error);
   2059 			goto fail5;
   2060 		}
   2061 		TAILQ_INSERT_TAIL(&sc->sc_txbuf, bf, bf_list);
   2062 	}
   2063 	TAILQ_INIT(&sc->sc_txq);
   2064 
   2065 	/* beacon buffer */
   2066 	bf->bf_desc = ds;
   2067 	bf->bf_daddr = sc->sc_desc_paddr + ((caddr_t)ds - (caddr_t)sc->sc_desc);
   2068 	if ((error = bus_dmamap_create(sc->sc_dmat, MCLBYTES, 1, MCLBYTES, 0, 0,
   2069 	    &bf->bf_dmamap)) != 0) {
   2070 		printf("%s: unable to create beacon dmamap, error = %d\n",
   2071 		    sc->sc_dev.dv_xname, error);
   2072 		goto fail5;
   2073 	}
   2074 	sc->sc_bcbuf = bf;
   2075 	return 0;
   2076 
   2077 fail5:
   2078 	for (i = ATH_RXBUF; i < ATH_RXBUF + ATH_TXBUF; i++) {
   2079 		if (sc->sc_bufptr[i].bf_dmamap == NULL)
   2080 			continue;
   2081 		bus_dmamap_destroy(sc->sc_dmat, sc->sc_bufptr[i].bf_dmamap);
   2082 	}
   2083 fail4:
   2084 	for (i = 0; i < ATH_RXBUF; i++) {
   2085 		if (sc->sc_bufptr[i].bf_dmamap == NULL)
   2086 			continue;
   2087 		bus_dmamap_destroy(sc->sc_dmat, sc->sc_bufptr[i].bf_dmamap);
   2088 	}
   2089 fail3:
   2090 	bus_dmamap_unload(sc->sc_dmat, sc->sc_ddmamap);
   2091 fail2:
   2092 	bus_dmamap_destroy(sc->sc_dmat, sc->sc_ddmamap);
   2093 	sc->sc_ddmamap = NULL;
   2094 fail1:
   2095 	bus_dmamem_unmap(sc->sc_dmat, (caddr_t)sc->sc_desc, sc->sc_desc_len);
   2096 fail0:
   2097 	bus_dmamem_free(sc->sc_dmat, &sc->sc_dseg, sc->sc_dnseg);
   2098 	return error;
   2099 }
   2100 #endif
   2101 
   2102 static void
   2103 ath_desc_free(struct ath_softc *sc)
   2104 {
   2105 	struct ath_buf *bf;
   2106 
   2107 #ifdef __FreeBSD__
   2108 	bus_dmamap_unload(sc->sc_dmat, sc->sc_ddmamap);
   2109 	bus_dmamem_free(sc->sc_dmat, sc->sc_desc, sc->sc_ddmamap);
   2110 	bus_dmamap_destroy(sc->sc_dmat, sc->sc_ddmamap);
   2111 #else
   2112 	bus_dmamap_unload(sc->sc_dmat, sc->sc_ddmamap);
   2113 	bus_dmamap_destroy(sc->sc_dmat, sc->sc_ddmamap);
   2114 	bus_dmamem_free(sc->sc_dmat, &sc->sc_dseg, sc->sc_dnseg);
   2115 #endif
   2116 
   2117 	TAILQ_FOREACH(bf, &sc->sc_txq, bf_list) {
   2118 		bus_dmamap_unload(sc->sc_dmat, bf->bf_dmamap);
   2119 		bus_dmamap_destroy(sc->sc_dmat, bf->bf_dmamap);
   2120 		m_freem(bf->bf_m);
   2121 	}
   2122 	TAILQ_FOREACH(bf, &sc->sc_txbuf, bf_list)
   2123 		bus_dmamap_destroy(sc->sc_dmat, bf->bf_dmamap);
   2124 	TAILQ_FOREACH(bf, &sc->sc_rxbuf, bf_list) {
   2125 		if (bf->bf_m) {
   2126 			bus_dmamap_unload(sc->sc_dmat, bf->bf_dmamap);
   2127 			bus_dmamap_destroy(sc->sc_dmat, bf->bf_dmamap);
   2128 			m_freem(bf->bf_m);
   2129 			bf->bf_m = NULL;
   2130 		}
   2131 	}
   2132 	if (sc->sc_bcbuf != NULL) {
   2133 		bus_dmamap_unload(sc->sc_dmat, sc->sc_bcbuf->bf_dmamap);
   2134 		bus_dmamap_destroy(sc->sc_dmat, sc->sc_bcbuf->bf_dmamap);
   2135 		sc->sc_bcbuf = NULL;
   2136 	}
   2137 
   2138 	TAILQ_INIT(&sc->sc_rxbuf);
   2139 	TAILQ_INIT(&sc->sc_txbuf);
   2140 	TAILQ_INIT(&sc->sc_txq);
   2141 	free(sc->sc_bufptr, M_DEVBUF);
   2142 	sc->sc_bufptr = NULL;
   2143 }
   2144 
   2145 static struct ieee80211_node *
   2146 ath_node_alloc(struct ieee80211com *ic)
   2147 {
   2148 	struct ath_node *an =
   2149 		malloc(sizeof(struct ath_node), M_80211_NODE, M_NOWAIT|M_ZERO);
   2150 	if (an) {
   2151 		int i;
   2152 		for (i = 0; i < ATH_RHIST_SIZE; i++)
   2153 			an->an_rx_hist[i].arh_ticks = ATH_RHIST_NOTIME;
   2154 		an->an_rx_hist_next = ATH_RHIST_SIZE-1;
   2155 		return &an->an_node;
   2156 	} else
   2157 		return NULL;
   2158 }
   2159 
   2160 static void
   2161 ath_node_free(struct ieee80211com *ic, struct ieee80211_node *ni)
   2162 {
   2163 	struct ath_softc *sc = ic->ic_if.if_softc;
   2164 	struct ath_buf *bf;
   2165 
   2166 	TAILQ_FOREACH(bf, &sc->sc_txq, bf_list) {
   2167 		if (bf->bf_node == ni)
   2168 			bf->bf_node = NULL;
   2169 	}
   2170 	(*sc->sc_node_free)(ic, ni);
   2171 }
   2172 
   2173 static void
   2174 ath_node_copy(struct ieee80211com *ic,
   2175 	struct ieee80211_node *dst, const struct ieee80211_node *src)
   2176 {
   2177         struct ath_softc *sc = ic->ic_if.if_softc;
   2178 
   2179 	memcpy(&dst[1], &src[1],
   2180 		sizeof(struct ath_node) - sizeof(struct ieee80211_node));
   2181 	(*sc->sc_node_copy)(ic, dst, src);
   2182 }
   2183 
   2184 static u_int8_t
   2185 ath_node_getrssi(struct ieee80211com *ic, struct ieee80211_node *ni)
   2186 {
   2187 	struct ath_node *an = ATH_NODE(ni);
   2188 	int i, now, nsamples, rssi;
   2189 
   2190 	/*
   2191 	 * Calculate the average over the last second of sampled data.
   2192 	 */
   2193 	now = ATH_TICKS();
   2194 	nsamples = 0;
   2195 	rssi = 0;
   2196 	i = an->an_rx_hist_next;
   2197 	do {
   2198 		struct ath_recv_hist *rh = &an->an_rx_hist[i];
   2199 		if (rh->arh_ticks == ATH_RHIST_NOTIME)
   2200 			goto done;
   2201 		if (now - rh->arh_ticks > hz)
   2202 			goto done;
   2203 		rssi += rh->arh_rssi;
   2204 		nsamples++;
   2205 		if (i == 0)
   2206 			i = ATH_RHIST_SIZE-1;
   2207 		else
   2208 			i--;
   2209 	} while (i != an->an_rx_hist_next);
   2210 done:
   2211 	/*
   2212 	 * Return either the average or the last known
   2213 	 * value if there is no recent data.
   2214 	 */
   2215 	return (nsamples ? rssi / nsamples : an->an_rx_hist[i].arh_rssi);
   2216 }
   2217 
   2218 static int
   2219 ath_rxbuf_init(struct ath_softc *sc, struct ath_buf *bf)
   2220 {
   2221 	struct ath_hal *ah = sc->sc_ah;
   2222 	int error;
   2223 	struct mbuf *m;
   2224 	struct ath_desc *ds;
   2225 
   2226 	m = bf->bf_m;
   2227 	if (m == NULL) {
   2228 		/*
   2229 		 * NB: by assigning a page to the rx dma buffer we
   2230 		 * implicitly satisfy the Atheros requirement that
   2231 		 * this buffer be cache-line-aligned and sized to be
   2232 		 * multiple of the cache line size.  Not doing this
   2233 		 * causes weird stuff to happen (for the 5210 at least).
   2234 		 */
   2235 		m = ath_getmbuf(M_DONTWAIT, MT_DATA, MCLBYTES);
   2236 		if (m == NULL) {
   2237 			DPRINTF(ATH_DEBUG_ANY,
   2238 				("%s: no mbuf/cluster\n", __func__));
   2239 			sc->sc_stats.ast_rx_nombuf++;
   2240 			return ENOMEM;
   2241 		}
   2242 		bf->bf_m = m;
   2243 		m->m_pkthdr.len = m->m_len = m->m_ext.ext_size;
   2244 
   2245 		error = ath_buf_dmamap_load_mbuf(sc->sc_dmat, bf, m,
   2246 		                                 BUS_DMA_NOWAIT);
   2247 		if (error != 0) {
   2248 			DPRINTF(ATH_DEBUG_ANY,
   2249 				("%s: ath_buf_dmamap_load_mbuf failed;"
   2250 				" error %d\n", __func__, error));
   2251 			sc->sc_stats.ast_rx_busdma++;
   2252 			return error;
   2253 		}
   2254 		KASSERT(bf->bf_nseg == 1,
   2255 			("ath_rxbuf_init: multi-segment packet; nseg %u",
   2256 			bf->bf_nseg));
   2257 	}
   2258 	ath_buf_dmamap_sync(sc->sc_dmat, bf, BUS_DMASYNC_PREREAD);
   2259 
   2260 	/*
   2261 	 * Setup descriptors.  For receive we always terminate
   2262 	 * the descriptor list with a self-linked entry so we'll
   2263 	 * not get overrun under high load (as can happen with a
   2264 	 * 5212 when ANI processing enables PHY errors).
   2265 	 *
   2266 	 * To insure the last descriptor is self-linked we create
   2267 	 * each descriptor as self-linked and add it to the end.  As
   2268 	 * each additional descriptor is added the previous self-linked
   2269 	 * entry is ``fixed'' naturally.  This should be safe even
   2270 	 * if DMA is happening.  When processing RX interrupts we
   2271 	 * never remove/process the last, self-linked, entry on the
   2272 	 * descriptor list.  This insures the hardware always has
   2273 	 * someplace to write a new frame.
   2274 	 */
   2275 	ds = bf->bf_desc;
   2276 	ds->ds_link = bf->bf_daddr;	/* link to self */
   2277 	ds->ds_data = bf->bf_segs[0].ds_addr;
   2278 	ath_hal_setuprxdesc(ah, ds
   2279 		, m->m_len		/* buffer size */
   2280 		, 0
   2281 	);
   2282 
   2283 	if (sc->sc_rxlink != NULL)
   2284 		*sc->sc_rxlink = bf->bf_daddr;
   2285 	sc->sc_rxlink = &ds->ds_link;
   2286 	return 0;
   2287 }
   2288 
   2289 static void
   2290 ath_rx_proc(void *arg, int npending)
   2291 {
   2292 #define	PA2DESC(_sc, _pa) \
   2293 	((struct ath_desc *)((caddr_t)(_sc)->sc_desc + \
   2294 		((_pa) - (_sc)->sc_desc_paddr)))
   2295 	struct ath_softc *sc = arg;
   2296 	struct ath_buf *bf;
   2297 	struct ieee80211com *ic = &sc->sc_ic;
   2298 	struct ifnet *ifp = &ic->ic_if;
   2299 	struct ath_hal *ah = sc->sc_ah;
   2300 	struct ath_desc *ds;
   2301 	struct mbuf *m;
   2302 	struct ieee80211_frame *wh, whbuf;
   2303 	struct ieee80211_node *ni;
   2304 	struct ath_node *an;
   2305 	struct ath_recv_hist *rh;
   2306 	int len;
   2307 	u_int phyerr;
   2308 	HAL_STATUS status;
   2309 
   2310 	DPRINTF(ATH_DEBUG_RX_PROC, ("%s: pending %u\n", __func__, npending));
   2311 	do {
   2312 		bf = TAILQ_FIRST(&sc->sc_rxbuf);
   2313 		if (bf == NULL) {		/* NB: shouldn't happen */
   2314 			if_printf(ifp, "ath_rx_proc: no buffer!\n");
   2315 			break;
   2316 		}
   2317 		ds = bf->bf_desc;
   2318 		if (ds->ds_link == bf->bf_daddr) {
   2319 			/* NB: never process the self-linked entry at the end */
   2320 			break;
   2321 		}
   2322 		m = bf->bf_m;
   2323 		if (m == NULL) {		/* NB: shouldn't happen */
   2324 			if_printf(ifp, "ath_rx_proc: no mbuf!\n");
   2325 			continue;
   2326 		}
   2327 		/* XXX sync descriptor memory */
   2328 		/*
   2329 		 * Must provide the virtual address of the current
   2330 		 * descriptor, the physical address, and the virtual
   2331 		 * address of the next descriptor in the h/w chain.
   2332 		 * This allows the HAL to look ahead to see if the
   2333 		 * hardware is done with a descriptor by checking the
   2334 		 * done bit in the following descriptor and the address
   2335 		 * of the current descriptor the DMA engine is working
   2336 		 * on.  All this is necessary because of our use of
   2337 		 * a self-linked list to avoid rx overruns.
   2338 		 */
   2339 		status = ath_hal_rxprocdesc(ah, ds,
   2340 				bf->bf_daddr, PA2DESC(sc, ds->ds_link));
   2341 #ifdef AR_DEBUG
   2342 		if (ath_debug & ATH_DEBUG_RECV_DESC)
   2343 			ath_printrxbuf(bf, status == HAL_OK);
   2344 #endif
   2345 		if (status == HAL_EINPROGRESS)
   2346 			break;
   2347 		TAILQ_REMOVE(&sc->sc_rxbuf, bf, bf_list);
   2348 
   2349 		if (ds->ds_rxstat.rs_more) {
   2350 			/*
   2351 			 * Frame spans multiple descriptors; this
   2352 			 * cannot happen yet as we don't support
   2353 			 * jumbograms.  If not in monitor mode,
   2354 			 * discard the frame.
   2355 			 */
   2356 
   2357 			/* enable this if you want to see error frames in Monitor mode */
   2358 #ifdef ERROR_FRAMES
   2359 			if (ic->ic_opmode != IEEE80211_M_MONITOR) {
   2360 				/* XXX statistic */
   2361 				goto rx_next;
   2362 			}
   2363 #endif
   2364 			/* fall thru for monitor mode handling... */
   2365 
   2366 		} else if (ds->ds_rxstat.rs_status != 0) {
   2367 			if (ds->ds_rxstat.rs_status & HAL_RXERR_CRC)
   2368 				sc->sc_stats.ast_rx_crcerr++;
   2369 			if (ds->ds_rxstat.rs_status & HAL_RXERR_FIFO)
   2370 				sc->sc_stats.ast_rx_fifoerr++;
   2371 			if (ds->ds_rxstat.rs_status & HAL_RXERR_DECRYPT)
   2372 				sc->sc_stats.ast_rx_badcrypt++;
   2373 			if (ds->ds_rxstat.rs_status & HAL_RXERR_PHY) {
   2374 				sc->sc_stats.ast_rx_phyerr++;
   2375 				phyerr = ds->ds_rxstat.rs_phyerr & 0x1f;
   2376 				sc->sc_stats.ast_rx_phy[phyerr]++;
   2377 			}
   2378 
   2379 			/*
   2380 			 * reject error frames, we normally don't want
   2381 			 * to see them in monitor mode.
   2382 			 */
   2383 			if ((ds->ds_rxstat.rs_status & HAL_RXERR_DECRYPT ) ||
   2384 			    (ds->ds_rxstat.rs_status & HAL_RXERR_PHY))
   2385 			    goto rx_next;
   2386 
   2387 			/*
   2388 			 * In monitor mode, allow through packets that
   2389 			 * cannot be decrypted
   2390 			 */
   2391 			if ((ds->ds_rxstat.rs_status & ~HAL_RXERR_DECRYPT) ||
   2392 			    sc->sc_ic.ic_opmode != IEEE80211_M_MONITOR)
   2393 				goto rx_next;
   2394 		}
   2395 
   2396 		len = ds->ds_rxstat.rs_datalen;
   2397 		if (len < IEEE80211_MIN_LEN) {
   2398 			DPRINTF(ATH_DEBUG_RECV, ("%s: short packet %d\n",
   2399 				__func__, len));
   2400 			sc->sc_stats.ast_rx_tooshort++;
   2401 			goto rx_next;
   2402 		}
   2403 
   2404 		ath_buf_dmamap_sync(sc->sc_dmat, bf, BUS_DMASYNC_POSTREAD);
   2405 
   2406 		bus_dmamap_unload(sc->sc_dmat, bf->bf_dmamap);
   2407 		bf->bf_m = NULL;
   2408 		m->m_pkthdr.rcvif = ifp;
   2409 		m->m_pkthdr.len = m->m_len = len;
   2410 
   2411 #if NBPFILTER > 0
   2412 		if (sc->sc_drvbpf) {
   2413 			sc->sc_rx_th.wr_rate =
   2414 				sc->sc_hwmap[ds->ds_rxstat.rs_rate];
   2415 			sc->sc_rx_th.wr_antsignal = ds->ds_rxstat.rs_rssi;
   2416 			sc->sc_rx_th.wr_antenna = ds->ds_rxstat.rs_antenna;
   2417 			/* XXX TSF */
   2418 			bpf_mtap2(sc->sc_drvbpf,
   2419 				&sc->sc_rx_th, sc->sc_rx_th_len, m);
   2420 		}
   2421 #endif
   2422 
   2423 		m_adj(m, -IEEE80211_CRC_LEN);
   2424 		wh = mtod(m, struct ieee80211_frame *);
   2425 		if (wh->i_fc[1] & IEEE80211_FC1_WEP) {
   2426 			/*
   2427 			 * WEP is decrypted by hardware. Clear WEP bit
   2428 			 * and trim WEP header for ieee80211_input().
   2429 			 */
   2430 			wh->i_fc[1] &= ~IEEE80211_FC1_WEP;
   2431 			memcpy(&whbuf, wh, sizeof(whbuf));
   2432 			m_adj(m, IEEE80211_WEP_IVLEN + IEEE80211_WEP_KIDLEN);
   2433 			wh = mtod(m, struct ieee80211_frame *);
   2434 			memcpy(wh, &whbuf, sizeof(whbuf));
   2435 			/*
   2436 			 * Also trim WEP ICV from the tail.
   2437 			 */
   2438 			m_adj(m, -IEEE80211_WEP_CRCLEN);
   2439 			/*
   2440 			 * The header has probably moved.
   2441 			 */
   2442 			wh = mtod(m, struct ieee80211_frame *);
   2443 		}
   2444 
   2445 		/*
   2446 		 * Locate the node for sender, track state, and
   2447 		 * then pass this node (referenced) up to the 802.11
   2448 		 * layer for its use.
   2449 		 */
   2450 		ni = ieee80211_find_rxnode(ic, wh);
   2451 
   2452 		/*
   2453 		 * Record driver-specific state.
   2454 		 */
   2455 		an = ATH_NODE(ni);
   2456 		if (++(an->an_rx_hist_next) == ATH_RHIST_SIZE)
   2457 			an->an_rx_hist_next = 0;
   2458 		rh = &an->an_rx_hist[an->an_rx_hist_next];
   2459 		rh->arh_ticks = ATH_TICKS();
   2460 		rh->arh_rssi = ds->ds_rxstat.rs_rssi;
   2461 		rh->arh_antenna = ds->ds_rxstat.rs_antenna;
   2462 
   2463 		/*
   2464 		 * Send frame up for processing.
   2465 		 */
   2466 		ieee80211_input(ifp, m, ni,
   2467 			ds->ds_rxstat.rs_rssi, ds->ds_rxstat.rs_tstamp);
   2468 
   2469 		/*
   2470 		 * The frame may have caused the node to be marked for
   2471 		 * reclamation (e.g. in response to a DEAUTH message)
   2472 		 * so use release_node here instead of unref_node.
   2473 		 */
   2474 		ieee80211_release_node(ic, ni);
   2475   rx_next:
   2476 		TAILQ_INSERT_TAIL(&sc->sc_rxbuf, bf, bf_list);
   2477 	} while (ath_rxbuf_init(sc, bf) == 0);
   2478 
   2479 	ath_hal_rxmonitor(ah);			/* rx signal state monitoring */
   2480 	ath_hal_rxena(ah);			/* in case of RXEOL */
   2481 
   2482 #ifdef __NetBSD__
   2483 	if ((ifp->if_flags & IFF_OACTIVE) == 0 && !IFQ_IS_EMPTY(&ifp->if_snd))
   2484 		ath_start(ifp);
   2485 #endif /* __NetBSD__ */
   2486 #undef PA2DESC
   2487 }
   2488 
   2489 /*
   2490  * XXX Size of an ACK control frame in bytes.
   2491  */
   2492 #define	IEEE80211_ACK_SIZE	(2+2+IEEE80211_ADDR_LEN+4)
   2493 
   2494 static int
   2495 ath_tx_start(struct ath_softc *sc, struct ieee80211_node *ni, struct ath_buf *bf,
   2496     struct mbuf *m0)
   2497 {
   2498 	struct ieee80211com *ic = &sc->sc_ic;
   2499 	struct ath_hal *ah = sc->sc_ah;
   2500 	struct ifnet *ifp = &sc->sc_ic.ic_if;
   2501 	int i, error, iswep, hdrlen, pktlen;
   2502 	u_int8_t rix, cix, txrate, ctsrate;
   2503 	struct ath_desc *ds;
   2504 	struct mbuf *m;
   2505 	struct ieee80211_frame *wh;
   2506 	u_int32_t iv;
   2507 	u_int8_t *ivp;
   2508 	u_int8_t hdrbuf[sizeof(struct ieee80211_frame) +
   2509 	    IEEE80211_WEP_IVLEN + IEEE80211_WEP_KIDLEN];
   2510 	u_int subtype, flags, ctsduration, antenna;
   2511 	HAL_PKT_TYPE atype;
   2512 	const HAL_RATE_TABLE *rt;
   2513 	HAL_BOOL shortPreamble;
   2514 	struct ath_node *an;
   2515 	ath_txq_critsect_decl(s);
   2516 
   2517 	wh = mtod(m0, struct ieee80211_frame *);
   2518 	iswep = wh->i_fc[1] & IEEE80211_FC1_WEP;
   2519 	hdrlen = sizeof(struct ieee80211_frame);
   2520 	pktlen = m0->m_pkthdr.len;
   2521 
   2522 	if (iswep) {
   2523 		memcpy(hdrbuf, mtod(m0, caddr_t), hdrlen);
   2524 		m_adj(m0, hdrlen);
   2525 		M_PREPEND(m0, sizeof(hdrbuf), M_DONTWAIT);
   2526 		if (m0 == NULL) {
   2527 			sc->sc_stats.ast_tx_nombuf++;
   2528 			return ENOMEM;
   2529 		}
   2530 		ivp = hdrbuf + hdrlen;
   2531 		wh = mtod(m0, struct ieee80211_frame *);
   2532 		/*
   2533 		 * XXX
   2534 		 * IV must not duplicate during the lifetime of the key.
   2535 		 * But no mechanism to renew keys is defined in IEEE 802.11
   2536 		 * for WEP.  And the IV may be duplicated at other stations
   2537 		 * because the session key itself is shared.  So we use a
   2538 		 * pseudo random IV for now, though it is not the right way.
   2539 		 *
   2540 		 * NB: Rather than use a strictly random IV we select a
   2541 		 * random one to start and then increment the value for
   2542 		 * each frame.  This is an explicit tradeoff between
   2543 		 * overhead and security.  Given the basic insecurity of
   2544 		 * WEP this seems worthwhile.
   2545 		 */
   2546 
   2547 		/*
   2548 		 * Skip 'bad' IVs from Fluhrer/Mantin/Shamir:
   2549 		 * (B, 255, N) with 3 <= B < 16 and 0 <= N <= 255
   2550 		 */
   2551 		iv = ic->ic_iv;
   2552 		if ((iv & 0xff00) == 0xff00) {
   2553 			int B = (iv & 0xff0000) >> 16;
   2554 			if (3 <= B && B < 16)
   2555 				iv = (B+1) << 16;
   2556 		}
   2557 		ic->ic_iv = iv + 1;
   2558 
   2559 		/*
   2560 		 * NB: Preserve byte order of IV for packet
   2561 		 *     sniffers; it doesn't matter otherwise.
   2562 		 */
   2563 #if AH_BYTE_ORDER == AH_BIG_ENDIAN
   2564 		ivp[0] = iv >> 0;
   2565 		ivp[1] = iv >> 8;
   2566 		ivp[2] = iv >> 16;
   2567 #else
   2568 		ivp[2] = iv >> 0;
   2569 		ivp[1] = iv >> 8;
   2570 		ivp[0] = iv >> 16;
   2571 #endif
   2572 		ivp[3] = ic->ic_wep_txkey << 6; /* Key ID and pad */
   2573 		memcpy(mtod(m0, caddr_t), hdrbuf, sizeof(hdrbuf));
   2574 		/*
   2575 		 * The ICV length must be included into hdrlen and pktlen.
   2576 		 */
   2577 		hdrlen = sizeof(hdrbuf) + IEEE80211_WEP_CRCLEN;
   2578 		pktlen = m0->m_pkthdr.len + IEEE80211_WEP_CRCLEN;
   2579 	}
   2580 	pktlen += IEEE80211_CRC_LEN;
   2581 
   2582 	/*
   2583 	 * Load the DMA map so any coalescing is done.  This
   2584 	 * also calculates the number of descriptors we need.
   2585 	 */
   2586 	error = ath_buf_dmamap_load_mbuf(sc->sc_dmat, bf, m0, BUS_DMA_NOWAIT);
   2587 	/*
   2588 	 * Discard null packets and check for packets that
   2589 	 * require too many TX descriptors.  We try to convert
   2590 	 * the latter to a cluster.
   2591 	 */
   2592 	if (error == EFBIG) {		/* too many desc's, linearize */
   2593 		sc->sc_stats.ast_tx_linear++;
   2594 		MGETHDR(m, M_DONTWAIT, MT_DATA);
   2595 		if (m == NULL) {
   2596 			sc->sc_stats.ast_tx_nombuf++;
   2597 			m_freem(m0);
   2598 			return ENOMEM;
   2599 		}
   2600 #ifdef __FreeBSD__
   2601 		M_MOVE_PKTHDR(m, m0);
   2602 #else
   2603 		M_COPY_PKTHDR(m, m0);
   2604 #endif
   2605 		MCLGET(m, M_DONTWAIT);
   2606 		if ((m->m_flags & M_EXT) == 0) {
   2607 			sc->sc_stats.ast_tx_nomcl++;
   2608 			m_freem(m0);
   2609 			m_free(m);
   2610 			return ENOMEM;
   2611 		}
   2612 		m_copydata(m0, 0, m0->m_pkthdr.len, mtod(m, caddr_t));
   2613 		m_freem(m0);
   2614 		m->m_len = m->m_pkthdr.len;
   2615 		m0 = m;
   2616 		error = ath_buf_dmamap_load_mbuf(sc->sc_dmat, bf, m0,
   2617 					         BUS_DMA_NOWAIT);
   2618 		if (error != 0) {
   2619 			sc->sc_stats.ast_tx_busdma++;
   2620 			m_freem(m0);
   2621 			return error;
   2622 		}
   2623 		KASSERT(bf->bf_nseg == 1,
   2624 			("ath_tx_start: packet not one segment; nseg %u",
   2625 			bf->bf_nseg));
   2626 	} else if (error != 0) {
   2627 		sc->sc_stats.ast_tx_busdma++;
   2628 		m_freem(m0);
   2629 		return error;
   2630 	} else if (bf->bf_nseg == 0) {		/* null packet, discard */
   2631 		sc->sc_stats.ast_tx_nodata++;
   2632 		m_freem(m0);
   2633 		return EIO;
   2634 	}
   2635 	DPRINTF(ATH_DEBUG_XMIT, ("%s: m %p len %u\n", __func__, m0, pktlen));
   2636 	ath_buf_dmamap_sync(sc->sc_dmat, bf, BUS_DMASYNC_PREWRITE);
   2637 	bf->bf_m = m0;
   2638 	bf->bf_node = ni;			/* NB: held reference */
   2639 
   2640 	/* setup descriptors */
   2641 	ds = bf->bf_desc;
   2642 	rt = sc->sc_currates;
   2643 	KASSERT(rt != NULL, ("no rate table, mode %u", sc->sc_curmode));
   2644 
   2645 	/*
   2646 	 * Calculate Atheros packet type from IEEE80211 packet header
   2647 	 * and setup for rate calculations.
   2648 	 */
   2649 	atype = HAL_PKT_TYPE_NORMAL;			/* default */
   2650 	switch (wh->i_fc[0] & IEEE80211_FC0_TYPE_MASK) {
   2651 	case IEEE80211_FC0_TYPE_MGT:
   2652 		subtype = wh->i_fc[0] & IEEE80211_FC0_SUBTYPE_MASK;
   2653 		if (subtype == IEEE80211_FC0_SUBTYPE_BEACON)
   2654 			atype = HAL_PKT_TYPE_BEACON;
   2655 		else if (subtype == IEEE80211_FC0_SUBTYPE_PROBE_RESP)
   2656 			atype = HAL_PKT_TYPE_PROBE_RESP;
   2657 		else if (subtype == IEEE80211_FC0_SUBTYPE_ATIM)
   2658 			atype = HAL_PKT_TYPE_ATIM;
   2659 		rix = 0;			/* XXX lowest rate */
   2660 		break;
   2661 	case IEEE80211_FC0_TYPE_CTL:
   2662 		subtype = wh->i_fc[0] & IEEE80211_FC0_SUBTYPE_MASK;
   2663 		if (subtype == IEEE80211_FC0_SUBTYPE_PS_POLL)
   2664 			atype = HAL_PKT_TYPE_PSPOLL;
   2665 		rix = 0;			/* XXX lowest rate */
   2666 		break;
   2667 	default:
   2668 		rix = sc->sc_rixmap[ni->ni_rates.rs_rates[ni->ni_txrate] &
   2669 				IEEE80211_RATE_VAL];
   2670 		if (rix == 0xff) {
   2671 			if_printf(ifp, "bogus xmit rate 0x%x\n",
   2672 				ni->ni_rates.rs_rates[ni->ni_txrate]);
   2673 			sc->sc_stats.ast_tx_badrate++;
   2674 			m_freem(m0);
   2675 			return EIO;
   2676 		}
   2677 		break;
   2678 	}
   2679 	/*
   2680 	 * NB: the 802.11 layer marks whether or not we should
   2681 	 * use short preamble based on the current mode and
   2682 	 * negotiated parameters.
   2683 	 */
   2684 	if ((ic->ic_flags & IEEE80211_F_SHPREAMBLE) &&
   2685 	    (ni->ni_capinfo & IEEE80211_CAPINFO_SHORT_PREAMBLE)) {
   2686 		txrate = rt->info[rix].rateCode | rt->info[rix].shortPreamble;
   2687 		shortPreamble = AH_TRUE;
   2688 		sc->sc_stats.ast_tx_shortpre++;
   2689 	} else {
   2690 		txrate = rt->info[rix].rateCode;
   2691 		shortPreamble = AH_FALSE;
   2692 	}
   2693 
   2694 	/*
   2695 	 * Calculate miscellaneous flags.
   2696 	 */
   2697 	flags = HAL_TXDESC_CLRDMASK;		/* XXX needed for wep errors */
   2698 	if (IEEE80211_IS_MULTICAST(wh->i_addr1)) {
   2699 		flags |= HAL_TXDESC_NOACK;	/* no ack on broad/multicast */
   2700 		sc->sc_stats.ast_tx_noack++;
   2701 	} else if (pktlen > ic->ic_rtsthreshold) {
   2702 		flags |= HAL_TXDESC_RTSENA;	/* RTS based on frame length */
   2703 		sc->sc_stats.ast_tx_rts++;
   2704 	}
   2705 
   2706 	/*
   2707 	 * Calculate duration.  This logically belongs in the 802.11
   2708 	 * layer but it lacks sufficient information to calculate it.
   2709 	 */
   2710 	if ((flags & HAL_TXDESC_NOACK) == 0 &&
   2711 	    (wh->i_fc[0] & IEEE80211_FC0_TYPE_MASK) != IEEE80211_FC0_TYPE_CTL) {
   2712 		u_int16_t dur;
   2713 		/*
   2714 		 * XXX not right with fragmentation.
   2715 		 */
   2716 		dur = ath_hal_computetxtime(ah, rt, IEEE80211_ACK_SIZE,
   2717 				rix, shortPreamble);
   2718 		*((u_int16_t*) wh->i_dur) = htole16(dur);
   2719 	}
   2720 
   2721 	/*
   2722 	 * Calculate RTS/CTS rate and duration if needed.
   2723 	 */
   2724 	ctsduration = 0;
   2725 	if (flags & (HAL_TXDESC_RTSENA|HAL_TXDESC_CTSENA)) {
   2726 		/*
   2727 		 * CTS transmit rate is derived from the transmit rate
   2728 		 * by looking in the h/w rate table.  We must also factor
   2729 		 * in whether or not a short preamble is to be used.
   2730 		 */
   2731 		cix = rt->info[rix].controlRate;
   2732 		ctsrate = rt->info[cix].rateCode;
   2733 		if (shortPreamble)
   2734 			ctsrate |= rt->info[cix].shortPreamble;
   2735 		/*
   2736 		 * Compute the transmit duration based on the size
   2737 		 * of an ACK frame.  We call into the HAL to do the
   2738 		 * computation since it depends on the characteristics
   2739 		 * of the actual PHY being used.
   2740 		 */
   2741 		if (flags & HAL_TXDESC_RTSENA) {	/* SIFS + CTS */
   2742 			ctsduration += ath_hal_computetxtime(ah,
   2743 				rt, IEEE80211_ACK_SIZE, cix, shortPreamble);
   2744 		}
   2745 		/* SIFS + data */
   2746 		ctsduration += ath_hal_computetxtime(ah,
   2747 			rt, pktlen, rix, shortPreamble);
   2748 		if ((flags & HAL_TXDESC_NOACK) == 0) {	/* SIFS + ACK */
   2749 			ctsduration += ath_hal_computetxtime(ah,
   2750 				rt, IEEE80211_ACK_SIZE, cix, shortPreamble);
   2751 		}
   2752 	} else
   2753 		ctsrate = 0;
   2754 
   2755 	/*
   2756 	 * For now use the antenna on which the last good
   2757 	 * frame was received on.  We assume this field is
   2758 	 * initialized to 0 which gives us ``auto'' or the
   2759 	 * ``default'' antenna.
   2760 	 */
   2761 	an = (struct ath_node *) ni;
   2762 	if (an->an_tx_antenna)
   2763 		antenna = an->an_tx_antenna;
   2764 	else
   2765 		antenna = an->an_rx_hist[an->an_rx_hist_next].arh_antenna;
   2766 
   2767 	if (ic->ic_rawbpf)
   2768 		bpf_mtap(ic->ic_rawbpf, m0);
   2769 	if (sc->sc_drvbpf) {
   2770 		sc->sc_tx_th.wt_flags = 0;
   2771 		if (shortPreamble)
   2772 			sc->sc_tx_th.wt_flags |= IEEE80211_RADIOTAP_F_SHORTPRE;
   2773 		if (iswep)
   2774 			sc->sc_tx_th.wt_flags |= IEEE80211_RADIOTAP_F_WEP;
   2775 		sc->sc_tx_th.wt_rate = ni->ni_rates.rs_rates[ni->ni_txrate];
   2776 		sc->sc_tx_th.wt_txpower = 60/2;		/* XXX */
   2777 		sc->sc_tx_th.wt_antenna = antenna;
   2778 
   2779 		bpf_mtap2(sc->sc_drvbpf,
   2780 			&sc->sc_tx_th, sc->sc_tx_th_len, m0);
   2781 	}
   2782 
   2783 	/*
   2784 	 * Formulate first tx descriptor with tx controls.
   2785 	 */
   2786 	/* XXX check return value? */
   2787 	ath_hal_setuptxdesc(ah, ds
   2788 		, pktlen		/* packet length */
   2789 		, hdrlen		/* header length */
   2790 		, atype			/* Atheros packet type */
   2791 		, 60			/* txpower XXX */
   2792 		, txrate, 1+10		/* series 0 rate/tries */
   2793 		, iswep ? sc->sc_ic.ic_wep_txkey : HAL_TXKEYIX_INVALID
   2794 		, antenna		/* antenna mode */
   2795 		, flags			/* flags */
   2796 		, ctsrate		/* rts/cts rate */
   2797 		, ctsduration		/* rts/cts duration */
   2798 	);
   2799 #ifdef notyet
   2800 	ath_hal_setupxtxdesc(ah, ds
   2801 		, AH_FALSE		/* short preamble */
   2802 		, 0, 0			/* series 1 rate/tries */
   2803 		, 0, 0			/* series 2 rate/tries */
   2804 		, 0, 0			/* series 3 rate/tries */
   2805 	);
   2806 #endif
   2807 	/*
   2808 	 * Fillin the remainder of the descriptor info.
   2809 	 */
   2810 	for (i = 0; i < bf->bf_nseg; i++, ds++) {
   2811 		ds->ds_data = bf->bf_segs[i].ds_addr;
   2812 		if (i == bf->bf_nseg - 1)
   2813 			ds->ds_link = 0;
   2814 		else
   2815 			ds->ds_link = bf->bf_daddr + sizeof(*ds) * (i + 1);
   2816 		ath_hal_filltxdesc(ah, ds
   2817 			, bf->bf_segs[i].ds_len	/* segment length */
   2818 			, i == 0		/* first segment */
   2819 			, i == bf->bf_nseg - 1	/* last segment */
   2820 		);
   2821 		DPRINTF(ATH_DEBUG_XMIT,
   2822 			("%s: %d: %08x %08x %08x %08x %08x %08x\n",
   2823 			__func__, i, ds->ds_link, ds->ds_data,
   2824 			ds->ds_ctl0, ds->ds_ctl1, ds->ds_hw[0], ds->ds_hw[1]));
   2825 	}
   2826 
   2827 	/*
   2828 	 * Insert the frame on the outbound list and
   2829 	 * pass it on to the hardware.
   2830 	 */
   2831 	ath_txq_critsect_begin(sc, s);
   2832 	TAILQ_INSERT_TAIL(&sc->sc_txq, bf, bf_list);
   2833 	if (sc->sc_txlink == NULL) {
   2834 		ath_hal_puttxbuf(ah, sc->sc_txhalq, bf->bf_daddr);
   2835 		DPRINTF(ATH_DEBUG_XMIT, ("%s: TXDP0 = %p (%p)\n", __func__,
   2836 		    (caddr_t)bf->bf_daddr, bf->bf_desc));
   2837 	} else {
   2838 		*sc->sc_txlink = bf->bf_daddr;
   2839 		DPRINTF(ATH_DEBUG_XMIT, ("%s: link(%p)=%p (%p)\n", __func__,
   2840 		    sc->sc_txlink, (caddr_t)bf->bf_daddr, bf->bf_desc));
   2841 	}
   2842 	sc->sc_txlink = &bf->bf_desc[bf->bf_nseg - 1].ds_link;
   2843 	ath_txq_critsect_end(sc, s);
   2844 
   2845 	ath_hal_txstart(ah, sc->sc_txhalq);
   2846 	return 0;
   2847 }
   2848 
   2849 static void
   2850 ath_tx_proc(void *arg, int npending)
   2851 {
   2852 	struct ath_softc *sc = arg;
   2853 	struct ath_hal *ah = sc->sc_ah;
   2854 	struct ath_buf *bf;
   2855 	struct ieee80211com *ic = &sc->sc_ic;
   2856 	struct ifnet *ifp = &ic->ic_if;
   2857 	struct ath_desc *ds;
   2858 	struct ieee80211_node *ni;
   2859 	struct ath_node *an;
   2860 	int sr, lr;
   2861 	HAL_STATUS status;
   2862 	ath_txq_critsect_decl(s);
   2863 	ath_txbuf_critsect_decl(s2);
   2864 
   2865 	DPRINTF(ATH_DEBUG_TX_PROC, ("%s: pending %u tx queue %p, link %p\n",
   2866 		__func__, npending,
   2867 		(caddr_t)(uintptr_t) ath_hal_gettxbuf(sc->sc_ah, sc->sc_txhalq),
   2868 		sc->sc_txlink));
   2869 	for (;;) {
   2870 		ath_txq_critsect_begin(sc, s);
   2871 		bf = TAILQ_FIRST(&sc->sc_txq);
   2872 		if (bf == NULL) {
   2873 			sc->sc_txlink = NULL;
   2874 			ath_txq_critsect_end(sc, s);
   2875 			break;
   2876 		}
   2877 		/* only the last descriptor is needed */
   2878 		ds = &bf->bf_desc[bf->bf_nseg - 1];
   2879 		status = ath_hal_txprocdesc(ah, ds);
   2880 #ifdef AR_DEBUG
   2881 		if (ath_debug & ATH_DEBUG_XMIT_DESC)
   2882 			ath_printtxbuf(bf, status == HAL_OK);
   2883 #endif
   2884 		if (status == HAL_EINPROGRESS) {
   2885 			ath_txq_critsect_end(sc, s);
   2886 			break;
   2887 		}
   2888 		TAILQ_REMOVE(&sc->sc_txq, bf, bf_list);
   2889 		ath_txq_critsect_end(sc, s);
   2890 
   2891 		ni = bf->bf_node;
   2892 		if (ni != NULL) {
   2893 			an = (struct ath_node *) ni;
   2894 			if (ds->ds_txstat.ts_status == 0) {
   2895 				an->an_tx_ok++;
   2896 				an->an_tx_antenna = ds->ds_txstat.ts_antenna;
   2897 			} else {
   2898 				an->an_tx_err++;
   2899 				ifp->if_oerrors++;
   2900 				if (ds->ds_txstat.ts_status & HAL_TXERR_XRETRY)
   2901 					sc->sc_stats.ast_tx_xretries++;
   2902 				if (ds->ds_txstat.ts_status & HAL_TXERR_FIFO)
   2903 					sc->sc_stats.ast_tx_fifoerr++;
   2904 				if (ds->ds_txstat.ts_status & HAL_TXERR_FILT)
   2905 					sc->sc_stats.ast_tx_filtered++;
   2906 				an->an_tx_antenna = 0;	/* invalidate */
   2907 			}
   2908 			sr = ds->ds_txstat.ts_shortretry;
   2909 			lr = ds->ds_txstat.ts_longretry;
   2910 			sc->sc_stats.ast_tx_shortretry += sr;
   2911 			sc->sc_stats.ast_tx_longretry += lr;
   2912 			if (sr + lr)
   2913 				an->an_tx_retr++;
   2914 			/*
   2915 			 * Reclaim reference to node.
   2916 			 *
   2917 			 * NB: the node may be reclaimed here if, for example
   2918 			 *     this is a DEAUTH message that was sent and the
   2919 			 *     node was timed out due to inactivity.
   2920 			 */
   2921 			ieee80211_release_node(ic, ni);
   2922 		}
   2923 		ath_buf_dmamap_sync(sc->sc_dmat, bf, BUS_DMASYNC_POSTWRITE);
   2924 		bus_dmamap_unload(sc->sc_dmat, bf->bf_dmamap);
   2925 		m_freem(bf->bf_m);
   2926 		bf->bf_m = NULL;
   2927 		bf->bf_node = NULL;
   2928 
   2929 		ath_txbuf_critsect_begin(sc, s2);
   2930 		TAILQ_INSERT_TAIL(&sc->sc_txbuf, bf, bf_list);
   2931 		ath_txbuf_critsect_end(sc, s2);
   2932 	}
   2933 	ifp->if_flags &= ~IFF_OACTIVE;
   2934 	sc->sc_tx_timer = 0;
   2935 
   2936 	ath_start(ifp);
   2937 }
   2938 
   2939 /*
   2940  * Drain the transmit queue and reclaim resources.
   2941  */
   2942 static void
   2943 ath_draintxq(struct ath_softc *sc)
   2944 {
   2945 	struct ath_hal *ah = sc->sc_ah;
   2946 	struct ieee80211com *ic = &sc->sc_ic;
   2947 	struct ifnet *ifp = &ic->ic_if;
   2948 	struct ieee80211_node *ni;
   2949 	struct ath_buf *bf;
   2950 	ath_txq_critsect_decl(s);
   2951 	ath_txbuf_critsect_decl(s2);
   2952 
   2953 	/* XXX return value */
   2954 	if (!sc->sc_invalid) {
   2955 		/* don't touch the hardware if marked invalid */
   2956 		(void) ath_hal_stoptxdma(ah, sc->sc_txhalq);
   2957 		DPRINTF(ATH_DEBUG_RESET,
   2958 		    ("%s: tx queue %p, link %p\n", __func__,
   2959 		    (caddr_t)(uintptr_t) ath_hal_gettxbuf(ah, sc->sc_txhalq),
   2960 		    sc->sc_txlink));
   2961 		(void) ath_hal_stoptxdma(ah, sc->sc_bhalq);
   2962 		DPRINTF(ATH_DEBUG_RESET,
   2963 		    ("%s: beacon queue %p\n", __func__,
   2964 		    (caddr_t)(uintptr_t) ath_hal_gettxbuf(ah, sc->sc_bhalq)));
   2965 	}
   2966 	for (;;) {
   2967 		ath_txq_critsect_begin(sc, s);
   2968 		bf = TAILQ_FIRST(&sc->sc_txq);
   2969 		if (bf == NULL) {
   2970 			sc->sc_txlink = NULL;
   2971 			ath_txq_critsect_end(sc, s);
   2972 			break;
   2973 		}
   2974 		TAILQ_REMOVE(&sc->sc_txq, bf, bf_list);
   2975 		ath_txq_critsect_end(sc, s);
   2976 #ifdef AR_DEBUG
   2977 		if (ath_debug & ATH_DEBUG_RESET)
   2978 			ath_printtxbuf(bf,
   2979 				ath_hal_txprocdesc(ah, bf->bf_desc) == HAL_OK);
   2980 #endif /* AR_DEBUG */
   2981 		bus_dmamap_unload(sc->sc_dmat, bf->bf_dmamap);
   2982 		m_freem(bf->bf_m);
   2983 		bf->bf_m = NULL;
   2984 		ni = bf->bf_node;
   2985 		bf->bf_node = NULL;
   2986 		ath_txbuf_critsect_begin(sc, s2);
   2987 		if (ni != NULL) {
   2988 			/*
   2989 			 * Reclaim node reference.
   2990 			 */
   2991 			ieee80211_release_node(ic, ni);
   2992 		}
   2993 		TAILQ_INSERT_TAIL(&sc->sc_txbuf, bf, bf_list);
   2994 		ath_txbuf_critsect_end(sc, s2);
   2995 	}
   2996 	ifp->if_flags &= ~IFF_OACTIVE;
   2997 	sc->sc_tx_timer = 0;
   2998 }
   2999 
   3000 /*
   3001  * Disable the receive h/w in preparation for a reset.
   3002  */
   3003 static void
   3004 ath_stoprecv(struct ath_softc *sc)
   3005 {
   3006 #define	PA2DESC(_sc, _pa) \
   3007 	((struct ath_desc *)((caddr_t)(_sc)->sc_desc + \
   3008 		((_pa) - (_sc)->sc_desc_paddr)))
   3009 	struct ath_hal *ah = sc->sc_ah;
   3010 
   3011 	ath_hal_stoppcurecv(ah);	/* disable PCU */
   3012 	ath_hal_setrxfilter(ah, 0);	/* clear recv filter */
   3013 	ath_hal_stopdmarecv(ah);	/* disable DMA engine */
   3014 	DELAY(3000);			/* long enough for 1 frame */
   3015 #ifdef AR_DEBUG
   3016 	if (ath_debug & ATH_DEBUG_RESET) {
   3017 		struct ath_buf *bf;
   3018 
   3019 		printf("%s: rx queue %p, link %p\n", __func__,
   3020 			(caddr_t)(uintptr_t) ath_hal_getrxbuf(ah), sc->sc_rxlink);
   3021 		TAILQ_FOREACH(bf, &sc->sc_rxbuf, bf_list) {
   3022 			struct ath_desc *ds = bf->bf_desc;
   3023 			if (ath_hal_rxprocdesc(ah, ds, bf->bf_daddr,
   3024 			    PA2DESC(sc, ds->ds_link)) == HAL_OK)
   3025 				ath_printrxbuf(bf, 1);
   3026 		}
   3027 	}
   3028 #endif
   3029 	sc->sc_rxlink = NULL;		/* just in case */
   3030 #undef PA2DESC
   3031 }
   3032 
   3033 /*
   3034  * Enable the receive h/w following a reset.
   3035  */
   3036 static int
   3037 ath_startrecv(struct ath_softc *sc)
   3038 {
   3039 	struct ath_hal *ah = sc->sc_ah;
   3040 	struct ath_buf *bf;
   3041 
   3042 	sc->sc_rxlink = NULL;
   3043 	TAILQ_FOREACH(bf, &sc->sc_rxbuf, bf_list) {
   3044 		int error = ath_rxbuf_init(sc, bf);
   3045 		if (error != 0) {
   3046 			DPRINTF(ATH_DEBUG_RECV,
   3047 				("%s: ath_rxbuf_init failed %d\n",
   3048 				__func__, error));
   3049 			return error;
   3050 		}
   3051 	}
   3052 
   3053 	bf = TAILQ_FIRST(&sc->sc_rxbuf);
   3054 	ath_hal_putrxbuf(ah, bf->bf_daddr);
   3055 	ath_hal_rxena(ah);		/* enable recv descriptors */
   3056 	ath_mode_init(sc);		/* set filters, etc. */
   3057 	ath_hal_startpcurecv(ah);	/* re-enable PCU/DMA engine */
   3058 	return 0;
   3059 }
   3060 
   3061 /*
   3062  * Set/change channels.  If the channel is really being changed,
   3063  * it's done by resetting the chip.  To accomplish this we must
   3064  * first cleanup any pending DMA, then restart stuff after a la
   3065  * ath_init.
   3066  */
   3067 static int
   3068 ath_chan_set(struct ath_softc *sc, struct ieee80211_channel *chan)
   3069 {
   3070 	struct ath_hal *ah = sc->sc_ah;
   3071 	struct ieee80211com *ic = &sc->sc_ic;
   3072 
   3073 	DPRINTF(ATH_DEBUG_ANY, ("%s: %u (%u MHz) -> %u (%u MHz)\n", __func__,
   3074 	    ieee80211_chan2ieee(ic, ic->ic_ibss_chan),
   3075 		ic->ic_ibss_chan->ic_freq,
   3076 	    ieee80211_chan2ieee(ic, chan), chan->ic_freq));
   3077 	if (chan != ic->ic_ibss_chan) {
   3078 		HAL_STATUS status;
   3079 		HAL_CHANNEL hchan;
   3080 		enum ieee80211_phymode mode;
   3081 
   3082 		/*
   3083 		 * To switch channels clear any pending DMA operations;
   3084 		 * wait long enough for the RX fifo to drain, reset the
   3085 		 * hardware at the new frequency, and then re-enable
   3086 		 * the relevant bits of the h/w.
   3087 		 */
   3088 		ath_hal_intrset(ah, 0);		/* disable interrupts */
   3089 		ath_draintxq(sc);		/* clear pending tx frames */
   3090 		ath_stoprecv(sc);		/* turn off frame recv */
   3091 		/*
   3092 		 * Convert to a HAL channel description with
   3093 		 * the flags constrained to reflect the current
   3094 		 * operating mode.
   3095 		 */
   3096 		hchan.channel = chan->ic_freq;
   3097 		hchan.channelFlags = ath_chan2flags(ic, chan);
   3098 		if (!ath_hal_reset(ah, ic->ic_opmode, &hchan, AH_TRUE, &status)) {
   3099 			if_printf(&ic->ic_if, "ath_chan_set: unable to reset "
   3100 				"channel %u (%u Mhz)\n",
   3101 				ieee80211_chan2ieee(ic, chan), chan->ic_freq);
   3102 			return EIO;
   3103 		}
   3104 		/*
   3105 		 * Re-enable rx framework.
   3106 		 */
   3107 		if (ath_startrecv(sc) != 0) {
   3108 			if_printf(&ic->ic_if,
   3109 				"ath_chan_set: unable to restart recv logic\n");
   3110 			return EIO;
   3111 		}
   3112 
   3113 		/*
   3114 		 * Update BPF state.
   3115 		 */
   3116 		sc->sc_tx_th.wt_chan_freq = sc->sc_rx_th.wr_chan_freq =
   3117 			htole16(chan->ic_freq);
   3118 		sc->sc_tx_th.wt_chan_flags = sc->sc_rx_th.wr_chan_flags =
   3119 			htole16(chan->ic_flags);
   3120 
   3121 		/*
   3122 		 * Change channels and update the h/w rate map
   3123 		 * if we're switching; e.g. 11a to 11b/g.
   3124 		 */
   3125 		ic->ic_ibss_chan = chan;
   3126 		mode = ieee80211_chan2mode(ic, chan);
   3127 		if (mode != sc->sc_curmode)
   3128 			ath_setcurmode(sc, mode);
   3129 
   3130 		/*
   3131 		 * Re-enable interrupts.
   3132 		 */
   3133 		ath_hal_intrset(ah, sc->sc_imask);
   3134 	}
   3135 	return 0;
   3136 }
   3137 
   3138 static void
   3139 ath_next_scan(void *arg)
   3140 {
   3141 	struct ath_softc *sc = arg;
   3142 	struct ieee80211com *ic = &sc->sc_ic;
   3143 	int s;
   3144 
   3145 	/* don't call ath_start w/o network interrupts blocked */
   3146 	s = splnet();
   3147 
   3148 	if (ic->ic_state == IEEE80211_S_SCAN)
   3149 		ieee80211_next_scan(ic);
   3150 	splx(s);
   3151 }
   3152 
   3153 /*
   3154  * Periodically recalibrate the PHY to account
   3155  * for temperature/environment changes.
   3156  */
   3157 static void
   3158 ath_calibrate(void *arg)
   3159 {
   3160 	struct ath_softc *sc = arg;
   3161 	struct ath_hal *ah = sc->sc_ah;
   3162 	struct ieee80211com *ic = &sc->sc_ic;
   3163 	struct ieee80211_channel *c;
   3164 	HAL_CHANNEL hchan;
   3165 
   3166 	sc->sc_stats.ast_per_cal++;
   3167 
   3168 	/*
   3169 	 * Convert to a HAL channel description with the flags
   3170 	 * constrained to reflect the current operating mode.
   3171 	 */
   3172 	c = ic->ic_ibss_chan;
   3173 	hchan.channel = c->ic_freq;
   3174 	hchan.channelFlags = ath_chan2flags(ic, c);
   3175 
   3176 	DPRINTF(ATH_DEBUG_CALIBRATE,
   3177 		("%s: channel %u/%x\n", __func__, c->ic_freq, c->ic_flags));
   3178 
   3179 	if (ath_hal_getrfgain(ah) == HAL_RFGAIN_NEED_CHANGE) {
   3180 		/*
   3181 		 * Rfgain is out of bounds, reset the chip
   3182 		 * to load new gain values.
   3183 		 */
   3184 		sc->sc_stats.ast_per_rfgain++;
   3185 		ath_reset(sc);
   3186 	}
   3187 	if (!ath_hal_calibrate(ah, &hchan)) {
   3188 		DPRINTF(ATH_DEBUG_ANY,
   3189 			("%s: calibration of channel %u failed\n",
   3190 			__func__, c->ic_freq));
   3191 		sc->sc_stats.ast_per_calfail++;
   3192 	}
   3193 	callout_reset(&sc->sc_cal_ch, hz * ath_calinterval, ath_calibrate, sc);
   3194 }
   3195 
   3196 static HAL_LED_STATE
   3197 ath_state_to_led(enum ieee80211_state state)
   3198 {
   3199 	switch (state) {
   3200 	case IEEE80211_S_INIT:
   3201 		return HAL_LED_INIT;
   3202 	case IEEE80211_S_SCAN:
   3203 		return HAL_LED_SCAN;
   3204 	case IEEE80211_S_AUTH:
   3205 		return HAL_LED_AUTH;
   3206 	case IEEE80211_S_ASSOC:
   3207 		return HAL_LED_ASSOC;
   3208 	case IEEE80211_S_RUN:
   3209 		return HAL_LED_RUN;
   3210 	default:
   3211 		panic("%s: unknown 802.11 state %d\n", __func__, state);
   3212 		return HAL_LED_INIT;
   3213 	}
   3214 }
   3215 
   3216 static int
   3217 ath_newstate(struct ieee80211com *ic, enum ieee80211_state nstate, int arg)
   3218 {
   3219 	struct ifnet *ifp = &ic->ic_if;
   3220 	struct ath_softc *sc = ifp->if_softc;
   3221 	struct ath_hal *ah = sc->sc_ah;
   3222 	struct ieee80211_node *ni;
   3223 	int i, error;
   3224 	const u_int8_t *bssid;
   3225 	u_int32_t rfilt;
   3226 
   3227 	DPRINTF(ATH_DEBUG_ANY, ("%s: %s -> %s\n", __func__,
   3228 		ieee80211_state_name[ic->ic_state],
   3229 		ieee80211_state_name[nstate]));
   3230 
   3231 	ath_hal_setledstate(ah, ath_state_to_led(nstate));	/* set LED */
   3232 
   3233 	if (nstate == IEEE80211_S_INIT) {
   3234 		sc->sc_imask &= ~(HAL_INT_SWBA | HAL_INT_BMISS);
   3235 		ath_hal_intrset(ah, sc->sc_imask);
   3236 		callout_stop(&sc->sc_scan_ch);
   3237 		callout_stop(&sc->sc_cal_ch);
   3238 		return (*sc->sc_newstate)(ic, nstate, arg);
   3239 	}
   3240 	ni = ic->ic_bss;
   3241 	error = ath_chan_set(sc, ni->ni_chan);
   3242 	if (error != 0)
   3243 		goto bad;
   3244 	rfilt = ath_calcrxfilter(sc);
   3245 	if (nstate == IEEE80211_S_SCAN) {
   3246 		callout_reset(&sc->sc_scan_ch, (hz * ath_dwelltime) / 1000,
   3247 			ath_next_scan, sc);
   3248 		bssid = ifp->if_broadcastaddr;
   3249 	} else {
   3250 		callout_stop(&sc->sc_scan_ch);
   3251 		bssid = ni->ni_bssid;
   3252 	}
   3253 	ath_hal_setrxfilter(ah, rfilt);
   3254 	DPRINTF(ATH_DEBUG_ANY, ("%s: RX filter 0x%x bssid %s\n",
   3255 		 __func__, rfilt, ether_sprintf(bssid)));
   3256 
   3257 	if (nstate == IEEE80211_S_RUN && ic->ic_opmode == IEEE80211_M_STA)
   3258 		ath_hal_setassocid(ah, bssid, ni->ni_associd);
   3259 	else
   3260 		ath_hal_setassocid(ah, bssid, 0);
   3261 	if (ic->ic_flags & IEEE80211_F_PRIVACY) {
   3262 		for (i = 0; i < IEEE80211_WEP_NKID; i++)
   3263 			if (ath_hal_keyisvalid(ah, i))
   3264 				ath_hal_keysetmac(ah, i, bssid);
   3265 	}
   3266 
   3267 	if (nstate == IEEE80211_S_RUN) {
   3268 		DPRINTF(ATH_DEBUG_ANY, ("%s(RUN): ic_flags=0x%08x iv=%d bssid=%s "
   3269 			"capinfo=0x%04x chan=%d\n"
   3270 			 , __func__
   3271 			 , ic->ic_flags
   3272 			 , ni->ni_intval
   3273 			 , ether_sprintf(ni->ni_bssid)
   3274 			 , ni->ni_capinfo
   3275 			 , ieee80211_chan2ieee(ic, ni->ni_chan)));
   3276 
   3277 		/*
   3278 		 * Allocate and setup the beacon frame for AP or adhoc mode.
   3279 		 */
   3280 		if (ic->ic_opmode == IEEE80211_M_HOSTAP ||
   3281 		    ic->ic_opmode == IEEE80211_M_IBSS) {
   3282 			error = ath_beacon_alloc(sc, ni);
   3283 			if (error != 0)
   3284 				goto bad;
   3285 		}
   3286 
   3287 		/*
   3288 		 * Configure the beacon and sleep timers.
   3289 		 */
   3290 		ath_beacon_config(sc);
   3291 
   3292 		/* start periodic recalibration timer */
   3293 		callout_reset(&sc->sc_cal_ch, hz * ath_calinterval,
   3294 			ath_calibrate, sc);
   3295 	} else {
   3296 		sc->sc_imask &= ~(HAL_INT_SWBA | HAL_INT_BMISS);
   3297 		ath_hal_intrset(ah, sc->sc_imask);
   3298 		callout_stop(&sc->sc_cal_ch);		/* no calibration */
   3299 	}
   3300 	/*
   3301 	 * Reset the rate control state.
   3302 	 */
   3303 	ath_rate_ctl_reset(sc, nstate);
   3304 	/*
   3305 	 * Invoke the parent method to complete the work.
   3306 	 */
   3307 	return (*sc->sc_newstate)(ic, nstate, arg);
   3308 bad:
   3309 	callout_stop(&sc->sc_scan_ch);
   3310 	callout_stop(&sc->sc_cal_ch);
   3311 	/* NB: do not invoke the parent */
   3312 	return error;
   3313 }
   3314 
   3315 static void
   3316 ath_recv_mgmt(struct ieee80211com *ic, struct mbuf *m,
   3317     struct ieee80211_node *ni, int subtype, int rssi, u_int32_t rstamp)
   3318 {
   3319 	struct ath_softc *sc = (struct ath_softc*)ic->ic_softc;
   3320 	struct ath_hal *ah = sc->sc_ah;
   3321 
   3322 	(*sc->sc_recv_mgmt)(ic, m, ni, subtype, rssi, rstamp);
   3323 
   3324 	switch (subtype) {
   3325 	case IEEE80211_FC0_SUBTYPE_PROBE_RESP:
   3326 	case IEEE80211_FC0_SUBTYPE_BEACON:
   3327 		if (ic->ic_opmode != IEEE80211_M_IBSS ||
   3328 		    ic->ic_state != IEEE80211_S_RUN)
   3329 			break;
   3330 		if (ieee80211_ibss_merge(ic, ni, ath_hal_gettsf64(ah)) ==
   3331 		    ENETRESET)
   3332 			ath_hal_setassocid(ah, ic->ic_bss->ni_bssid, 0);
   3333 		break;
   3334 	default:
   3335 		break;
   3336 	}
   3337 	return;
   3338 }
   3339 
   3340 /*
   3341  * Setup driver-specific state for a newly associated node.
   3342  * Note that we're called also on a re-associate, the isnew
   3343  * param tells us if this is the first time or not.
   3344  */
   3345 static void
   3346 ath_newassoc(struct ieee80211com *ic, struct ieee80211_node *ni, int isnew)
   3347 {
   3348 	if (isnew) {
   3349 		struct ath_node *an = (struct ath_node *) ni;
   3350 
   3351 		an->an_tx_ok = an->an_tx_err =
   3352 			an->an_tx_retr = an->an_tx_upper = 0;
   3353 		/* start with highest negotiated rate */
   3354 		/*
   3355 		 * XXX should do otherwise but only when
   3356 		 * the rate control algorithm is better.
   3357 		 */
   3358 		KASSERT(ni->ni_rates.rs_nrates > 0,
   3359 			("new association w/ no rates!"));
   3360 		ni->ni_txrate = ni->ni_rates.rs_nrates - 1;
   3361 	}
   3362 }
   3363 
   3364 static int
   3365 ath_getchannels(struct ath_softc *sc, u_int cc, HAL_BOOL outdoor,
   3366     HAL_BOOL xchanmode)
   3367 {
   3368 	struct ieee80211com *ic = &sc->sc_ic;
   3369 	struct ifnet *ifp = &ic->ic_if;
   3370 	struct ath_hal *ah = sc->sc_ah;
   3371 	HAL_CHANNEL *chans;
   3372 	int i, ix, nchan;
   3373 
   3374 	chans = malloc(IEEE80211_CHAN_MAX * sizeof(HAL_CHANNEL),
   3375 			M_TEMP, M_NOWAIT);
   3376 	if (chans == NULL) {
   3377 		if_printf(ifp, "unable to allocate channel table\n");
   3378 		return ENOMEM;
   3379 	}
   3380 	if (!ath_hal_init_channels(ah, chans, IEEE80211_CHAN_MAX, &nchan,
   3381 	    cc, HAL_MODE_ALL, outdoor, xchanmode)) {
   3382 		if_printf(ifp, "unable to collect channel list from hal\n");
   3383 		free(chans, M_TEMP);
   3384 		return EINVAL;
   3385 	}
   3386 
   3387 	/*
   3388 	 * Convert HAL channels to ieee80211 ones and insert
   3389 	 * them in the table according to their channel number.
   3390 	 */
   3391 	for (i = 0; i < nchan; i++) {
   3392 		HAL_CHANNEL *c = &chans[i];
   3393 		ix = ath_hal_mhz2ieee(c->channel, c->channelFlags);
   3394 		if (ix > IEEE80211_CHAN_MAX) {
   3395 			if_printf(ifp, "bad hal channel %u (%u/%x) ignored\n",
   3396 				ix, c->channel, c->channelFlags);
   3397 			continue;
   3398 		}
   3399 		DPRINTF(ATH_DEBUG_ANY,
   3400 		    ("%s: HAL channel %d/%d freq %d flags %#04x idx %d\n",
   3401 		    sc->sc_dev.dv_xname, i, nchan, c->channel, c->channelFlags,
   3402 		    ix));
   3403 		/* NB: flags are known to be compatible */
   3404 		if (ic->ic_channels[ix].ic_freq == 0) {
   3405 			ic->ic_channels[ix].ic_freq = c->channel;
   3406 			ic->ic_channels[ix].ic_flags = c->channelFlags;
   3407 		} else {
   3408 			/* channels overlap; e.g. 11g and 11b */
   3409 			ic->ic_channels[ix].ic_flags |= c->channelFlags;
   3410 		}
   3411 	}
   3412 	free(chans, M_TEMP);
   3413 	return 0;
   3414 }
   3415 
   3416 static int
   3417 ath_rate_setup(struct ath_softc *sc, u_int mode)
   3418 {
   3419 	struct ath_hal *ah = sc->sc_ah;
   3420 	struct ieee80211com *ic = &sc->sc_ic;
   3421 	const HAL_RATE_TABLE *rt;
   3422 	struct ieee80211_rateset *rs;
   3423 	int i, maxrates;
   3424 
   3425 	switch (mode) {
   3426 	case IEEE80211_MODE_11A:
   3427 		sc->sc_rates[mode] = ath_hal_getratetable(ah, HAL_MODE_11A);
   3428 		break;
   3429 	case IEEE80211_MODE_11B:
   3430 		sc->sc_rates[mode] = ath_hal_getratetable(ah, HAL_MODE_11B);
   3431 		break;
   3432 	case IEEE80211_MODE_11G:
   3433 		sc->sc_rates[mode] = ath_hal_getratetable(ah, HAL_MODE_11G);
   3434 		break;
   3435 	case IEEE80211_MODE_TURBO:
   3436 		sc->sc_rates[mode] = ath_hal_getratetable(ah, HAL_MODE_TURBO);
   3437 		break;
   3438 	default:
   3439 		DPRINTF(ATH_DEBUG_ANY,
   3440 			("%s: invalid mode %u\n", __func__, mode));
   3441 		return 0;
   3442 	}
   3443 	rt = sc->sc_rates[mode];
   3444 	if (rt == NULL)
   3445 		return 0;
   3446 	if (rt->rateCount > IEEE80211_RATE_MAXSIZE) {
   3447 		DPRINTF(ATH_DEBUG_ANY,
   3448 			("%s: rate table too small (%u > %u)\n",
   3449 			__func__, rt->rateCount, IEEE80211_RATE_MAXSIZE));
   3450 		maxrates = IEEE80211_RATE_MAXSIZE;
   3451 	} else
   3452 		maxrates = rt->rateCount;
   3453 	rs = &ic->ic_sup_rates[mode];
   3454 	for (i = 0; i < maxrates; i++)
   3455 		rs->rs_rates[i] = rt->info[i].dot11Rate;
   3456 	rs->rs_nrates = maxrates;
   3457 	return 1;
   3458 }
   3459 
   3460 static void
   3461 ath_setcurmode(struct ath_softc *sc, enum ieee80211_phymode mode)
   3462 {
   3463 	const HAL_RATE_TABLE *rt;
   3464 	int i;
   3465 
   3466 	memset(sc->sc_rixmap, 0xff, sizeof(sc->sc_rixmap));
   3467 	rt = sc->sc_rates[mode];
   3468 	KASSERT(rt != NULL, ("no h/w rate set for phy mode %u", mode));
   3469 	for (i = 0; i < rt->rateCount; i++)
   3470 		sc->sc_rixmap[rt->info[i].dot11Rate & IEEE80211_RATE_VAL] = i;
   3471 	memset(sc->sc_hwmap, 0, sizeof(sc->sc_hwmap));
   3472 	for (i = 0; i < 32; i++)
   3473 		sc->sc_hwmap[i] = rt->info[rt->rateCodeToIndex[i]].dot11Rate;
   3474 	sc->sc_currates = rt;
   3475 	sc->sc_curmode = mode;
   3476 }
   3477 
   3478 /*
   3479  * Reset the rate control state for each 802.11 state transition.
   3480  */
   3481 static void
   3482 ath_rate_ctl_reset(struct ath_softc *sc, enum ieee80211_state state)
   3483 {
   3484 	struct ieee80211com *ic = &sc->sc_ic;
   3485 	struct ieee80211_node *ni;
   3486 	struct ath_node *an;
   3487 
   3488 	if (ic->ic_opmode != IEEE80211_M_STA) {
   3489 		/*
   3490 		 * When operating as a station the node table holds
   3491 		 * the AP's that were discovered during scanning.
   3492 		 * For any other operating mode we want to reset the
   3493 		 * tx rate state of each node.
   3494 		 */
   3495 		TAILQ_FOREACH(ni, &ic->ic_node, ni_list) {
   3496 			ni->ni_txrate = 0;		/* use lowest rate */
   3497 			an = (struct ath_node *) ni;
   3498 			an->an_tx_ok = an->an_tx_err = an->an_tx_retr =
   3499 			    an->an_tx_upper = 0;
   3500 		}
   3501 	}
   3502 	/*
   3503 	 * Reset local xmit state; this is really only meaningful
   3504 	 * when operating in station or adhoc mode.
   3505 	 */
   3506 	ni = ic->ic_bss;
   3507 	an = (struct ath_node *) ni;
   3508 	an->an_tx_ok = an->an_tx_err = an->an_tx_retr = an->an_tx_upper = 0;
   3509 	if (state == IEEE80211_S_RUN) {
   3510 		/* start with highest negotiated rate */
   3511 		KASSERT(ni->ni_rates.rs_nrates > 0,
   3512 			("transition to RUN state w/ no rates!"));
   3513 		ni->ni_txrate = ni->ni_rates.rs_nrates - 1;
   3514 	} else {
   3515 		/* use lowest rate */
   3516 		ni->ni_txrate = 0;
   3517 	}
   3518 }
   3519 
   3520 /*
   3521  * Examine and potentially adjust the transmit rate.
   3522  */
   3523 static void
   3524 ath_rate_ctl(void *arg, struct ieee80211_node *ni)
   3525 {
   3526 	struct ath_softc *sc = arg;
   3527 	struct ath_node *an = (struct ath_node *) ni;
   3528 	struct ieee80211_rateset *rs = &ni->ni_rates;
   3529 	int mod = 0, orate, enough;
   3530 
   3531 	/*
   3532 	 * Rate control
   3533 	 * XXX: very primitive version.
   3534 	 */
   3535 	sc->sc_stats.ast_rate_calls++;
   3536 
   3537 	enough = (an->an_tx_ok + an->an_tx_err >= 10);
   3538 
   3539 	/* no packet reached -> down */
   3540 	if (an->an_tx_err > 0 && an->an_tx_ok == 0)
   3541 		mod = -1;
   3542 
   3543 	/* all packets needs retry in average -> down */
   3544 	if (enough && an->an_tx_ok < an->an_tx_retr)
   3545 		mod = -1;
   3546 
   3547 	/* no error and less than 10% of packets needs retry -> up */
   3548 	if (enough && an->an_tx_err == 0 && an->an_tx_ok > an->an_tx_retr * 10)
   3549 		mod = 1;
   3550 
   3551 	orate = ni->ni_txrate;
   3552 	switch (mod) {
   3553 	case 0:
   3554 		if (enough && an->an_tx_upper > 0)
   3555 			an->an_tx_upper--;
   3556 		break;
   3557 	case -1:
   3558 		if (ni->ni_txrate > 0) {
   3559 			ni->ni_txrate--;
   3560 			sc->sc_stats.ast_rate_drop++;
   3561 		}
   3562 		an->an_tx_upper = 0;
   3563 		break;
   3564 	case 1:
   3565 		if (++an->an_tx_upper < 2)
   3566 			break;
   3567 		an->an_tx_upper = 0;
   3568 		if (ni->ni_txrate + 1 < rs->rs_nrates) {
   3569 			ni->ni_txrate++;
   3570 			sc->sc_stats.ast_rate_raise++;
   3571 		}
   3572 		break;
   3573 	}
   3574 
   3575 	if (ni->ni_txrate != orate) {
   3576 		DPRINTF(ATH_DEBUG_RATE,
   3577 		    ("%s: %dM -> %dM (%d ok, %d err, %d retr)\n",
   3578 		    __func__,
   3579 		    (rs->rs_rates[orate] & IEEE80211_RATE_VAL) / 2,
   3580 		    (rs->rs_rates[ni->ni_txrate] & IEEE80211_RATE_VAL) / 2,
   3581 		    an->an_tx_ok, an->an_tx_err, an->an_tx_retr));
   3582 	}
   3583 	if (ni->ni_txrate != orate || enough)
   3584 		an->an_tx_ok = an->an_tx_err = an->an_tx_retr = 0;
   3585 }
   3586 
   3587 #ifdef AR_DEBUG
   3588 #ifdef __FreeBSD__
   3589 static int
   3590 sysctl_hw_ath_dump(SYSCTL_HANDLER_ARGS)
   3591 {
   3592 	char dmode[64];
   3593 	int error;
   3594 
   3595 	strncpy(dmode, "", sizeof(dmode) - 1);
   3596 	dmode[sizeof(dmode) - 1] = '\0';
   3597 	error = sysctl_handle_string(oidp, &dmode[0], sizeof(dmode), req);
   3598 
   3599 	if (error == 0 && req->newptr != NULL) {
   3600 		struct ifnet *ifp;
   3601 		struct ath_softc *sc;
   3602 
   3603 		ifp = ifunit("ath0");		/* XXX */
   3604 		if (!ifp)
   3605 			return EINVAL;
   3606 		sc = ifp->if_softc;
   3607 		if (strcmp(dmode, "hal") == 0)
   3608 			ath_hal_dumpstate(sc->sc_ah);
   3609 		else
   3610 			return EINVAL;
   3611 	}
   3612 	return error;
   3613 }
   3614 SYSCTL_PROC(_hw_ath, OID_AUTO, dump, CTLTYPE_STRING | CTLFLAG_RW,
   3615 	0, 0, sysctl_hw_ath_dump, "A", "Dump driver state");
   3616 #endif /* __FreeBSD__ */
   3617 
   3618 #if 0 /* #ifdef __NetBSD__ */
   3619 static int
   3620 sysctl_hw_ath_dump(SYSCTL_HANDLER_ARGS)
   3621 {
   3622 	char dmode[64];
   3623 	int error;
   3624 
   3625 	strncpy(dmode, "", sizeof(dmode) - 1);
   3626 	dmode[sizeof(dmode) - 1] = '\0';
   3627 	error = sysctl_handle_string(oidp, &dmode[0], sizeof(dmode), req);
   3628 
   3629 	if (error == 0 && req->newptr != NULL) {
   3630 		struct ifnet *ifp;
   3631 		struct ath_softc *sc;
   3632 
   3633 		ifp = ifunit("ath0");		/* XXX */
   3634 		if (!ifp)
   3635 			return EINVAL;
   3636 		sc = ifp->if_softc;
   3637 		if (strcmp(dmode, "hal") == 0)
   3638 			ath_hal_dumpstate(sc->sc_ah);
   3639 		else
   3640 			return EINVAL;
   3641 	}
   3642 	return error;
   3643 }
   3644 SYSCTL_PROC(_hw_ath, OID_AUTO, dump, CTLTYPE_STRING | CTLFLAG_RW,
   3645 	0, 0, sysctl_hw_ath_dump, "A", "Dump driver state");
   3646 #endif /* __NetBSD__ */
   3647 
   3648 static void
   3649 ath_printrxbuf(struct ath_buf *bf, int done)
   3650 {
   3651 	struct ath_desc *ds;
   3652 	int i;
   3653 
   3654 	for (i = 0, ds = bf->bf_desc; i < bf->bf_nseg; i++, ds++) {
   3655 		printf("R%d (%p %p) %08x %08x %08x %08x %08x %08x %c\n",
   3656 		    i, ds, (struct ath_desc *)bf->bf_daddr + i,
   3657 		    ds->ds_link, ds->ds_data,
   3658 		    ds->ds_ctl0, ds->ds_ctl1,
   3659 		    ds->ds_hw[0], ds->ds_hw[1],
   3660 		    !done ? ' ' : (ds->ds_rxstat.rs_status == 0) ? '*' : '!');
   3661 	}
   3662 }
   3663 
   3664 static void
   3665 ath_printtxbuf(struct ath_buf *bf, int done)
   3666 {
   3667 	struct ath_desc *ds;
   3668 	int i;
   3669 
   3670 	for (i = 0, ds = bf->bf_desc; i < bf->bf_nseg; i++, ds++) {
   3671 		printf("T%d (%p %p) %08x %08x %08x %08x %08x %08x %08x %08x %c\n",
   3672 		    i, ds, (struct ath_desc *)bf->bf_daddr + i,
   3673 		    ds->ds_link, ds->ds_data,
   3674 		    ds->ds_ctl0, ds->ds_ctl1,
   3675 		    ds->ds_hw[0], ds->ds_hw[1], ds->ds_hw[2], ds->ds_hw[3],
   3676 		    !done ? ' ' : (ds->ds_txstat.ts_status == 0) ? '*' : '!');
   3677 	}
   3678 }
   3679 #endif /* AR_DEBUG */
   3680