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