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