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