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