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