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