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