Home | History | Annotate | Line # | Download | only in ic
ath.c revision 1.1.1.4
      1 /*-
      2  * Copyright (c) 2002-2005 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.88 2005/04/12 17:56:43 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 #include <contrib/dev/ath/ah_devid.h>		/* XXX for softled */
     86 
     87 /* unalligned little endian access */
     88 #define LE_READ_2(p)							\
     89 	((u_int16_t)							\
     90 	 ((((u_int8_t *)(p))[0]      ) | (((u_int8_t *)(p))[1] <<  8)))
     91 #define LE_READ_4(p)							\
     92 	((u_int32_t)							\
     93 	 ((((u_int8_t *)(p))[0]      ) | (((u_int8_t *)(p))[1] <<  8) |	\
     94 	  (((u_int8_t *)(p))[2] << 16) | (((u_int8_t *)(p))[3] << 24)))
     95 
     96 enum {
     97 	ATH_LED_TX,
     98 	ATH_LED_RX,
     99 	ATH_LED_POLL,
    100 };
    101 
    102 static void	ath_init(void *);
    103 static void	ath_stop_locked(struct ifnet *);
    104 static void	ath_stop(struct ifnet *);
    105 static void	ath_start(struct ifnet *);
    106 static int	ath_reset(struct ifnet *);
    107 static int	ath_media_change(struct ifnet *);
    108 static void	ath_watchdog(struct ifnet *);
    109 static int	ath_ioctl(struct ifnet *, u_long, caddr_t);
    110 static void	ath_fatal_proc(void *, int);
    111 static void	ath_rxorn_proc(void *, int);
    112 static void	ath_bmiss_proc(void *, int);
    113 static void	ath_initkeytable(struct ath_softc *);
    114 static int	ath_key_alloc(struct ieee80211com *,
    115 			const struct ieee80211_key *);
    116 static int	ath_key_delete(struct ieee80211com *,
    117 			const struct ieee80211_key *);
    118 static int	ath_key_set(struct ieee80211com *, const struct ieee80211_key *,
    119 			const u_int8_t mac[IEEE80211_ADDR_LEN]);
    120 static void	ath_key_update_begin(struct ieee80211com *);
    121 static void	ath_key_update_end(struct ieee80211com *);
    122 static void	ath_mode_init(struct ath_softc *);
    123 static void	ath_setslottime(struct ath_softc *);
    124 static void	ath_updateslot(struct ifnet *);
    125 static int	ath_beaconq_setup(struct ath_hal *);
    126 static int	ath_beacon_alloc(struct ath_softc *, struct ieee80211_node *);
    127 static void	ath_beacon_setup(struct ath_softc *, struct ath_buf *);
    128 static void	ath_beacon_proc(void *, int);
    129 static void	ath_bstuck_proc(void *, int);
    130 static void	ath_beacon_free(struct ath_softc *);
    131 static void	ath_beacon_config(struct ath_softc *);
    132 static void	ath_descdma_cleanup(struct ath_softc *sc,
    133 			struct ath_descdma *, ath_bufhead *);
    134 static int	ath_desc_alloc(struct ath_softc *);
    135 static void	ath_desc_free(struct ath_softc *);
    136 static struct ieee80211_node *ath_node_alloc(struct ieee80211_node_table *);
    137 static void	ath_node_free(struct ieee80211_node *);
    138 static u_int8_t	ath_node_getrssi(const struct ieee80211_node *);
    139 static int	ath_rxbuf_init(struct ath_softc *, struct ath_buf *);
    140 static void	ath_recv_mgmt(struct ieee80211com *ic, struct mbuf *m,
    141 			struct ieee80211_node *ni,
    142 			int subtype, int rssi, u_int32_t rstamp);
    143 static void	ath_setdefantenna(struct ath_softc *, u_int);
    144 static void	ath_rx_proc(void *, int);
    145 static struct ath_txq *ath_txq_setup(struct ath_softc*, int qtype, int subtype);
    146 static int	ath_tx_setup(struct ath_softc *, int, int);
    147 static int	ath_wme_update(struct ieee80211com *);
    148 static void	ath_tx_cleanupq(struct ath_softc *, struct ath_txq *);
    149 static void	ath_tx_cleanup(struct ath_softc *);
    150 static int	ath_tx_start(struct ath_softc *, struct ieee80211_node *,
    151 			     struct ath_buf *, struct mbuf *);
    152 static void	ath_tx_proc_q0(void *, int);
    153 static void	ath_tx_proc_q0123(void *, int);
    154 static void	ath_tx_proc(void *, int);
    155 static int	ath_chan_set(struct ath_softc *, struct ieee80211_channel *);
    156 static void	ath_draintxq(struct ath_softc *);
    157 static void	ath_stoprecv(struct ath_softc *);
    158 static int	ath_startrecv(struct ath_softc *);
    159 static void	ath_chan_change(struct ath_softc *, struct ieee80211_channel *);
    160 static void	ath_next_scan(void *);
    161 static void	ath_calibrate(void *);
    162 static int	ath_newstate(struct ieee80211com *, enum ieee80211_state, int);
    163 static void	ath_newassoc(struct ieee80211com *,
    164 			struct ieee80211_node *, int);
    165 static int	ath_getchannels(struct ath_softc *, u_int cc,
    166 			HAL_BOOL outdoor, HAL_BOOL xchanmode);
    167 static void	ath_led_event(struct ath_softc *, int);
    168 static void	ath_update_txpow(struct ath_softc *);
    169 
    170 static int	ath_rate_setup(struct ath_softc *, u_int mode);
    171 static void	ath_setcurmode(struct ath_softc *, enum ieee80211_phymode);
    172 
    173 static void	ath_sysctlattach(struct ath_softc *);
    174 static void	ath_bpfattach(struct ath_softc *);
    175 static void	ath_announce(struct ath_softc *);
    176 
    177 SYSCTL_DECL(_hw_ath);
    178 
    179 /* XXX validate sysctl values */
    180 static	int ath_dwelltime = 200;		/* 5 channels/second */
    181 SYSCTL_INT(_hw_ath, OID_AUTO, dwell, CTLFLAG_RW, &ath_dwelltime,
    182 	    0, "channel dwell time (ms) for AP/station scanning");
    183 static	int ath_calinterval = 30;		/* calibrate every 30 secs */
    184 SYSCTL_INT(_hw_ath, OID_AUTO, calibrate, CTLFLAG_RW, &ath_calinterval,
    185 	    0, "chip calibration interval (secs)");
    186 static	int ath_outdoor = AH_TRUE;		/* outdoor operation */
    187 SYSCTL_INT(_hw_ath, OID_AUTO, outdoor, CTLFLAG_RD, &ath_outdoor,
    188 	    0, "outdoor operation");
    189 TUNABLE_INT("hw.ath.outdoor", &ath_outdoor);
    190 static	int ath_xchanmode = AH_TRUE;		/* extended channel use */
    191 SYSCTL_INT(_hw_ath, OID_AUTO, xchanmode, CTLFLAG_RD, &ath_xchanmode,
    192 	    0, "extended channel mode");
    193 TUNABLE_INT("hw.ath.xchanmode", &ath_xchanmode);
    194 static	int ath_countrycode = CTRY_DEFAULT;	/* country code */
    195 SYSCTL_INT(_hw_ath, OID_AUTO, countrycode, CTLFLAG_RD, &ath_countrycode,
    196 	    0, "country code");
    197 TUNABLE_INT("hw.ath.countrycode", &ath_countrycode);
    198 static	int ath_regdomain = 0;			/* regulatory domain */
    199 SYSCTL_INT(_hw_ath, OID_AUTO, regdomain, CTLFLAG_RD, &ath_regdomain,
    200 	    0, "regulatory domain");
    201 
    202 #ifdef AR_DEBUG
    203 static	int ath_debug = 0;
    204 SYSCTL_INT(_hw_ath, OID_AUTO, debug, CTLFLAG_RW, &ath_debug,
    205 	    0, "control debugging printfs");
    206 TUNABLE_INT("hw.ath.debug", &ath_debug);
    207 enum {
    208 	ATH_DEBUG_XMIT		= 0x00000001,	/* basic xmit operation */
    209 	ATH_DEBUG_XMIT_DESC	= 0x00000002,	/* xmit descriptors */
    210 	ATH_DEBUG_RECV		= 0x00000004,	/* basic recv operation */
    211 	ATH_DEBUG_RECV_DESC	= 0x00000008,	/* recv descriptors */
    212 	ATH_DEBUG_RATE		= 0x00000010,	/* rate control */
    213 	ATH_DEBUG_RESET		= 0x00000020,	/* reset processing */
    214 	ATH_DEBUG_MODE		= 0x00000040,	/* mode init/setup */
    215 	ATH_DEBUG_BEACON 	= 0x00000080,	/* beacon handling */
    216 	ATH_DEBUG_WATCHDOG 	= 0x00000100,	/* watchdog timeout */
    217 	ATH_DEBUG_INTR		= 0x00001000,	/* ISR */
    218 	ATH_DEBUG_TX_PROC	= 0x00002000,	/* tx ISR proc */
    219 	ATH_DEBUG_RX_PROC	= 0x00004000,	/* rx ISR proc */
    220 	ATH_DEBUG_BEACON_PROC	= 0x00008000,	/* beacon ISR proc */
    221 	ATH_DEBUG_CALIBRATE	= 0x00010000,	/* periodic calibration */
    222 	ATH_DEBUG_KEYCACHE	= 0x00020000,	/* key cache management */
    223 	ATH_DEBUG_STATE		= 0x00040000,	/* 802.11 state transitions */
    224 	ATH_DEBUG_NODE		= 0x00080000,	/* node management */
    225 	ATH_DEBUG_LED		= 0x00100000,	/* led management */
    226 	ATH_DEBUG_FATAL		= 0x80000000,	/* fatal errors */
    227 	ATH_DEBUG_ANY		= 0xffffffff
    228 };
    229 #define	IFF_DUMPPKTS(sc, m) \
    230 	((sc->sc_debug & (m)) || \
    231 	    (sc->sc_if.if_flags & (IFF_DEBUG|IFF_LINK2)) == (IFF_DEBUG|IFF_LINK2))
    232 #define	DPRINTF(sc, m, fmt, ...) do {				\
    233 	if (sc->sc_debug & (m))					\
    234 		printf(fmt, __VA_ARGS__);			\
    235 } while (0)
    236 #define	KEYPRINTF(sc, ix, hk, mac) do {				\
    237 	if (sc->sc_debug & ATH_DEBUG_KEYCACHE)			\
    238 		ath_keyprint(__func__, ix, hk, mac);		\
    239 } while (0)
    240 static	void ath_printrxbuf(struct ath_buf *bf, int);
    241 static	void ath_printtxbuf(struct ath_buf *bf, int);
    242 #else
    243 #define	IFF_DUMPPKTS(sc, m) \
    244 	((sc->sc_if.if_flags & (IFF_DEBUG|IFF_LINK2)) == (IFF_DEBUG|IFF_LINK2))
    245 #define	DPRINTF(m, fmt, ...)
    246 #define	KEYPRINTF(sc, k, ix, mac)
    247 #endif
    248 
    249 MALLOC_DEFINE(M_ATHDEV, "athdev", "ath driver dma buffers");
    250 
    251 int
    252 ath_attach(u_int16_t devid, struct ath_softc *sc)
    253 {
    254 	struct ifnet *ifp = &sc->sc_if;
    255 	struct ieee80211com *ic = &sc->sc_ic;
    256 	struct ath_hal *ah;
    257 	HAL_STATUS status;
    258 	int error = 0, i;
    259 
    260 	DPRINTF(sc, ATH_DEBUG_ANY, "%s: devid 0x%x\n", __func__, devid);
    261 
    262 	/* set these up early for if_printf use */
    263 	if_initname(ifp, device_get_name(sc->sc_dev),
    264 		device_get_unit(sc->sc_dev));
    265 
    266 	ah = ath_hal_attach(devid, sc, sc->sc_st, sc->sc_sh, &status);
    267 	if (ah == NULL) {
    268 		if_printf(ifp, "unable to attach hardware; HAL status %u\n",
    269 			status);
    270 		error = ENXIO;
    271 		goto bad;
    272 	}
    273 	if (ah->ah_abi != HAL_ABI_VERSION) {
    274 		if_printf(ifp, "HAL ABI mismatch detected "
    275 			"(HAL:0x%x != driver:0x%x)\n",
    276 			ah->ah_abi, HAL_ABI_VERSION);
    277 		error = ENXIO;
    278 		goto bad;
    279 	}
    280 	sc->sc_ah = ah;
    281 	sc->sc_invalid = 0;	/* ready to go, enable interrupt handling */
    282 
    283 	/*
    284 	 * Check if the MAC has multi-rate retry support.
    285 	 * We do this by trying to setup a fake extended
    286 	 * descriptor.  MAC's that don't have support will
    287 	 * return false w/o doing anything.  MAC's that do
    288 	 * support it will return true w/o doing anything.
    289 	 */
    290 	sc->sc_mrretry = ath_hal_setupxtxdesc(ah, NULL, 0,0, 0,0, 0,0);
    291 
    292 	/*
    293 	 * Check if the device has hardware counters for PHY
    294 	 * errors.  If so we need to enable the MIB interrupt
    295 	 * so we can act on stat triggers.
    296 	 */
    297 	if (ath_hal_hwphycounters(ah))
    298 		sc->sc_needmib = 1;
    299 
    300 	/*
    301 	 * Get the hardware key cache size.
    302 	 */
    303 	sc->sc_keymax = ath_hal_keycachesize(ah);
    304 	if (sc->sc_keymax > sizeof(sc->sc_keymap) * NBBY) {
    305 		if_printf(ifp,
    306 			"Warning, using only %zu of %u key cache slots\n",
    307 			sizeof(sc->sc_keymap) * NBBY, sc->sc_keymax);
    308 		sc->sc_keymax = sizeof(sc->sc_keymap) * NBBY;
    309 	}
    310 	/*
    311 	 * Reset the key cache since some parts do not
    312 	 * reset the contents on initial power up.
    313 	 */
    314 	for (i = 0; i < sc->sc_keymax; i++)
    315 		ath_hal_keyreset(ah, i);
    316 	/*
    317 	 * Mark key cache slots associated with global keys
    318 	 * as in use.  If we knew TKIP was not to be used we
    319 	 * could leave the +32, +64, and +32+64 slots free.
    320 	 * XXX only for splitmic.
    321 	 */
    322 	for (i = 0; i < IEEE80211_WEP_NKID; i++) {
    323 		setbit(sc->sc_keymap, i);
    324 		setbit(sc->sc_keymap, i+32);
    325 		setbit(sc->sc_keymap, i+64);
    326 		setbit(sc->sc_keymap, i+32+64);
    327 	}
    328 
    329 	/*
    330 	 * Collect the channel list using the default country
    331 	 * code and including outdoor channels.  The 802.11 layer
    332 	 * is resposible for filtering this list based on settings
    333 	 * like the phy mode.
    334 	 */
    335 	error = ath_getchannels(sc, ath_countrycode,
    336 			ath_outdoor, ath_xchanmode);
    337 	if (error != 0)
    338 		goto bad;
    339 	/*
    340 	 * Setup dynamic sysctl's now that country code and
    341 	 * regdomain are available from the hal.
    342 	 */
    343 	ath_sysctlattach(sc);
    344 
    345 	/*
    346 	 * Setup rate tables for all potential media types.
    347 	 */
    348 	ath_rate_setup(sc, IEEE80211_MODE_11A);
    349 	ath_rate_setup(sc, IEEE80211_MODE_11B);
    350 	ath_rate_setup(sc, IEEE80211_MODE_11G);
    351 	ath_rate_setup(sc, IEEE80211_MODE_TURBO_A);
    352 	ath_rate_setup(sc, IEEE80211_MODE_TURBO_G);
    353 	/* NB: setup here so ath_rate_update is happy */
    354 	ath_setcurmode(sc, IEEE80211_MODE_11A);
    355 
    356 	/*
    357 	 * Allocate tx+rx descriptors and populate the lists.
    358 	 */
    359 	error = ath_desc_alloc(sc);
    360 	if (error != 0) {
    361 		if_printf(ifp, "failed to allocate descriptors: %d\n", error);
    362 		goto bad;
    363 	}
    364 	callout_init(&sc->sc_scan_ch, debug_mpsafenet ? CALLOUT_MPSAFE : 0);
    365 	callout_init(&sc->sc_cal_ch, CALLOUT_MPSAFE);
    366 
    367 	ATH_TXBUF_LOCK_INIT(sc);
    368 
    369 	TASK_INIT(&sc->sc_rxtask, 0, ath_rx_proc, sc);
    370 	TASK_INIT(&sc->sc_rxorntask, 0, ath_rxorn_proc, sc);
    371 	TASK_INIT(&sc->sc_fataltask, 0, ath_fatal_proc, sc);
    372 	TASK_INIT(&sc->sc_bmisstask, 0, ath_bmiss_proc, sc);
    373 	TASK_INIT(&sc->sc_bstucktask, 0, ath_bstuck_proc, sc);
    374 
    375 	/*
    376 	 * Allocate hardware transmit queues: one queue for
    377 	 * beacon frames and one data queue for each QoS
    378 	 * priority.  Note that the hal handles reseting
    379 	 * these queues at the needed time.
    380 	 *
    381 	 * XXX PS-Poll
    382 	 */
    383 	sc->sc_bhalq = ath_beaconq_setup(ah);
    384 	if (sc->sc_bhalq == (u_int) -1) {
    385 		if_printf(ifp, "unable to setup a beacon xmit queue!\n");
    386 		error = EIO;
    387 		goto bad2;
    388 	}
    389 	sc->sc_cabq = ath_txq_setup(sc, HAL_TX_QUEUE_CAB, 0);
    390 	if (sc->sc_cabq == NULL) {
    391 		if_printf(ifp, "unable to setup CAB xmit queue!\n");
    392 		error = EIO;
    393 		goto bad2;
    394 	}
    395 	/* NB: insure BK queue is the lowest priority h/w queue */
    396 	if (!ath_tx_setup(sc, WME_AC_BK, HAL_WME_AC_BK)) {
    397 		if_printf(ifp, "unable to setup xmit queue for %s traffic!\n",
    398 			ieee80211_wme_acnames[WME_AC_BK]);
    399 		error = EIO;
    400 		goto bad2;
    401 	}
    402 	if (!ath_tx_setup(sc, WME_AC_BE, HAL_WME_AC_BE) ||
    403 	    !ath_tx_setup(sc, WME_AC_VI, HAL_WME_AC_VI) ||
    404 	    !ath_tx_setup(sc, WME_AC_VO, HAL_WME_AC_VO)) {
    405 		/*
    406 		 * Not enough hardware tx queues to properly do WME;
    407 		 * just punt and assign them all to the same h/w queue.
    408 		 * We could do a better job of this if, for example,
    409 		 * we allocate queues when we switch from station to
    410 		 * AP mode.
    411 		 */
    412 		if (sc->sc_ac2q[WME_AC_VI] != NULL)
    413 			ath_tx_cleanupq(sc, sc->sc_ac2q[WME_AC_VI]);
    414 		if (sc->sc_ac2q[WME_AC_BE] != NULL)
    415 			ath_tx_cleanupq(sc, sc->sc_ac2q[WME_AC_BE]);
    416 		sc->sc_ac2q[WME_AC_BE] = sc->sc_ac2q[WME_AC_BK];
    417 		sc->sc_ac2q[WME_AC_VI] = sc->sc_ac2q[WME_AC_BK];
    418 		sc->sc_ac2q[WME_AC_VO] = sc->sc_ac2q[WME_AC_BK];
    419 	}
    420 
    421 	/*
    422 	 * Special case certain configurations.  Note the
    423 	 * CAB queue is handled by these specially so don't
    424 	 * include them when checking the txq setup mask.
    425 	 */
    426 	switch (sc->sc_txqsetup &~ (1<<sc->sc_cabq->axq_qnum)) {
    427 	case 0x01:
    428 		TASK_INIT(&sc->sc_txtask, 0, ath_tx_proc_q0, sc);
    429 		break;
    430 	case 0x0f:
    431 		TASK_INIT(&sc->sc_txtask, 0, ath_tx_proc_q0123, sc);
    432 		break;
    433 	default:
    434 		TASK_INIT(&sc->sc_txtask, 0, ath_tx_proc, sc);
    435 		break;
    436 	}
    437 
    438 	/*
    439 	 * Setup rate control.  Some rate control modules
    440 	 * call back to change the anntena state so expose
    441 	 * the necessary entry points.
    442 	 * XXX maybe belongs in struct ath_ratectrl?
    443 	 */
    444 	sc->sc_setdefantenna = ath_setdefantenna;
    445 	sc->sc_rc = ath_rate_attach(sc);
    446 	if (sc->sc_rc == NULL) {
    447 		error = EIO;
    448 		goto bad2;
    449 	}
    450 
    451 	sc->sc_blinking = 0;
    452 	sc->sc_ledstate = 1;
    453 	sc->sc_ledon = 0;			/* low true */
    454 	sc->sc_ledidle = (2700*hz)/1000;	/* 2.7sec */
    455 	callout_init(&sc->sc_ledtimer, CALLOUT_MPSAFE);
    456 	/*
    457 	 * Auto-enable soft led processing for IBM cards and for
    458 	 * 5211 minipci cards.  Users can also manually enable/disable
    459 	 * support with a sysctl.
    460 	 */
    461 	sc->sc_softled = (devid == AR5212_DEVID_IBM || devid == AR5211_DEVID);
    462 	if (sc->sc_softled) {
    463 		ath_hal_gpioCfgOutput(ah, sc->sc_ledpin);
    464 		ath_hal_gpioset(ah, sc->sc_ledpin, !sc->sc_ledon);
    465 	}
    466 
    467 	ifp->if_softc = sc;
    468 	ifp->if_flags = IFF_SIMPLEX | IFF_BROADCAST | IFF_MULTICAST;
    469 	ifp->if_start = ath_start;
    470 	ifp->if_watchdog = ath_watchdog;
    471 	ifp->if_ioctl = ath_ioctl;
    472 	ifp->if_init = ath_init;
    473 	IFQ_SET_MAXLEN(&ifp->if_snd, IFQ_MAXLEN);
    474 	ifp->if_snd.ifq_drv_maxlen = IFQ_MAXLEN;
    475 	IFQ_SET_READY(&ifp->if_snd);
    476 
    477 	ic->ic_ifp = ifp;
    478 	ic->ic_reset = ath_reset;
    479 	ic->ic_newassoc = ath_newassoc;
    480 	ic->ic_updateslot = ath_updateslot;
    481 	ic->ic_wme.wme_update = ath_wme_update;
    482 	/* XXX not right but it's not used anywhere important */
    483 	ic->ic_phytype = IEEE80211_T_OFDM;
    484 	ic->ic_opmode = IEEE80211_M_STA;
    485 	ic->ic_caps =
    486 		  IEEE80211_C_IBSS		/* ibss, nee adhoc, mode */
    487 		| IEEE80211_C_HOSTAP		/* hostap mode */
    488 		| IEEE80211_C_MONITOR		/* monitor mode */
    489 		| IEEE80211_C_SHPREAMBLE	/* short preamble supported */
    490 		| IEEE80211_C_SHSLOT		/* short slot time supported */
    491 		| IEEE80211_C_WPA		/* capable of WPA1+WPA2 */
    492 		;
    493 	/*
    494 	 * Query the hal to figure out h/w crypto support.
    495 	 */
    496 	if (ath_hal_ciphersupported(ah, HAL_CIPHER_WEP))
    497 		ic->ic_caps |= IEEE80211_C_WEP;
    498 	if (ath_hal_ciphersupported(ah, HAL_CIPHER_AES_OCB))
    499 		ic->ic_caps |= IEEE80211_C_AES;
    500 	if (ath_hal_ciphersupported(ah, HAL_CIPHER_AES_CCM))
    501 		ic->ic_caps |= IEEE80211_C_AES_CCM;
    502 	if (ath_hal_ciphersupported(ah, HAL_CIPHER_CKIP))
    503 		ic->ic_caps |= IEEE80211_C_CKIP;
    504 	if (ath_hal_ciphersupported(ah, HAL_CIPHER_TKIP)) {
    505 		ic->ic_caps |= IEEE80211_C_TKIP;
    506 		/*
    507 		 * Check if h/w does the MIC and/or whether the
    508 		 * separate key cache entries are required to
    509 		 * handle both tx+rx MIC keys.
    510 		 */
    511 		if (ath_hal_ciphersupported(ah, HAL_CIPHER_MIC))
    512 			ic->ic_caps |= IEEE80211_C_TKIPMIC;
    513 		if (ath_hal_tkipsplit(ah))
    514 			sc->sc_splitmic = 1;
    515 	}
    516 	/*
    517 	 * TPC support can be done either with a global cap or
    518 	 * per-packet support.  The latter is not available on
    519 	 * all parts.  We're a bit pedantic here as all parts
    520 	 * support a global cap.
    521 	 */
    522 	sc->sc_hastpc = ath_hal_hastpc(ah);
    523 	if (sc->sc_hastpc || ath_hal_hastxpowlimit(ah))
    524 		ic->ic_caps |= IEEE80211_C_TXPMGT;
    525 
    526 	/*
    527 	 * Mark WME capability only if we have sufficient
    528 	 * hardware queues to do proper priority scheduling.
    529 	 */
    530 	if (sc->sc_ac2q[WME_AC_BE] != sc->sc_ac2q[WME_AC_BK])
    531 		ic->ic_caps |= IEEE80211_C_WME;
    532 	/*
    533 	 * Check for frame bursting capability.
    534 	 */
    535 	if (ath_hal_hasbursting(ah))
    536 		ic->ic_caps |= IEEE80211_C_BURST;
    537 
    538 	/*
    539 	 * Indicate we need the 802.11 header padded to a
    540 	 * 32-bit boundary for 4-address and QoS frames.
    541 	 */
    542 	ic->ic_flags |= IEEE80211_F_DATAPAD;
    543 
    544 	/*
    545 	 * Query the hal about antenna support.
    546 	 */
    547 	if (ath_hal_hasdiversity(ah)) {
    548 		sc->sc_hasdiversity = 1;
    549 		sc->sc_diversity = ath_hal_getdiversity(ah);
    550 	}
    551 	sc->sc_defant = ath_hal_getdefantenna(ah);
    552 
    553 	/*
    554 	 * Not all chips have the VEOL support we want to
    555 	 * use with IBSS beacons; check here for it.
    556 	 */
    557 	sc->sc_hasveol = ath_hal_hasveol(ah);
    558 
    559 	/* get mac address from hardware */
    560 	ath_hal_getmac(ah, ic->ic_myaddr);
    561 
    562 	/* call MI attach routine. */
    563 	ieee80211_ifattach(ic);
    564 	/* override default methods */
    565 	ic->ic_node_alloc = ath_node_alloc;
    566 	sc->sc_node_free = ic->ic_node_free;
    567 	ic->ic_node_free = ath_node_free;
    568 	ic->ic_node_getrssi = ath_node_getrssi;
    569 	sc->sc_recv_mgmt = ic->ic_recv_mgmt;
    570 	ic->ic_recv_mgmt = ath_recv_mgmt;
    571 	sc->sc_newstate = ic->ic_newstate;
    572 	ic->ic_newstate = ath_newstate;
    573 	ic->ic_crypto.cs_key_alloc = ath_key_alloc;
    574 	ic->ic_crypto.cs_key_delete = ath_key_delete;
    575 	ic->ic_crypto.cs_key_set = ath_key_set;
    576 	ic->ic_crypto.cs_key_update_begin = ath_key_update_begin;
    577 	ic->ic_crypto.cs_key_update_end = ath_key_update_end;
    578 	/* complete initialization */
    579 	ieee80211_media_init(ic, ath_media_change, ieee80211_media_status);
    580 
    581 	ath_bpfattach(sc);
    582 
    583 	if (bootverbose)
    584 		ieee80211_announce(ic);
    585 	ath_announce(sc);
    586 	return 0;
    587 bad2:
    588 	ath_tx_cleanup(sc);
    589 	ath_desc_free(sc);
    590 bad:
    591 	if (ah)
    592 		ath_hal_detach(ah);
    593 	sc->sc_invalid = 1;
    594 	return error;
    595 }
    596 
    597 int
    598 ath_detach(struct ath_softc *sc)
    599 {
    600 	struct ifnet *ifp = &sc->sc_if;
    601 
    602 	DPRINTF(sc, ATH_DEBUG_ANY, "%s: if_flags %x\n",
    603 		__func__, ifp->if_flags);
    604 
    605 	ath_stop(ifp);
    606 	bpfdetach(ifp);
    607 	/*
    608 	 * NB: the order of these is important:
    609 	 * o call the 802.11 layer before detaching the hal to
    610 	 *   insure callbacks into the driver to delete global
    611 	 *   key cache entries can be handled
    612 	 * o reclaim the tx queue data structures after calling
    613 	 *   the 802.11 layer as we'll get called back to reclaim
    614 	 *   node state and potentially want to use them
    615 	 * o to cleanup the tx queues the hal is called, so detach
    616 	 *   it last
    617 	 * Other than that, it's straightforward...
    618 	 */
    619 	ieee80211_ifdetach(&sc->sc_ic);
    620 	ath_rate_detach(sc->sc_rc);
    621 	ath_desc_free(sc);
    622 	ath_tx_cleanup(sc);
    623 	ath_hal_detach(sc->sc_ah);
    624 
    625 	return 0;
    626 }
    627 
    628 void
    629 ath_suspend(struct ath_softc *sc)
    630 {
    631 	struct ifnet *ifp = &sc->sc_if;
    632 
    633 	DPRINTF(sc, ATH_DEBUG_ANY, "%s: if_flags %x\n",
    634 		__func__, ifp->if_flags);
    635 
    636 	ath_stop(ifp);
    637 }
    638 
    639 void
    640 ath_resume(struct ath_softc *sc)
    641 {
    642 	struct ifnet *ifp = &sc->sc_if;
    643 
    644 	DPRINTF(sc, ATH_DEBUG_ANY, "%s: if_flags %x\n",
    645 		__func__, ifp->if_flags);
    646 
    647 	if (ifp->if_flags & IFF_UP) {
    648 		ath_init(ifp);
    649 		if (ifp->if_flags & IFF_RUNNING)
    650 			ath_start(ifp);
    651 	}
    652 }
    653 
    654 void
    655 ath_shutdown(struct ath_softc *sc)
    656 {
    657 	struct ifnet *ifp = &sc->sc_if;
    658 
    659 	DPRINTF(sc, ATH_DEBUG_ANY, "%s: if_flags %x\n",
    660 		__func__, ifp->if_flags);
    661 
    662 	ath_stop(ifp);
    663 }
    664 
    665 /*
    666  * Interrupt handler.  Most of the actual processing is deferred.
    667  */
    668 void
    669 ath_intr(void *arg)
    670 {
    671 	struct ath_softc *sc = arg;
    672 	struct ifnet *ifp = &sc->sc_if;
    673 	struct ath_hal *ah = sc->sc_ah;
    674 	HAL_INT status;
    675 
    676 	if (sc->sc_invalid) {
    677 		/*
    678 		 * The hardware is not ready/present, don't touch anything.
    679 		 * Note this can happen early on if the IRQ is shared.
    680 		 */
    681 		DPRINTF(sc, ATH_DEBUG_ANY, "%s: invalid; ignored\n", __func__);
    682 		return;
    683 	}
    684 	if (!ath_hal_intrpend(ah))		/* shared irq, not for us */
    685 		return;
    686 	if ((ifp->if_flags & (IFF_RUNNING|IFF_UP)) != (IFF_RUNNING|IFF_UP)) {
    687 		DPRINTF(sc, ATH_DEBUG_ANY, "%s: if_flags 0x%x\n",
    688 			__func__, ifp->if_flags);
    689 		ath_hal_getisr(ah, &status);	/* clear ISR */
    690 		ath_hal_intrset(ah, 0);		/* disable further intr's */
    691 		return;
    692 	}
    693 	/*
    694 	 * Figure out the reason(s) for the interrupt.  Note
    695 	 * that the hal returns a pseudo-ISR that may include
    696 	 * bits we haven't explicitly enabled so we mask the
    697 	 * value to insure we only process bits we requested.
    698 	 */
    699 	ath_hal_getisr(ah, &status);		/* NB: clears ISR too */
    700 	DPRINTF(sc, ATH_DEBUG_INTR, "%s: status 0x%x\n", __func__, status);
    701 	status &= sc->sc_imask;			/* discard unasked for bits */
    702 	if (status & HAL_INT_FATAL) {
    703 		/*
    704 		 * Fatal errors are unrecoverable.  Typically
    705 		 * these are caused by DMA errors.  Unfortunately
    706 		 * the exact reason is not (presently) returned
    707 		 * by the hal.
    708 		 */
    709 		sc->sc_stats.ast_hardware++;
    710 		ath_hal_intrset(ah, 0);		/* disable intr's until reset */
    711 		taskqueue_enqueue(taskqueue_swi, &sc->sc_fataltask);
    712 	} else if (status & HAL_INT_RXORN) {
    713 		sc->sc_stats.ast_rxorn++;
    714 		ath_hal_intrset(ah, 0);		/* disable intr's until reset */
    715 		taskqueue_enqueue(taskqueue_swi, &sc->sc_rxorntask);
    716 	} else {
    717 		if (status & HAL_INT_SWBA) {
    718 			/*
    719 			 * Software beacon alert--time to send a beacon.
    720 			 * Handle beacon transmission directly; deferring
    721 			 * this is too slow to meet timing constraints
    722 			 * under load.
    723 			 */
    724 			ath_beacon_proc(sc, 0);
    725 		}
    726 		if (status & HAL_INT_RXEOL) {
    727 			/*
    728 			 * NB: the hardware should re-read the link when
    729 			 *     RXE bit is written, but it doesn't work at
    730 			 *     least on older hardware revs.
    731 			 */
    732 			sc->sc_stats.ast_rxeol++;
    733 			sc->sc_rxlink = NULL;
    734 		}
    735 		if (status & HAL_INT_TXURN) {
    736 			sc->sc_stats.ast_txurn++;
    737 			/* bump tx trigger level */
    738 			ath_hal_updatetxtriglevel(ah, AH_TRUE);
    739 		}
    740 		if (status & HAL_INT_RX)
    741 			taskqueue_enqueue(taskqueue_swi, &sc->sc_rxtask);
    742 		if (status & HAL_INT_TX)
    743 			taskqueue_enqueue(taskqueue_swi, &sc->sc_txtask);
    744 		if (status & HAL_INT_BMISS) {
    745 			sc->sc_stats.ast_bmiss++;
    746 			taskqueue_enqueue(taskqueue_swi, &sc->sc_bmisstask);
    747 		}
    748 		if (status & HAL_INT_MIB) {
    749 			sc->sc_stats.ast_mib++;
    750 			/*
    751 			 * Disable interrupts until we service the MIB
    752 			 * interrupt; otherwise it will continue to fire.
    753 			 */
    754 			ath_hal_intrset(ah, 0);
    755 			/*
    756 			 * Let the hal handle the event.  We assume it will
    757 			 * clear whatever condition caused the interrupt.
    758 			 */
    759 			ath_hal_mibevent(ah,
    760 				&ATH_NODE(sc->sc_ic.ic_bss)->an_halstats);
    761 			ath_hal_intrset(ah, sc->sc_imask);
    762 		}
    763 	}
    764 }
    765 
    766 static void
    767 ath_fatal_proc(void *arg, int pending)
    768 {
    769 	struct ath_softc *sc = arg;
    770 	struct ifnet *ifp = &sc->sc_if;
    771 
    772 	if_printf(ifp, "hardware error; resetting\n");
    773 	ath_reset(ifp);
    774 }
    775 
    776 static void
    777 ath_rxorn_proc(void *arg, int pending)
    778 {
    779 	struct ath_softc *sc = arg;
    780 	struct ifnet *ifp = &sc->sc_if;
    781 
    782 	if_printf(ifp, "rx FIFO overrun; resetting\n");
    783 	ath_reset(ifp);
    784 }
    785 
    786 static void
    787 ath_bmiss_proc(void *arg, int pending)
    788 {
    789 	struct ath_softc *sc = arg;
    790 	struct ieee80211com *ic = &sc->sc_ic;
    791 
    792 	DPRINTF(sc, ATH_DEBUG_ANY, "%s: pending %u\n", __func__, pending);
    793 	KASSERT(ic->ic_opmode == IEEE80211_M_STA,
    794 		("unexpect operating mode %u", ic->ic_opmode));
    795 	if (ic->ic_state == IEEE80211_S_RUN) {
    796 		/*
    797 		 * Rather than go directly to scan state, try to
    798 		 * reassociate first.  If that fails then the state
    799 		 * machine will drop us into scanning after timing
    800 		 * out waiting for a probe response.
    801 		 */
    802 		NET_LOCK_GIANT();
    803 		ieee80211_new_state(ic, IEEE80211_S_ASSOC, -1);
    804 		NET_UNLOCK_GIANT();
    805 	}
    806 }
    807 
    808 static u_int
    809 ath_chan2flags(struct ieee80211com *ic, struct ieee80211_channel *chan)
    810 {
    811 #define	N(a)	(sizeof(a) / sizeof(a[0]))
    812 	static const u_int modeflags[] = {
    813 		0,			/* IEEE80211_MODE_AUTO */
    814 		CHANNEL_A,		/* IEEE80211_MODE_11A */
    815 		CHANNEL_B,		/* IEEE80211_MODE_11B */
    816 		CHANNEL_PUREG,		/* IEEE80211_MODE_11G */
    817 		0,			/* IEEE80211_MODE_FH */
    818 		CHANNEL_T,		/* IEEE80211_MODE_TURBO_A */
    819 		CHANNEL_108G		/* IEEE80211_MODE_TURBO_G */
    820 	};
    821 	enum ieee80211_phymode mode = ieee80211_chan2mode(ic, chan);
    822 
    823 	KASSERT(mode < N(modeflags), ("unexpected phy mode %u", mode));
    824 	KASSERT(modeflags[mode] != 0, ("mode %u undefined", mode));
    825 	return modeflags[mode];
    826 #undef N
    827 }
    828 
    829 static void
    830 ath_init(void *arg)
    831 {
    832 	struct ath_softc *sc = (struct ath_softc *) arg;
    833 	struct ieee80211com *ic = &sc->sc_ic;
    834 	struct ifnet *ifp = &sc->sc_if;
    835 	struct ieee80211_node *ni;
    836 	struct ath_hal *ah = sc->sc_ah;
    837 	HAL_STATUS status;
    838 
    839 	DPRINTF(sc, ATH_DEBUG_ANY, "%s: if_flags 0x%x\n",
    840 		__func__, ifp->if_flags);
    841 
    842 	ATH_LOCK(sc);
    843 	/*
    844 	 * Stop anything previously setup.  This is safe
    845 	 * whether this is the first time through or not.
    846 	 */
    847 	ath_stop_locked(ifp);
    848 
    849 	/*
    850 	 * The basic interface to setting the hardware in a good
    851 	 * state is ``reset''.  On return the hardware is known to
    852 	 * be powered up and with interrupts disabled.  This must
    853 	 * be followed by initialization of the appropriate bits
    854 	 * and then setup of the interrupt mask.
    855 	 */
    856 	sc->sc_curchan.channel = ic->ic_ibss_chan->ic_freq;
    857 	sc->sc_curchan.channelFlags = ath_chan2flags(ic, ic->ic_ibss_chan);
    858 	if (!ath_hal_reset(ah, ic->ic_opmode, &sc->sc_curchan, AH_FALSE, &status)) {
    859 		if_printf(ifp, "unable to reset hardware; hal status %u\n",
    860 			status);
    861 		goto done;
    862 	}
    863 
    864 	/*
    865 	 * This is needed only to setup initial state
    866 	 * but it's best done after a reset.
    867 	 */
    868 	ath_update_txpow(sc);
    869 
    870 	/*
    871 	 * Setup the hardware after reset: the key cache
    872 	 * is filled as needed and the receive engine is
    873 	 * set going.  Frame transmit is handled entirely
    874 	 * in the frame output path; there's nothing to do
    875 	 * here except setup the interrupt mask.
    876 	 */
    877 	ath_initkeytable(sc);		/* XXX still needed? */
    878 	if (ath_startrecv(sc) != 0) {
    879 		if_printf(ifp, "unable to start recv logic\n");
    880 		goto done;
    881 	}
    882 
    883 	/*
    884 	 * Enable interrupts.
    885 	 */
    886 	sc->sc_imask = HAL_INT_RX | HAL_INT_TX
    887 		  | HAL_INT_RXEOL | HAL_INT_RXORN
    888 		  | HAL_INT_FATAL | HAL_INT_GLOBAL;
    889 	/*
    890 	 * Enable MIB interrupts when there are hardware phy counters.
    891 	 * Note we only do this (at the moment) for station mode.
    892 	 */
    893 	if (sc->sc_needmib && ic->ic_opmode == IEEE80211_M_STA)
    894 		sc->sc_imask |= HAL_INT_MIB;
    895 	ath_hal_intrset(ah, sc->sc_imask);
    896 
    897 	ifp->if_flags |= IFF_RUNNING;
    898 	ic->ic_state = IEEE80211_S_INIT;
    899 
    900 	/*
    901 	 * The hardware should be ready to go now so it's safe
    902 	 * to kick the 802.11 state machine as it's likely to
    903 	 * immediately call back to us to send mgmt frames.
    904 	 */
    905 	ni = ic->ic_bss;
    906 	ni->ni_chan = ic->ic_ibss_chan;
    907 	ath_chan_change(sc, ni->ni_chan);
    908 	if (ic->ic_opmode != IEEE80211_M_MONITOR) {
    909 		if (ic->ic_roaming != IEEE80211_ROAMING_MANUAL)
    910 			ieee80211_new_state(ic, IEEE80211_S_SCAN, -1);
    911 	} else
    912 		ieee80211_new_state(ic, IEEE80211_S_RUN, -1);
    913 done:
    914 	ATH_UNLOCK(sc);
    915 }
    916 
    917 static void
    918 ath_stop_locked(struct ifnet *ifp)
    919 {
    920 	struct ath_softc *sc = ifp->if_softc;
    921 	struct ieee80211com *ic = &sc->sc_ic;
    922 	struct ath_hal *ah = sc->sc_ah;
    923 
    924 	DPRINTF(sc, ATH_DEBUG_ANY, "%s: invalid %u if_flags 0x%x\n",
    925 		__func__, sc->sc_invalid, ifp->if_flags);
    926 
    927 	ATH_LOCK_ASSERT(sc);
    928 	if (ifp->if_flags & IFF_RUNNING) {
    929 		/*
    930 		 * Shutdown the hardware and driver:
    931 		 *    reset 802.11 state machine
    932 		 *    turn off timers
    933 		 *    disable interrupts
    934 		 *    turn off the radio
    935 		 *    clear transmit machinery
    936 		 *    clear receive machinery
    937 		 *    drain and release tx queues
    938 		 *    reclaim beacon resources
    939 		 *    power down hardware
    940 		 *
    941 		 * Note that some of this work is not possible if the
    942 		 * hardware is gone (invalid).
    943 		 */
    944 		ieee80211_new_state(ic, IEEE80211_S_INIT, -1);
    945 		ifp->if_flags &= ~IFF_RUNNING;
    946 		ifp->if_timer = 0;
    947 		if (!sc->sc_invalid) {
    948 			if (sc->sc_softled) {
    949 				callout_stop(&sc->sc_ledtimer);
    950 				ath_hal_gpioset(ah, sc->sc_ledpin,
    951 					!sc->sc_ledon);
    952 				sc->sc_blinking = 0;
    953 			}
    954 			ath_hal_intrset(ah, 0);
    955 		}
    956 		ath_draintxq(sc);
    957 		if (!sc->sc_invalid) {
    958 			ath_stoprecv(sc);
    959 			ath_hal_phydisable(ah);
    960 		} else
    961 			sc->sc_rxlink = NULL;
    962 		IFQ_DRV_PURGE(&ifp->if_snd);
    963 		ath_beacon_free(sc);
    964 	}
    965 }
    966 
    967 static void
    968 ath_stop(struct ifnet *ifp)
    969 {
    970 	struct ath_softc *sc = ifp->if_softc;
    971 
    972 	ATH_LOCK(sc);
    973 	ath_stop_locked(ifp);
    974 	if (!sc->sc_invalid) {
    975 		/*
    976 		 * Set the chip in full sleep mode.  Note that we are
    977 		 * careful to do this only when bringing the interface
    978 		 * completely to a stop.  When the chip is in this state
    979 		 * it must be carefully woken up or references to
    980 		 * registers in the PCI clock domain may freeze the bus
    981 		 * (and system).  This varies by chip and is mostly an
    982 		 * issue with newer parts that go to sleep more quickly.
    983 		 */
    984 		ath_hal_setpower(sc->sc_ah, HAL_PM_FULL_SLEEP, 0);
    985 	}
    986 	ATH_UNLOCK(sc);
    987 }
    988 
    989 /*
    990  * Reset the hardware w/o losing operational state.  This is
    991  * basically a more efficient way of doing ath_stop, ath_init,
    992  * followed by state transitions to the current 802.11
    993  * operational state.  Used to recover from various errors and
    994  * to reset or reload hardware state.
    995  */
    996 static int
    997 ath_reset(struct ifnet *ifp)
    998 {
    999 	struct ath_softc *sc = ifp->if_softc;
   1000 	struct ieee80211com *ic = &sc->sc_ic;
   1001 	struct ath_hal *ah = sc->sc_ah;
   1002 	struct ieee80211_channel *c;
   1003 	HAL_STATUS status;
   1004 
   1005 	/*
   1006 	 * Convert to a HAL channel description with the flags
   1007 	 * constrained to reflect the current operating mode.
   1008 	 */
   1009 	c = ic->ic_ibss_chan;
   1010 	sc->sc_curchan.channel = c->ic_freq;
   1011 	sc->sc_curchan.channelFlags = ath_chan2flags(ic, c);
   1012 
   1013 	ath_hal_intrset(ah, 0);		/* disable interrupts */
   1014 	ath_draintxq(sc);		/* stop xmit side */
   1015 	ath_stoprecv(sc);		/* stop recv side */
   1016 	/* NB: indicate channel change so we do a full reset */
   1017 	if (!ath_hal_reset(ah, ic->ic_opmode, &sc->sc_curchan, AH_TRUE, &status))
   1018 		if_printf(ifp, "%s: unable to reset hardware; hal status %u\n",
   1019 			__func__, status);
   1020 	ath_update_txpow(sc);		/* update tx power state */
   1021 	if (ath_startrecv(sc) != 0)	/* restart recv */
   1022 		if_printf(ifp, "%s: unable to start recv logic\n", __func__);
   1023 	/*
   1024 	 * We may be doing a reset in response to an ioctl
   1025 	 * that changes the channel so update any state that
   1026 	 * might change as a result.
   1027 	 */
   1028 	ath_chan_change(sc, c);
   1029 	if (ic->ic_state == IEEE80211_S_RUN)
   1030 		ath_beacon_config(sc);	/* restart beacons */
   1031 	ath_hal_intrset(ah, sc->sc_imask);
   1032 
   1033 	ath_start(ifp);			/* restart xmit */
   1034 	return 0;
   1035 }
   1036 
   1037 static void
   1038 ath_start(struct ifnet *ifp)
   1039 {
   1040 	struct ath_softc *sc = ifp->if_softc;
   1041 	struct ath_hal *ah = sc->sc_ah;
   1042 	struct ieee80211com *ic = &sc->sc_ic;
   1043 	struct ieee80211_node *ni;
   1044 	struct ath_buf *bf;
   1045 	struct mbuf *m;
   1046 	struct ieee80211_frame *wh;
   1047 	struct ether_header *eh;
   1048 
   1049 	if ((ifp->if_flags & IFF_RUNNING) == 0 || sc->sc_invalid)
   1050 		return;
   1051 	for (;;) {
   1052 		/*
   1053 		 * Grab a TX buffer and associated resources.
   1054 		 */
   1055 		ATH_TXBUF_LOCK(sc);
   1056 		bf = STAILQ_FIRST(&sc->sc_txbuf);
   1057 		if (bf != NULL)
   1058 			STAILQ_REMOVE_HEAD(&sc->sc_txbuf, bf_list);
   1059 		ATH_TXBUF_UNLOCK(sc);
   1060 		if (bf == NULL) {
   1061 			DPRINTF(sc, ATH_DEBUG_ANY, "%s: out of xmit buffers\n",
   1062 				__func__);
   1063 			sc->sc_stats.ast_tx_qstop++;
   1064 			ifp->if_flags |= IFF_OACTIVE;
   1065 			break;
   1066 		}
   1067 		/*
   1068 		 * Poll the management queue for frames; they
   1069 		 * have priority over normal data frames.
   1070 		 */
   1071 		IF_DEQUEUE(&ic->ic_mgtq, m);
   1072 		if (m == NULL) {
   1073 			/*
   1074 			 * No data frames go out unless we're associated.
   1075 			 */
   1076 			if (ic->ic_state != IEEE80211_S_RUN) {
   1077 				DPRINTF(sc, ATH_DEBUG_ANY,
   1078 					"%s: ignore data packet, state %u\n",
   1079 					__func__, ic->ic_state);
   1080 				sc->sc_stats.ast_tx_discard++;
   1081 				ATH_TXBUF_LOCK(sc);
   1082 				STAILQ_INSERT_TAIL(&sc->sc_txbuf, bf, bf_list);
   1083 				ATH_TXBUF_UNLOCK(sc);
   1084 				break;
   1085 			}
   1086 			IFQ_DRV_DEQUEUE(&ifp->if_snd, m);	/* XXX: LOCK */
   1087 			if (m == NULL) {
   1088 				ATH_TXBUF_LOCK(sc);
   1089 				STAILQ_INSERT_TAIL(&sc->sc_txbuf, bf, bf_list);
   1090 				ATH_TXBUF_UNLOCK(sc);
   1091 				break;
   1092 			}
   1093 			/*
   1094 			 * Find the node for the destination so we can do
   1095 			 * things like power save and fast frames aggregation.
   1096 			 */
   1097 			if (m->m_len < sizeof(struct ether_header) &&
   1098 			   (m = m_pullup(m, sizeof(struct ether_header))) == NULL) {
   1099 				ic->ic_stats.is_tx_nobuf++;	/* XXX */
   1100 				ni = NULL;
   1101 				goto bad;
   1102 			}
   1103 			eh = mtod(m, struct ether_header *);
   1104 			ni = ieee80211_find_txnode(ic, eh->ether_dhost);
   1105 			if (ni == NULL) {
   1106 				/* NB: ieee80211_find_txnode does stat+msg */
   1107 				m_freem(m);
   1108 				goto bad;
   1109 			}
   1110 			if ((ni->ni_flags & IEEE80211_NODE_PWR_MGT) &&
   1111 			    (m->m_flags & M_PWR_SAV) == 0) {
   1112 				/*
   1113 				 * Station in power save mode; pass the frame
   1114 				 * to the 802.11 layer and continue.  We'll get
   1115 				 * the frame back when the time is right.
   1116 				 */
   1117 				ieee80211_pwrsave(ic, ni, m);
   1118 				goto reclaim;
   1119 			}
   1120 			/* calculate priority so we can find the tx queue */
   1121 			if (ieee80211_classify(ic, m, ni)) {
   1122 				DPRINTF(sc, ATH_DEBUG_XMIT,
   1123 					"%s: discard, classification failure\n",
   1124 					__func__);
   1125 				m_freem(m);
   1126 				goto bad;
   1127 			}
   1128 			ifp->if_opackets++;
   1129 			BPF_MTAP(ifp, m);
   1130 			/*
   1131 			 * Encapsulate the packet in prep for transmission.
   1132 			 */
   1133 			m = ieee80211_encap(ic, m, ni);
   1134 			if (m == NULL) {
   1135 				DPRINTF(sc, ATH_DEBUG_ANY,
   1136 					"%s: encapsulation failure\n",
   1137 					__func__);
   1138 				sc->sc_stats.ast_tx_encap++;
   1139 				goto bad;
   1140 			}
   1141 		} else {
   1142 			/*
   1143 			 * Hack!  The referenced node pointer is in the
   1144 			 * rcvif field of the packet header.  This is
   1145 			 * placed there by ieee80211_mgmt_output because
   1146 			 * we need to hold the reference with the frame
   1147 			 * and there's no other way (other than packet
   1148 			 * tags which we consider too expensive to use)
   1149 			 * to pass it along.
   1150 			 */
   1151 			ni = (struct ieee80211_node *) m->m_pkthdr.rcvif;
   1152 			m->m_pkthdr.rcvif = NULL;
   1153 
   1154 			wh = mtod(m, struct ieee80211_frame *);
   1155 			if ((wh->i_fc[0] & IEEE80211_FC0_SUBTYPE_MASK) ==
   1156 			    IEEE80211_FC0_SUBTYPE_PROBE_RESP) {
   1157 				/* fill time stamp */
   1158 				u_int64_t tsf;
   1159 				u_int32_t *tstamp;
   1160 
   1161 				tsf = ath_hal_gettsf64(ah);
   1162 				/* XXX: adjust 100us delay to xmit */
   1163 				tsf += 100;
   1164 				tstamp = (u_int32_t *)&wh[1];
   1165 				tstamp[0] = htole32(tsf & 0xffffffff);
   1166 				tstamp[1] = htole32(tsf >> 32);
   1167 			}
   1168 			sc->sc_stats.ast_tx_mgmt++;
   1169 		}
   1170 
   1171 		if (ath_tx_start(sc, ni, bf, m)) {
   1172 	bad:
   1173 			ifp->if_oerrors++;
   1174 	reclaim:
   1175 			ATH_TXBUF_LOCK(sc);
   1176 			STAILQ_INSERT_TAIL(&sc->sc_txbuf, bf, bf_list);
   1177 			ATH_TXBUF_UNLOCK(sc);
   1178 			if (ni != NULL)
   1179 				ieee80211_free_node(ni);
   1180 			continue;
   1181 		}
   1182 
   1183 		sc->sc_tx_timer = 5;
   1184 		ifp->if_timer = 1;
   1185 	}
   1186 }
   1187 
   1188 static int
   1189 ath_media_change(struct ifnet *ifp)
   1190 {
   1191 #define	IS_UP(ifp) \
   1192 	((ifp->if_flags & (IFF_RUNNING|IFF_UP)) == (IFF_RUNNING|IFF_UP))
   1193 	int error;
   1194 
   1195 	error = ieee80211_media_change(ifp);
   1196 	if (error == ENETRESET) {
   1197 		if (IS_UP(ifp))
   1198 			ath_init(ifp);		/* XXX lose error */
   1199 		error = 0;
   1200 	}
   1201 	return error;
   1202 #undef IS_UP
   1203 }
   1204 
   1205 #ifdef AR_DEBUG
   1206 static void
   1207 ath_keyprint(const char *tag, u_int ix,
   1208 	const HAL_KEYVAL *hk, const u_int8_t mac[IEEE80211_ADDR_LEN])
   1209 {
   1210 	static const char *ciphers[] = {
   1211 		"WEP",
   1212 		"AES-OCB",
   1213 		"AES-CCM",
   1214 		"CKIP",
   1215 		"TKIP",
   1216 		"CLR",
   1217 	};
   1218 	int i, n;
   1219 
   1220 	printf("%s: [%02u] %-7s ", tag, ix, ciphers[hk->kv_type]);
   1221 	for (i = 0, n = hk->kv_len; i < n; i++)
   1222 		printf("%02x", hk->kv_val[i]);
   1223 	printf(" mac %s", ether_sprintf(mac));
   1224 	if (hk->kv_type == HAL_CIPHER_TKIP) {
   1225 		printf(" mic ");
   1226 		for (i = 0; i < sizeof(hk->kv_mic); i++)
   1227 			printf("%02x", hk->kv_mic[i]);
   1228 	}
   1229 	printf("\n");
   1230 }
   1231 #endif
   1232 
   1233 /*
   1234  * Set a TKIP key into the hardware.  This handles the
   1235  * potential distribution of key state to multiple key
   1236  * cache slots for TKIP.
   1237  */
   1238 static int
   1239 ath_keyset_tkip(struct ath_softc *sc, const struct ieee80211_key *k,
   1240 	HAL_KEYVAL *hk, const u_int8_t mac[IEEE80211_ADDR_LEN])
   1241 {
   1242 #define	IEEE80211_KEY_XR	(IEEE80211_KEY_XMIT | IEEE80211_KEY_RECV)
   1243 	static const u_int8_t zerobssid[IEEE80211_ADDR_LEN];
   1244 	struct ath_hal *ah = sc->sc_ah;
   1245 
   1246 	KASSERT(k->wk_cipher->ic_cipher == IEEE80211_CIPHER_TKIP,
   1247 		("got a non-TKIP key, cipher %u", k->wk_cipher->ic_cipher));
   1248 	KASSERT(sc->sc_splitmic, ("key cache !split"));
   1249 	if ((k->wk_flags & IEEE80211_KEY_XR) == IEEE80211_KEY_XR) {
   1250 		/*
   1251 		 * TX key goes at first index, RX key at +32.
   1252 		 * The hal handles the MIC keys at index+64.
   1253 		 */
   1254 		memcpy(hk->kv_mic, k->wk_txmic, sizeof(hk->kv_mic));
   1255 		KEYPRINTF(sc, k->wk_keyix, hk, zerobssid);
   1256 		if (!ath_hal_keyset(ah, k->wk_keyix, hk, zerobssid))
   1257 			return 0;
   1258 
   1259 		memcpy(hk->kv_mic, k->wk_rxmic, sizeof(hk->kv_mic));
   1260 		KEYPRINTF(sc, k->wk_keyix+32, hk, mac);
   1261 		/* XXX delete tx key on failure? */
   1262 		return ath_hal_keyset(ah, k->wk_keyix+32, hk, mac);
   1263 	} else if (k->wk_flags & IEEE80211_KEY_XR) {
   1264 		/*
   1265 		 * TX/RX key goes at first index.
   1266 		 * The hal handles the MIC keys are index+64.
   1267 		 */
   1268 		KASSERT(k->wk_keyix < IEEE80211_WEP_NKID,
   1269 			("group key at index %u", k->wk_keyix));
   1270 		memcpy(hk->kv_mic, k->wk_flags & IEEE80211_KEY_XMIT ?
   1271 			k->wk_txmic : k->wk_rxmic, sizeof(hk->kv_mic));
   1272 		KEYPRINTF(sc, k->wk_keyix, hk, zerobssid);
   1273 		return ath_hal_keyset(ah, k->wk_keyix, hk, zerobssid);
   1274 	}
   1275 	/* XXX key w/o xmit/recv; need this for compression? */
   1276 	return 0;
   1277 #undef IEEE80211_KEY_XR
   1278 }
   1279 
   1280 /*
   1281  * Set a net80211 key into the hardware.  This handles the
   1282  * potential distribution of key state to multiple key
   1283  * cache slots for TKIP with hardware MIC support.
   1284  */
   1285 static int
   1286 ath_keyset(struct ath_softc *sc, const struct ieee80211_key *k,
   1287 	const u_int8_t mac[IEEE80211_ADDR_LEN])
   1288 {
   1289 #define	N(a)	(sizeof(a)/sizeof(a[0]))
   1290 	static const u_int8_t ciphermap[] = {
   1291 		HAL_CIPHER_WEP,		/* IEEE80211_CIPHER_WEP */
   1292 		HAL_CIPHER_TKIP,	/* IEEE80211_CIPHER_TKIP */
   1293 		HAL_CIPHER_AES_OCB,	/* IEEE80211_CIPHER_AES_OCB */
   1294 		HAL_CIPHER_AES_CCM,	/* IEEE80211_CIPHER_AES_CCM */
   1295 		(u_int8_t) -1,		/* 4 is not allocated */
   1296 		HAL_CIPHER_CKIP,	/* IEEE80211_CIPHER_CKIP */
   1297 		HAL_CIPHER_CLR,		/* IEEE80211_CIPHER_NONE */
   1298 	};
   1299 	struct ath_hal *ah = sc->sc_ah;
   1300 	const struct ieee80211_cipher *cip = k->wk_cipher;
   1301 	HAL_KEYVAL hk;
   1302 
   1303 	memset(&hk, 0, sizeof(hk));
   1304 	/*
   1305 	 * Software crypto uses a "clear key" so non-crypto
   1306 	 * state kept in the key cache are maintained and
   1307 	 * so that rx frames have an entry to match.
   1308 	 */
   1309 	if ((k->wk_flags & IEEE80211_KEY_SWCRYPT) == 0) {
   1310 		KASSERT(cip->ic_cipher < N(ciphermap),
   1311 			("invalid cipher type %u", cip->ic_cipher));
   1312 		hk.kv_type = ciphermap[cip->ic_cipher];
   1313 		hk.kv_len = k->wk_keylen;
   1314 		memcpy(hk.kv_val, k->wk_key, k->wk_keylen);
   1315 	} else
   1316 		hk.kv_type = HAL_CIPHER_CLR;
   1317 
   1318 	if (hk.kv_type == HAL_CIPHER_TKIP &&
   1319 	    (k->wk_flags & IEEE80211_KEY_SWMIC) == 0 &&
   1320 	    sc->sc_splitmic) {
   1321 		return ath_keyset_tkip(sc, k, &hk, mac);
   1322 	} else {
   1323 		KEYPRINTF(sc, k->wk_keyix, &hk, mac);
   1324 		return ath_hal_keyset(ah, k->wk_keyix, &hk, mac);
   1325 	}
   1326 #undef N
   1327 }
   1328 
   1329 /*
   1330  * Fill the hardware key cache with key entries.
   1331  */
   1332 static void
   1333 ath_initkeytable(struct ath_softc *sc)
   1334 {
   1335 	struct ieee80211com *ic = &sc->sc_ic;
   1336 	struct ifnet *ifp = &sc->sc_if;
   1337 	struct ath_hal *ah = sc->sc_ah;
   1338 	const u_int8_t *bssid;
   1339 	int i;
   1340 
   1341 	/* XXX maybe should reset all keys when !PRIVACY */
   1342 	if (ic->ic_state == IEEE80211_S_SCAN)
   1343 		bssid = ifp->if_broadcastaddr;
   1344 	else
   1345 		bssid = ic->ic_bss->ni_bssid;
   1346 	for (i = 0; i < IEEE80211_WEP_NKID; i++) {
   1347 		struct ieee80211_key *k = &ic->ic_nw_keys[i];
   1348 
   1349 		if (k->wk_keylen == 0) {
   1350 			ath_hal_keyreset(ah, i);
   1351 			DPRINTF(sc, ATH_DEBUG_KEYCACHE, "%s: reset key %u\n",
   1352 				__func__, i);
   1353 		} else {
   1354 			ath_keyset(sc, k, bssid);
   1355 		}
   1356 	}
   1357 }
   1358 
   1359 /*
   1360  * Allocate tx/rx key slots for TKIP.  We allocate two slots for
   1361  * each key, one for decrypt/encrypt and the other for the MIC.
   1362  */
   1363 static u_int16_t
   1364 key_alloc_2pair(struct ath_softc *sc)
   1365 {
   1366 #define	N(a)	(sizeof(a)/sizeof(a[0]))
   1367 	u_int i, keyix;
   1368 
   1369 	KASSERT(sc->sc_splitmic, ("key cache !split"));
   1370 	/* XXX could optimize */
   1371 	for (i = 0; i < N(sc->sc_keymap)/4; i++) {
   1372 		u_int8_t b = sc->sc_keymap[i];
   1373 		if (b != 0xff) {
   1374 			/*
   1375 			 * One or more slots in this byte are free.
   1376 			 */
   1377 			keyix = i*NBBY;
   1378 			while (b & 1) {
   1379 		again:
   1380 				keyix++;
   1381 				b >>= 1;
   1382 			}
   1383 			/* XXX IEEE80211_KEY_XMIT | IEEE80211_KEY_RECV */
   1384 			if (isset(sc->sc_keymap, keyix+32) ||
   1385 			    isset(sc->sc_keymap, keyix+64) ||
   1386 			    isset(sc->sc_keymap, keyix+32+64)) {
   1387 				/* full pair unavailable */
   1388 				/* XXX statistic */
   1389 				if (keyix == (i+1)*NBBY) {
   1390 					/* no slots were appropriate, advance */
   1391 					continue;
   1392 				}
   1393 				goto again;
   1394 			}
   1395 			setbit(sc->sc_keymap, keyix);
   1396 			setbit(sc->sc_keymap, keyix+64);
   1397 			setbit(sc->sc_keymap, keyix+32);
   1398 			setbit(sc->sc_keymap, keyix+32+64);
   1399 			DPRINTF(sc, ATH_DEBUG_KEYCACHE,
   1400 				"%s: key pair %u,%u %u,%u\n",
   1401 				__func__, keyix, keyix+64,
   1402 				keyix+32, keyix+32+64);
   1403 			return keyix;
   1404 		}
   1405 	}
   1406 	DPRINTF(sc, ATH_DEBUG_KEYCACHE, "%s: out of pair space\n", __func__);
   1407 	return IEEE80211_KEYIX_NONE;
   1408 #undef N
   1409 }
   1410 
   1411 /*
   1412  * Allocate a single key cache slot.
   1413  */
   1414 static u_int16_t
   1415 key_alloc_single(struct ath_softc *sc)
   1416 {
   1417 #define	N(a)	(sizeof(a)/sizeof(a[0]))
   1418 	u_int i, keyix;
   1419 
   1420 	/* XXX try i,i+32,i+64,i+32+64 to minimize key pair conflicts */
   1421 	for (i = 0; i < N(sc->sc_keymap); i++) {
   1422 		u_int8_t b = sc->sc_keymap[i];
   1423 		if (b != 0xff) {
   1424 			/*
   1425 			 * One or more slots are free.
   1426 			 */
   1427 			keyix = i*NBBY;
   1428 			while (b & 1)
   1429 				keyix++, b >>= 1;
   1430 			setbit(sc->sc_keymap, keyix);
   1431 			DPRINTF(sc, ATH_DEBUG_KEYCACHE, "%s: key %u\n",
   1432 				__func__, keyix);
   1433 			return keyix;
   1434 		}
   1435 	}
   1436 	DPRINTF(sc, ATH_DEBUG_KEYCACHE, "%s: out of space\n", __func__);
   1437 	return IEEE80211_KEYIX_NONE;
   1438 #undef N
   1439 }
   1440 
   1441 /*
   1442  * Allocate one or more key cache slots for a uniacst key.  The
   1443  * key itself is needed only to identify the cipher.  For hardware
   1444  * TKIP with split cipher+MIC keys we allocate two key cache slot
   1445  * pairs so that we can setup separate TX and RX MIC keys.  Note
   1446  * that the MIC key for a TKIP key at slot i is assumed by the
   1447  * hardware to be at slot i+64.  This limits TKIP keys to the first
   1448  * 64 entries.
   1449  */
   1450 static int
   1451 ath_key_alloc(struct ieee80211com *ic, const struct ieee80211_key *k)
   1452 {
   1453 	struct ath_softc *sc = ic->ic_ifp->if_softc;
   1454 
   1455 	/*
   1456 	 * Group key allocation must be handled specially for
   1457 	 * parts that do not support multicast key cache search
   1458 	 * functionality.  For those parts the key id must match
   1459 	 * the h/w key index so lookups find the right key.  On
   1460 	 * parts w/ the key search facility we install the sender's
   1461 	 * mac address (with the high bit set) and let the hardware
   1462 	 * find the key w/o using the key id.  This is preferred as
   1463 	 * it permits us to support multiple users for adhoc and/or
   1464 	 * multi-station operation.
   1465 	 */
   1466 	if ((k->wk_flags & IEEE80211_KEY_GROUP) && !sc->sc_mcastkey) {
   1467 		u_int keyix;
   1468 
   1469 		if (!(&ic->ic_nw_keys[0] <= k &&
   1470 		      k < &ic->ic_nw_keys[IEEE80211_WEP_NKID])) {
   1471 			/* should not happen */
   1472 			DPRINTF(sc, ATH_DEBUG_KEYCACHE,
   1473 				"%s: bogus group key\n", __func__);
   1474 			return IEEE80211_KEYIX_NONE;
   1475 		}
   1476 		keyix = k - ic->ic_nw_keys;
   1477 		/*
   1478 		 * XXX we pre-allocate the global keys so
   1479 		 * have no way to check if they've already been allocated.
   1480 		 */
   1481 		return keyix;
   1482 	}
   1483 
   1484 	/*
   1485 	 * We allocate two pair for TKIP when using the h/w to do
   1486 	 * the MIC.  For everything else, including software crypto,
   1487 	 * we allocate a single entry.  Note that s/w crypto requires
   1488 	 * a pass-through slot on the 5211 and 5212.  The 5210 does
   1489 	 * not support pass-through cache entries and we map all
   1490 	 * those requests to slot 0.
   1491 	 */
   1492 	if (k->wk_flags & IEEE80211_KEY_SWCRYPT) {
   1493 		return key_alloc_single(sc);
   1494 	} else if (k->wk_cipher->ic_cipher == IEEE80211_CIPHER_TKIP &&
   1495 	    (k->wk_flags & IEEE80211_KEY_SWMIC) == 0 && sc->sc_splitmic) {
   1496 		return key_alloc_2pair(sc);
   1497 	} else {
   1498 		return key_alloc_single(sc);
   1499 	}
   1500 }
   1501 
   1502 /*
   1503  * Delete an entry in the key cache allocated by ath_key_alloc.
   1504  */
   1505 static int
   1506 ath_key_delete(struct ieee80211com *ic, const struct ieee80211_key *k)
   1507 {
   1508 	struct ath_softc *sc = ic->ic_ifp->if_softc;
   1509 	struct ath_hal *ah = sc->sc_ah;
   1510 	const struct ieee80211_cipher *cip = k->wk_cipher;
   1511 	u_int keyix = k->wk_keyix;
   1512 
   1513 	DPRINTF(sc, ATH_DEBUG_KEYCACHE, "%s: delete key %u\n", __func__, keyix);
   1514 
   1515 	ath_hal_keyreset(ah, keyix);
   1516 	/*
   1517 	 * Handle split tx/rx keying required for TKIP with h/w MIC.
   1518 	 */
   1519 	if (cip->ic_cipher == IEEE80211_CIPHER_TKIP &&
   1520 	    (k->wk_flags & IEEE80211_KEY_SWMIC) == 0 && sc->sc_splitmic)
   1521 		ath_hal_keyreset(ah, keyix+32);		/* RX key */
   1522 	if (keyix >= IEEE80211_WEP_NKID) {
   1523 		/*
   1524 		 * Don't touch keymap entries for global keys so
   1525 		 * they are never considered for dynamic allocation.
   1526 		 */
   1527 		clrbit(sc->sc_keymap, keyix);
   1528 		if (cip->ic_cipher == IEEE80211_CIPHER_TKIP &&
   1529 		    (k->wk_flags & IEEE80211_KEY_SWMIC) == 0 &&
   1530 		    sc->sc_splitmic) {
   1531 			clrbit(sc->sc_keymap, keyix+64);	/* TX key MIC */
   1532 			clrbit(sc->sc_keymap, keyix+32);	/* RX key */
   1533 			clrbit(sc->sc_keymap, keyix+32+64);	/* RX key MIC */
   1534 		}
   1535 	}
   1536 	return 1;
   1537 }
   1538 
   1539 /*
   1540  * Set the key cache contents for the specified key.  Key cache
   1541  * slot(s) must already have been allocated by ath_key_alloc.
   1542  */
   1543 static int
   1544 ath_key_set(struct ieee80211com *ic, const struct ieee80211_key *k,
   1545 	const u_int8_t mac[IEEE80211_ADDR_LEN])
   1546 {
   1547 	struct ath_softc *sc = ic->ic_ifp->if_softc;
   1548 
   1549 	return ath_keyset(sc, k, mac);
   1550 }
   1551 
   1552 /*
   1553  * Block/unblock tx+rx processing while a key change is done.
   1554  * We assume the caller serializes key management operations
   1555  * so we only need to worry about synchronization with other
   1556  * uses that originate in the driver.
   1557  */
   1558 static void
   1559 ath_key_update_begin(struct ieee80211com *ic)
   1560 {
   1561 	struct ifnet *ifp = ic->ic_ifp;
   1562 	struct ath_softc *sc = ifp->if_softc;
   1563 
   1564 	DPRINTF(sc, ATH_DEBUG_KEYCACHE, "%s:\n", __func__);
   1565 #if 0
   1566 	tasklet_disable(&sc->sc_rxtq);
   1567 #endif
   1568 	IF_LOCK(&ifp->if_snd);		/* NB: doesn't block mgmt frames */
   1569 }
   1570 
   1571 static void
   1572 ath_key_update_end(struct ieee80211com *ic)
   1573 {
   1574 	struct ifnet *ifp = ic->ic_ifp;
   1575 	struct ath_softc *sc = ifp->if_softc;
   1576 
   1577 	DPRINTF(sc, ATH_DEBUG_KEYCACHE, "%s:\n", __func__);
   1578 	IF_UNLOCK(&ifp->if_snd);
   1579 #if 0
   1580 	tasklet_enable(&sc->sc_rxtq);
   1581 #endif
   1582 }
   1583 
   1584 /*
   1585  * Calculate the receive filter according to the
   1586  * operating mode and state:
   1587  *
   1588  * o always accept unicast, broadcast, and multicast traffic
   1589  * o maintain current state of phy error reception (the hal
   1590  *   may enable phy error frames for noise immunity work)
   1591  * o probe request frames are accepted only when operating in
   1592  *   hostap, adhoc, or monitor modes
   1593  * o enable promiscuous mode according to the interface state
   1594  * o accept beacons:
   1595  *   - when operating in adhoc mode so the 802.11 layer creates
   1596  *     node table entries for peers,
   1597  *   - when operating in station mode for collecting rssi data when
   1598  *     the station is otherwise quiet, or
   1599  *   - when scanning
   1600  */
   1601 static u_int32_t
   1602 ath_calcrxfilter(struct ath_softc *sc, enum ieee80211_state state)
   1603 {
   1604 	struct ieee80211com *ic = &sc->sc_ic;
   1605 	struct ath_hal *ah = sc->sc_ah;
   1606 	struct ifnet *ifp = &sc->sc_if;
   1607 	u_int32_t rfilt;
   1608 
   1609 	rfilt = (ath_hal_getrxfilter(ah) & HAL_RX_FILTER_PHYERR)
   1610 	      | HAL_RX_FILTER_UCAST | HAL_RX_FILTER_BCAST | HAL_RX_FILTER_MCAST;
   1611 	if (ic->ic_opmode != IEEE80211_M_STA)
   1612 		rfilt |= HAL_RX_FILTER_PROBEREQ;
   1613 	if (ic->ic_opmode != IEEE80211_M_HOSTAP &&
   1614 	    (ifp->if_flags & IFF_PROMISC))
   1615 		rfilt |= HAL_RX_FILTER_PROM;
   1616 	if (ic->ic_opmode == IEEE80211_M_STA ||
   1617 	    ic->ic_opmode == IEEE80211_M_IBSS ||
   1618 	    state == IEEE80211_S_SCAN)
   1619 		rfilt |= HAL_RX_FILTER_BEACON;
   1620 	return rfilt;
   1621 }
   1622 
   1623 static void
   1624 ath_mode_init(struct ath_softc *sc)
   1625 {
   1626 	struct ieee80211com *ic = &sc->sc_ic;
   1627 	struct ath_hal *ah = sc->sc_ah;
   1628 	struct ifnet *ifp = &sc->sc_if;
   1629 	u_int32_t rfilt, mfilt[2], val;
   1630 	u_int8_t pos;
   1631 	struct ifmultiaddr *ifma;
   1632 
   1633 	/* configure rx filter */
   1634 	rfilt = ath_calcrxfilter(sc, ic->ic_state);
   1635 	ath_hal_setrxfilter(ah, rfilt);
   1636 
   1637 	/* configure operational mode */
   1638 	ath_hal_setopmode(ah);
   1639 
   1640 	/*
   1641 	 * Handle any link-level address change.  Note that we only
   1642 	 * need to force ic_myaddr; any other addresses are handled
   1643 	 * as a byproduct of the ifnet code marking the interface
   1644 	 * down then up.
   1645 	 *
   1646 	 * XXX should get from lladdr instead of arpcom but that's more work
   1647 	 */
   1648 	IEEE80211_ADDR_COPY(ic->ic_myaddr, IFP2AC(ifp)->ac_enaddr);
   1649 	ath_hal_setmac(ah, ic->ic_myaddr);
   1650 
   1651 	/* calculate and install multicast filter */
   1652 	if ((ifp->if_flags & IFF_ALLMULTI) == 0) {
   1653 		mfilt[0] = mfilt[1] = 0;
   1654 		TAILQ_FOREACH(ifma, &ifp->if_multiaddrs, ifma_link) {
   1655 			caddr_t dl;
   1656 
   1657 			/* calculate XOR of eight 6bit values */
   1658 			dl = LLADDR((struct sockaddr_dl *) ifma->ifma_addr);
   1659 			val = LE_READ_4(dl + 0);
   1660 			pos = (val >> 18) ^ (val >> 12) ^ (val >> 6) ^ val;
   1661 			val = LE_READ_4(dl + 3);
   1662 			pos ^= (val >> 18) ^ (val >> 12) ^ (val >> 6) ^ val;
   1663 			pos &= 0x3f;
   1664 			mfilt[pos / 32] |= (1 << (pos % 32));
   1665 		}
   1666 	} else {
   1667 		mfilt[0] = mfilt[1] = ~0;
   1668 	}
   1669 	ath_hal_setmcastfilter(ah, mfilt[0], mfilt[1]);
   1670 	DPRINTF(sc, ATH_DEBUG_MODE, "%s: RX filter 0x%x, MC filter %08x:%08x\n",
   1671 		__func__, rfilt, mfilt[0], mfilt[1]);
   1672 }
   1673 
   1674 /*
   1675  * Set the slot time based on the current setting.
   1676  */
   1677 static void
   1678 ath_setslottime(struct ath_softc *sc)
   1679 {
   1680 	struct ieee80211com *ic = &sc->sc_ic;
   1681 	struct ath_hal *ah = sc->sc_ah;
   1682 
   1683 	if (ic->ic_flags & IEEE80211_F_SHSLOT)
   1684 		ath_hal_setslottime(ah, HAL_SLOT_TIME_9);
   1685 	else
   1686 		ath_hal_setslottime(ah, HAL_SLOT_TIME_20);
   1687 	sc->sc_updateslot = OK;
   1688 }
   1689 
   1690 /*
   1691  * Callback from the 802.11 layer to update the
   1692  * slot time based on the current setting.
   1693  */
   1694 static void
   1695 ath_updateslot(struct ifnet *ifp)
   1696 {
   1697 	struct ath_softc *sc = ifp->if_softc;
   1698 	struct ieee80211com *ic = &sc->sc_ic;
   1699 
   1700 	/*
   1701 	 * When not coordinating the BSS, change the hardware
   1702 	 * immediately.  For other operation we defer the change
   1703 	 * until beacon updates have propagated to the stations.
   1704 	 */
   1705 	if (ic->ic_opmode == IEEE80211_M_HOSTAP)
   1706 		sc->sc_updateslot = UPDATE;
   1707 	else
   1708 		ath_setslottime(sc);
   1709 }
   1710 
   1711 /*
   1712  * Setup a h/w transmit queue for beacons.
   1713  */
   1714 static int
   1715 ath_beaconq_setup(struct ath_hal *ah)
   1716 {
   1717 	HAL_TXQ_INFO qi;
   1718 
   1719 	memset(&qi, 0, sizeof(qi));
   1720 	qi.tqi_aifs = HAL_TXQ_USEDEFAULT;
   1721 	qi.tqi_cwmin = HAL_TXQ_USEDEFAULT;
   1722 	qi.tqi_cwmax = HAL_TXQ_USEDEFAULT;
   1723 	/* NB: don't enable any interrupts */
   1724 	return ath_hal_setuptxqueue(ah, HAL_TX_QUEUE_BEACON, &qi);
   1725 }
   1726 
   1727 /*
   1728  * Allocate and setup an initial beacon frame.
   1729  */
   1730 static int
   1731 ath_beacon_alloc(struct ath_softc *sc, struct ieee80211_node *ni)
   1732 {
   1733 	struct ieee80211com *ic = ni->ni_ic;
   1734 	struct ath_buf *bf;
   1735 	struct mbuf *m;
   1736 	int error;
   1737 
   1738 	bf = STAILQ_FIRST(&sc->sc_bbuf);
   1739 	if (bf == NULL) {
   1740 		DPRINTF(sc, ATH_DEBUG_BEACON, "%s: no dma buffers\n", __func__);
   1741 		sc->sc_stats.ast_be_nombuf++;	/* XXX */
   1742 		return ENOMEM;			/* XXX */
   1743 	}
   1744 	/*
   1745 	 * NB: the beacon data buffer must be 32-bit aligned;
   1746 	 * we assume the mbuf routines will return us something
   1747 	 * with this alignment (perhaps should assert).
   1748 	 */
   1749 	m = ieee80211_beacon_alloc(ic, ni, &sc->sc_boff);
   1750 	if (m == NULL) {
   1751 		DPRINTF(sc, ATH_DEBUG_BEACON, "%s: cannot get mbuf\n",
   1752 			__func__);
   1753 		sc->sc_stats.ast_be_nombuf++;
   1754 		return ENOMEM;
   1755 	}
   1756 	error = bus_dmamap_load_mbuf_sg(sc->sc_dmat, bf->bf_dmamap, m,
   1757 				     bf->bf_segs, &bf->bf_nseg,
   1758 				     BUS_DMA_NOWAIT);
   1759 	if (error == 0) {
   1760 		bf->bf_m = m;
   1761 		bf->bf_node = ieee80211_ref_node(ni);
   1762 	} else {
   1763 		m_freem(m);
   1764 	}
   1765 	return error;
   1766 }
   1767 
   1768 /*
   1769  * Setup the beacon frame for transmit.
   1770  */
   1771 static void
   1772 ath_beacon_setup(struct ath_softc *sc, struct ath_buf *bf)
   1773 {
   1774 #define	USE_SHPREAMBLE(_ic) \
   1775 	(((_ic)->ic_flags & (IEEE80211_F_SHPREAMBLE | IEEE80211_F_USEBARKER))\
   1776 		== IEEE80211_F_SHPREAMBLE)
   1777 	struct ieee80211_node *ni = bf->bf_node;
   1778 	struct ieee80211com *ic = ni->ni_ic;
   1779 	struct mbuf *m = bf->bf_m;
   1780 	struct ath_hal *ah = sc->sc_ah;
   1781 	struct ath_node *an = ATH_NODE(ni);
   1782 	struct ath_desc *ds;
   1783 	int flags, antenna;
   1784 	u_int8_t rate;
   1785 
   1786 	DPRINTF(sc, ATH_DEBUG_BEACON, "%s: m %p len %u\n",
   1787 		__func__, m, m->m_len);
   1788 
   1789 	/* setup descriptors */
   1790 	ds = bf->bf_desc;
   1791 
   1792 	flags = HAL_TXDESC_NOACK;
   1793 	if (ic->ic_opmode == IEEE80211_M_IBSS && sc->sc_hasveol) {
   1794 		ds->ds_link = bf->bf_daddr;	/* self-linked */
   1795 		flags |= HAL_TXDESC_VEOL;
   1796 		/*
   1797 		 * Let hardware handle antenna switching.
   1798 		 */
   1799 		antenna = 0;
   1800 	} else {
   1801 		ds->ds_link = 0;
   1802 		/*
   1803 		 * Switch antenna every 4 beacons.
   1804 		 * XXX assumes two antenna
   1805 		 */
   1806 		antenna = (sc->sc_stats.ast_be_xmit & 4 ? 2 : 1);
   1807 	}
   1808 
   1809 	KASSERT(bf->bf_nseg == 1,
   1810 		("multi-segment beacon frame; nseg %u", bf->bf_nseg));
   1811 	ds->ds_data = bf->bf_segs[0].ds_addr;
   1812 	/*
   1813 	 * Calculate rate code.
   1814 	 * XXX everything at min xmit rate
   1815 	 */
   1816 	if (USE_SHPREAMBLE(ic))
   1817 		rate = an->an_tx_mgtratesp;
   1818 	else
   1819 		rate = an->an_tx_mgtrate;
   1820 	ath_hal_setuptxdesc(ah, ds
   1821 		, m->m_len + IEEE80211_CRC_LEN	/* frame length */
   1822 		, sizeof(struct ieee80211_frame)/* header length */
   1823 		, HAL_PKT_TYPE_BEACON		/* Atheros packet type */
   1824 		, ni->ni_txpower		/* txpower XXX */
   1825 		, rate, 1			/* series 0 rate/tries */
   1826 		, HAL_TXKEYIX_INVALID		/* no encryption */
   1827 		, antenna			/* antenna mode */
   1828 		, flags				/* no ack, veol for beacons */
   1829 		, 0				/* rts/cts rate */
   1830 		, 0				/* rts/cts duration */
   1831 	);
   1832 	/* NB: beacon's BufLen must be a multiple of 4 bytes */
   1833 	ath_hal_filltxdesc(ah, ds
   1834 		, roundup(m->m_len, 4)		/* buffer length */
   1835 		, AH_TRUE			/* first segment */
   1836 		, AH_TRUE			/* last segment */
   1837 		, ds				/* first descriptor */
   1838 	);
   1839 #undef USE_SHPREAMBLE
   1840 }
   1841 
   1842 /*
   1843  * Transmit a beacon frame at SWBA.  Dynamic updates to the
   1844  * frame contents are done as needed and the slot time is
   1845  * also adjusted based on current state.
   1846  */
   1847 static void
   1848 ath_beacon_proc(void *arg, int pending)
   1849 {
   1850 	struct ath_softc *sc = arg;
   1851 	struct ath_buf *bf = STAILQ_FIRST(&sc->sc_bbuf);
   1852 	struct ieee80211_node *ni = bf->bf_node;
   1853 	struct ieee80211com *ic = ni->ni_ic;
   1854 	struct ath_hal *ah = sc->sc_ah;
   1855 	struct mbuf *m;
   1856 	int ncabq, error, otherant;
   1857 
   1858 	DPRINTF(sc, ATH_DEBUG_BEACON_PROC, "%s: pending %u\n",
   1859 		__func__, pending);
   1860 
   1861 	if (ic->ic_opmode == IEEE80211_M_STA ||
   1862 	    ic->ic_opmode == IEEE80211_M_MONITOR ||
   1863 	    bf == NULL || bf->bf_m == NULL) {
   1864 		DPRINTF(sc, ATH_DEBUG_ANY, "%s: ic_flags=%x bf=%p bf_m=%p\n",
   1865 			__func__, ic->ic_flags, bf, bf ? bf->bf_m : NULL);
   1866 		return;
   1867 	}
   1868 	/*
   1869 	 * Check if the previous beacon has gone out.  If
   1870 	 * not don't don't try to post another, skip this
   1871 	 * period and wait for the next.  Missed beacons
   1872 	 * indicate a problem and should not occur.  If we
   1873 	 * miss too many consecutive beacons reset the device.
   1874 	 */
   1875 	if (ath_hal_numtxpending(ah, sc->sc_bhalq) != 0) {
   1876 		sc->sc_bmisscount++;
   1877 		DPRINTF(sc, ATH_DEBUG_BEACON_PROC,
   1878 			"%s: missed %u consecutive beacons\n",
   1879 			__func__, sc->sc_bmisscount);
   1880 		if (sc->sc_bmisscount > 3)		/* NB: 3 is a guess */
   1881 			taskqueue_enqueue(taskqueue_swi, &sc->sc_bstucktask);
   1882 		return;
   1883 	}
   1884 	if (sc->sc_bmisscount != 0) {
   1885 		DPRINTF(sc, ATH_DEBUG_BEACON,
   1886 			"%s: resume beacon xmit after %u misses\n",
   1887 			__func__, sc->sc_bmisscount);
   1888 		sc->sc_bmisscount = 0;
   1889 	}
   1890 
   1891 	/*
   1892 	 * Update dynamic beacon contents.  If this returns
   1893 	 * non-zero then we need to remap the memory because
   1894 	 * the beacon frame changed size (probably because
   1895 	 * of the TIM bitmap).
   1896 	 */
   1897 	m = bf->bf_m;
   1898 	ncabq = ath_hal_numtxpending(ah, sc->sc_cabq->axq_qnum);
   1899 	if (ieee80211_beacon_update(ic, bf->bf_node, &sc->sc_boff, m, ncabq)) {
   1900 		/* XXX too conservative? */
   1901 		bus_dmamap_unload(sc->sc_dmat, bf->bf_dmamap);
   1902 		error = bus_dmamap_load_mbuf_sg(sc->sc_dmat, bf->bf_dmamap, m,
   1903 					     bf->bf_segs, &bf->bf_nseg,
   1904 					     BUS_DMA_NOWAIT);
   1905 		if (error != 0) {
   1906 			if_printf(ic->ic_ifp,
   1907 			    "%s: bus_dmamap_load_mbuf_sg failed, error %u\n",
   1908 			    __func__, error);
   1909 			return;
   1910 		}
   1911 	}
   1912 
   1913 	/*
   1914 	 * Handle slot time change when a non-ERP station joins/leaves
   1915 	 * an 11g network.  The 802.11 layer notifies us via callback,
   1916 	 * we mark updateslot, then wait one beacon before effecting
   1917 	 * the change.  This gives associated stations at least one
   1918 	 * beacon interval to note the state change.
   1919 	 */
   1920 	/* XXX locking */
   1921 	if (sc->sc_updateslot == UPDATE)
   1922 		sc->sc_updateslot = COMMIT;	/* commit next beacon */
   1923 	else if (sc->sc_updateslot == COMMIT)
   1924 		ath_setslottime(sc);		/* commit change to h/w */
   1925 
   1926 	/*
   1927 	 * Check recent per-antenna transmit statistics and flip
   1928 	 * the default antenna if noticeably more frames went out
   1929 	 * on the non-default antenna.
   1930 	 * XXX assumes 2 anntenae
   1931 	 */
   1932 	otherant = sc->sc_defant & 1 ? 2 : 1;
   1933 	if (sc->sc_ant_tx[otherant] > sc->sc_ant_tx[sc->sc_defant] + 2)
   1934 		ath_setdefantenna(sc, otherant);
   1935 	sc->sc_ant_tx[1] = sc->sc_ant_tx[2] = 0;
   1936 
   1937 	/*
   1938 	 * Construct tx descriptor.
   1939 	 */
   1940 	ath_beacon_setup(sc, bf);
   1941 
   1942 	/*
   1943 	 * Stop any current dma and put the new frame on the queue.
   1944 	 * This should never fail since we check above that no frames
   1945 	 * are still pending on the queue.
   1946 	 */
   1947 	if (!ath_hal_stoptxdma(ah, sc->sc_bhalq)) {
   1948 		DPRINTF(sc, ATH_DEBUG_ANY,
   1949 			"%s: beacon queue %u did not stop?\n",
   1950 			__func__, sc->sc_bhalq);
   1951 	}
   1952 	bus_dmamap_sync(sc->sc_dmat, bf->bf_dmamap, BUS_DMASYNC_PREWRITE);
   1953 
   1954 	/*
   1955 	 * Enable the CAB queue before the beacon queue to
   1956 	 * insure cab frames are triggered by this beacon.
   1957 	 */
   1958 	if (sc->sc_boff.bo_tim[4] & 1)		/* NB: only at DTIM */
   1959 		ath_hal_txstart(ah, sc->sc_cabq->axq_qnum);
   1960 	ath_hal_puttxbuf(ah, sc->sc_bhalq, bf->bf_daddr);
   1961 	ath_hal_txstart(ah, sc->sc_bhalq);
   1962 	DPRINTF(sc, ATH_DEBUG_BEACON_PROC,
   1963 		"%s: TXDP[%u] = %p (%p)\n", __func__,
   1964 		sc->sc_bhalq, (caddr_t)bf->bf_daddr, bf->bf_desc);
   1965 
   1966 	sc->sc_stats.ast_be_xmit++;
   1967 }
   1968 
   1969 /*
   1970  * Reset the hardware after detecting beacons have stopped.
   1971  */
   1972 static void
   1973 ath_bstuck_proc(void *arg, int pending)
   1974 {
   1975 	struct ath_softc *sc = arg;
   1976 	struct ifnet *ifp = &sc->sc_if;
   1977 
   1978 	if_printf(ifp, "stuck beacon; resetting (bmiss count %u)\n",
   1979 		sc->sc_bmisscount);
   1980 	ath_reset(ifp);
   1981 }
   1982 
   1983 /*
   1984  * Reclaim beacon resources.
   1985  */
   1986 static void
   1987 ath_beacon_free(struct ath_softc *sc)
   1988 {
   1989 	struct ath_buf *bf;
   1990 
   1991 	STAILQ_FOREACH(bf, &sc->sc_bbuf, bf_list) {
   1992 		if (bf->bf_m != NULL) {
   1993 			bus_dmamap_unload(sc->sc_dmat, bf->bf_dmamap);
   1994 			m_freem(bf->bf_m);
   1995 			bf->bf_m = NULL;
   1996 		}
   1997 		if (bf->bf_node != NULL) {
   1998 			ieee80211_free_node(bf->bf_node);
   1999 			bf->bf_node = NULL;
   2000 		}
   2001 	}
   2002 }
   2003 
   2004 /*
   2005  * Configure the beacon and sleep timers.
   2006  *
   2007  * When operating as an AP this resets the TSF and sets
   2008  * up the hardware to notify us when we need to issue beacons.
   2009  *
   2010  * When operating in station mode this sets up the beacon
   2011  * timers according to the timestamp of the last received
   2012  * beacon and the current TSF, configures PCF and DTIM
   2013  * handling, programs the sleep registers so the hardware
   2014  * will wakeup in time to receive beacons, and configures
   2015  * the beacon miss handling so we'll receive a BMISS
   2016  * interrupt when we stop seeing beacons from the AP
   2017  * we've associated with.
   2018  */
   2019 static void
   2020 ath_beacon_config(struct ath_softc *sc)
   2021 {
   2022 	struct ath_hal *ah = sc->sc_ah;
   2023 	struct ieee80211com *ic = &sc->sc_ic;
   2024 	struct ieee80211_node *ni = ic->ic_bss;
   2025 	u_int32_t nexttbtt, intval;
   2026 
   2027 	nexttbtt = (LE_READ_4(ni->ni_tstamp.data + 4) << 22) |
   2028 	    (LE_READ_4(ni->ni_tstamp.data) >> 10);
   2029 	intval = ni->ni_intval & HAL_BEACON_PERIOD;
   2030 	if (nexttbtt == 0)		/* e.g. for ap mode */
   2031 		nexttbtt = intval;
   2032 	else if (intval)		/* NB: can be 0 for monitor mode */
   2033 		nexttbtt = roundup(nexttbtt, intval);
   2034 	DPRINTF(sc, ATH_DEBUG_BEACON, "%s: nexttbtt %u intval %u (%u)\n",
   2035 		__func__, nexttbtt, intval, ni->ni_intval);
   2036 	if (ic->ic_opmode == IEEE80211_M_STA) {
   2037 		HAL_BEACON_STATE bs;
   2038 
   2039 		/* NB: no PCF support right now */
   2040 		memset(&bs, 0, sizeof(bs));
   2041 		bs.bs_intval = intval;
   2042 		bs.bs_nexttbtt = nexttbtt;
   2043 		bs.bs_dtimperiod = bs.bs_intval;
   2044 		bs.bs_nextdtim = nexttbtt;
   2045 		/*
   2046 		 * The 802.11 layer records the offset to the DTIM
   2047 		 * bitmap while receiving beacons; use it here to
   2048 		 * enable h/w detection of our AID being marked in
   2049 		 * the bitmap vector (to indicate frames for us are
   2050 		 * pending at the AP).
   2051 		 */
   2052 		bs.bs_timoffset = ni->ni_timoff;
   2053 		/*
   2054 		 * Calculate the number of consecutive beacons to miss
   2055 		 * before taking a BMISS interrupt.  The configuration
   2056 		 * is specified in ms, so we need to convert that to
   2057 		 * TU's and then calculate based on the beacon interval.
   2058 		 * Note that we clamp the result to at most 10 beacons.
   2059 		 */
   2060 		bs.bs_bmissthreshold = howmany(ic->ic_bmisstimeout, intval);
   2061 		if (bs.bs_bmissthreshold > 10)
   2062 			bs.bs_bmissthreshold = 10;
   2063 		else if (bs.bs_bmissthreshold <= 0)
   2064 			bs.bs_bmissthreshold = 1;
   2065 
   2066 		/*
   2067 		 * Calculate sleep duration.  The configuration is
   2068 		 * given in ms.  We insure a multiple of the beacon
   2069 		 * period is used.  Also, if the sleep duration is
   2070 		 * greater than the DTIM period then it makes senses
   2071 		 * to make it a multiple of that.
   2072 		 *
   2073 		 * XXX fixed at 100ms
   2074 		 */
   2075 		bs.bs_sleepduration =
   2076 			roundup(IEEE80211_MS_TO_TU(100), bs.bs_intval);
   2077 		if (bs.bs_sleepduration > bs.bs_dtimperiod)
   2078 			bs.bs_sleepduration = roundup(bs.bs_sleepduration, bs.bs_dtimperiod);
   2079 
   2080 		DPRINTF(sc, ATH_DEBUG_BEACON,
   2081 			"%s: intval %u nexttbtt %u dtim %u nextdtim %u bmiss %u sleep %u cfp:period %u maxdur %u next %u timoffset %u\n"
   2082 			, __func__
   2083 			, bs.bs_intval
   2084 			, bs.bs_nexttbtt
   2085 			, bs.bs_dtimperiod
   2086 			, bs.bs_nextdtim
   2087 			, bs.bs_bmissthreshold
   2088 			, bs.bs_sleepduration
   2089 			, bs.bs_cfpperiod
   2090 			, bs.bs_cfpmaxduration
   2091 			, bs.bs_cfpnext
   2092 			, bs.bs_timoffset
   2093 		);
   2094 		ath_hal_intrset(ah, 0);
   2095 		ath_hal_beacontimers(ah, &bs);
   2096 		sc->sc_imask |= HAL_INT_BMISS;
   2097 		ath_hal_intrset(ah, sc->sc_imask);
   2098 	} else {
   2099 		ath_hal_intrset(ah, 0);
   2100 		if (nexttbtt == intval)
   2101 			intval |= HAL_BEACON_RESET_TSF;
   2102 		if (ic->ic_opmode == IEEE80211_M_IBSS) {
   2103 			/*
   2104 			 * In IBSS mode enable the beacon timers but only
   2105 			 * enable SWBA interrupts if we need to manually
   2106 			 * prepare beacon frames.  Otherwise we use a
   2107 			 * self-linked tx descriptor and let the hardware
   2108 			 * deal with things.
   2109 			 */
   2110 			intval |= HAL_BEACON_ENA;
   2111 			if (!sc->sc_hasveol)
   2112 				sc->sc_imask |= HAL_INT_SWBA;
   2113 		} else if (ic->ic_opmode == IEEE80211_M_HOSTAP) {
   2114 			/*
   2115 			 * In AP mode we enable the beacon timers and
   2116 			 * SWBA interrupts to prepare beacon frames.
   2117 			 */
   2118 			intval |= HAL_BEACON_ENA;
   2119 			sc->sc_imask |= HAL_INT_SWBA;	/* beacon prepare */
   2120 		}
   2121 		ath_hal_beaconinit(ah, nexttbtt, intval);
   2122 		sc->sc_bmisscount = 0;
   2123 		ath_hal_intrset(ah, sc->sc_imask);
   2124 		/*
   2125 		 * When using a self-linked beacon descriptor in
   2126 		 * ibss mode load it once here.
   2127 		 */
   2128 		if (ic->ic_opmode == IEEE80211_M_IBSS && sc->sc_hasveol)
   2129 			ath_beacon_proc(sc, 0);
   2130 	}
   2131 }
   2132 
   2133 static void
   2134 ath_load_cb(void *arg, bus_dma_segment_t *segs, int nsegs, int error)
   2135 {
   2136 	bus_addr_t *paddr = (bus_addr_t*) arg;
   2137 	KASSERT(error == 0, ("error %u on bus_dma callback", error));
   2138 	*paddr = segs->ds_addr;
   2139 }
   2140 
   2141 static int
   2142 ath_descdma_setup(struct ath_softc *sc,
   2143 	struct ath_descdma *dd, ath_bufhead *head,
   2144 	const char *name, int nbuf, int ndesc)
   2145 {
   2146 #define	DS2PHYS(_dd, _ds) \
   2147 	((_dd)->dd_desc_paddr + ((caddr_t)(_ds) - (caddr_t)(_dd)->dd_desc))
   2148 	struct ifnet *ifp = &sc->sc_if;
   2149 	struct ath_desc *ds;
   2150 	struct ath_buf *bf;
   2151 	int i, bsize, error;
   2152 
   2153 	DPRINTF(sc, ATH_DEBUG_RESET, "%s: %s DMA: %u buffers %u desc/buf\n",
   2154 	    __func__, name, nbuf, ndesc);
   2155 
   2156 	dd->dd_name = name;
   2157 	dd->dd_desc_len = sizeof(struct ath_desc) * nbuf * ndesc;
   2158 
   2159 	/*
   2160 	 * Setup DMA descriptor area.
   2161 	 */
   2162 	error = bus_dma_tag_create(NULL,	/* parent */
   2163 		       PAGE_SIZE, 0,		/* alignment, bounds */
   2164 		       BUS_SPACE_MAXADDR_32BIT,	/* lowaddr */
   2165 		       BUS_SPACE_MAXADDR,	/* highaddr */
   2166 		       NULL, NULL,		/* filter, filterarg */
   2167 		       dd->dd_desc_len,		/* maxsize */
   2168 		       1,			/* nsegments */
   2169 		       BUS_SPACE_MAXADDR,	/* maxsegsize */
   2170 		       BUS_DMA_ALLOCNOW,	/* flags */
   2171 		       NULL,			/* lockfunc */
   2172 		       NULL,			/* lockarg */
   2173 		       &dd->dd_dmat);
   2174 	if (error != 0) {
   2175 		if_printf(ifp, "cannot allocate %s DMA tag\n", dd->dd_name);
   2176 		return error;
   2177 	}
   2178 
   2179 	/* allocate descriptors */
   2180 	error = bus_dmamap_create(dd->dd_dmat, BUS_DMA_NOWAIT, &dd->dd_dmamap);
   2181 	if (error != 0) {
   2182 		if_printf(ifp, "unable to create dmamap for %s descriptors, "
   2183 			"error %u\n", dd->dd_name, error);
   2184 		goto fail0;
   2185 	}
   2186 
   2187 	error = bus_dmamem_alloc(dd->dd_dmat, (void**) &dd->dd_desc,
   2188 				 BUS_DMA_NOWAIT, &dd->dd_dmamap);
   2189 	if (error != 0) {
   2190 		if_printf(ifp, "unable to alloc memory for %u %s descriptors, "
   2191 			"error %u\n", nbuf * ndesc, dd->dd_name, error);
   2192 		goto fail1;
   2193 	}
   2194 
   2195 	error = bus_dmamap_load(dd->dd_dmat, dd->dd_dmamap,
   2196 				dd->dd_desc, dd->dd_desc_len,
   2197 				ath_load_cb, &dd->dd_desc_paddr,
   2198 				BUS_DMA_NOWAIT);
   2199 	if (error != 0) {
   2200 		if_printf(ifp, "unable to map %s descriptors, error %u\n",
   2201 			dd->dd_name, error);
   2202 		goto fail2;
   2203 	}
   2204 
   2205 	ds = dd->dd_desc;
   2206 	DPRINTF(sc, ATH_DEBUG_RESET, "%s: %s DMA map: %p (%lu) -> %p (%lu)\n",
   2207 	    __func__, dd->dd_name, ds, (u_long) dd->dd_desc_len,
   2208 	    (caddr_t) dd->dd_desc_paddr, /*XXX*/ (u_long) dd->dd_desc_len);
   2209 
   2210 	/* allocate rx buffers */
   2211 	bsize = sizeof(struct ath_buf) * nbuf;
   2212 	bf = malloc(bsize, M_ATHDEV, M_NOWAIT | M_ZERO);
   2213 	if (bf == NULL) {
   2214 		if_printf(ifp, "malloc of %s buffers failed, size %u\n",
   2215 			dd->dd_name, bsize);
   2216 		goto fail3;
   2217 	}
   2218 	dd->dd_bufptr = bf;
   2219 
   2220 	STAILQ_INIT(head);
   2221 	for (i = 0; i < nbuf; i++, bf++, ds += ndesc) {
   2222 		bf->bf_desc = ds;
   2223 		bf->bf_daddr = DS2PHYS(dd, ds);
   2224 		error = bus_dmamap_create(sc->sc_dmat, BUS_DMA_NOWAIT,
   2225 				&bf->bf_dmamap);
   2226 		if (error != 0) {
   2227 			if_printf(ifp, "unable to create dmamap for %s "
   2228 				"buffer %u, error %u\n", dd->dd_name, i, error);
   2229 			ath_descdma_cleanup(sc, dd, head);
   2230 			return error;
   2231 		}
   2232 		STAILQ_INSERT_TAIL(head, bf, bf_list);
   2233 	}
   2234 	return 0;
   2235 fail3:
   2236 	bus_dmamap_unload(dd->dd_dmat, dd->dd_dmamap);
   2237 fail2:
   2238 	bus_dmamem_free(dd->dd_dmat, dd->dd_desc, dd->dd_dmamap);
   2239 fail1:
   2240 	bus_dmamap_destroy(dd->dd_dmat, dd->dd_dmamap);
   2241 fail0:
   2242 	bus_dma_tag_destroy(dd->dd_dmat);
   2243 	memset(dd, 0, sizeof(*dd));
   2244 	return error;
   2245 #undef DS2PHYS
   2246 }
   2247 
   2248 static void
   2249 ath_descdma_cleanup(struct ath_softc *sc,
   2250 	struct ath_descdma *dd, ath_bufhead *head)
   2251 {
   2252 	struct ath_buf *bf;
   2253 	struct ieee80211_node *ni;
   2254 
   2255 	bus_dmamap_unload(dd->dd_dmat, dd->dd_dmamap);
   2256 	bus_dmamem_free(dd->dd_dmat, dd->dd_desc, dd->dd_dmamap);
   2257 	bus_dmamap_destroy(dd->dd_dmat, dd->dd_dmamap);
   2258 	bus_dma_tag_destroy(dd->dd_dmat);
   2259 
   2260 	STAILQ_FOREACH(bf, head, bf_list) {
   2261 		if (bf->bf_m) {
   2262 			m_freem(bf->bf_m);
   2263 			bf->bf_m = NULL;
   2264 		}
   2265 		if (bf->bf_dmamap != NULL) {
   2266 			bus_dmamap_destroy(sc->sc_dmat, bf->bf_dmamap);
   2267 			bf->bf_dmamap = NULL;
   2268 		}
   2269 		ni = bf->bf_node;
   2270 		bf->bf_node = NULL;
   2271 		if (ni != NULL) {
   2272 			/*
   2273 			 * Reclaim node reference.
   2274 			 */
   2275 			ieee80211_free_node(ni);
   2276 		}
   2277 	}
   2278 
   2279 	STAILQ_INIT(head);
   2280 	free(dd->dd_bufptr, M_ATHDEV);
   2281 	memset(dd, 0, sizeof(*dd));
   2282 }
   2283 
   2284 static int
   2285 ath_desc_alloc(struct ath_softc *sc)
   2286 {
   2287 	int error;
   2288 
   2289 	error = ath_descdma_setup(sc, &sc->sc_rxdma, &sc->sc_rxbuf,
   2290 			"rx", ATH_RXBUF, 1);
   2291 	if (error != 0)
   2292 		return error;
   2293 
   2294 	error = ath_descdma_setup(sc, &sc->sc_txdma, &sc->sc_txbuf,
   2295 			"tx", ATH_TXBUF, ATH_TXDESC);
   2296 	if (error != 0) {
   2297 		ath_descdma_cleanup(sc, &sc->sc_rxdma, &sc->sc_rxbuf);
   2298 		return error;
   2299 	}
   2300 
   2301 	error = ath_descdma_setup(sc, &sc->sc_bdma, &sc->sc_bbuf,
   2302 			"beacon", 1, 1);
   2303 	if (error != 0) {
   2304 		ath_descdma_cleanup(sc, &sc->sc_txdma, &sc->sc_txbuf);
   2305 		ath_descdma_cleanup(sc, &sc->sc_rxdma, &sc->sc_rxbuf);
   2306 		return error;
   2307 	}
   2308 	return 0;
   2309 }
   2310 
   2311 static void
   2312 ath_desc_free(struct ath_softc *sc)
   2313 {
   2314 
   2315 	if (sc->sc_bdma.dd_desc_len != 0)
   2316 		ath_descdma_cleanup(sc, &sc->sc_bdma, &sc->sc_bbuf);
   2317 	if (sc->sc_txdma.dd_desc_len != 0)
   2318 		ath_descdma_cleanup(sc, &sc->sc_txdma, &sc->sc_txbuf);
   2319 	if (sc->sc_rxdma.dd_desc_len != 0)
   2320 		ath_descdma_cleanup(sc, &sc->sc_rxdma, &sc->sc_rxbuf);
   2321 }
   2322 
   2323 static struct ieee80211_node *
   2324 ath_node_alloc(struct ieee80211_node_table *nt)
   2325 {
   2326 	struct ieee80211com *ic = nt->nt_ic;
   2327 	struct ath_softc *sc = ic->ic_ifp->if_softc;
   2328 	const size_t space = sizeof(struct ath_node) + sc->sc_rc->arc_space;
   2329 	struct ath_node *an;
   2330 
   2331 	an = malloc(space, M_80211_NODE, M_NOWAIT|M_ZERO);
   2332 	if (an == NULL) {
   2333 		/* XXX stat+msg */
   2334 		return NULL;
   2335 	}
   2336 	an->an_avgrssi = ATH_RSSI_DUMMY_MARKER;
   2337 	an->an_halstats.ns_avgbrssi = ATH_RSSI_DUMMY_MARKER;
   2338 	an->an_halstats.ns_avgrssi = ATH_RSSI_DUMMY_MARKER;
   2339 	an->an_halstats.ns_avgtxrssi = ATH_RSSI_DUMMY_MARKER;
   2340 	ath_rate_node_init(sc, an);
   2341 
   2342 	DPRINTF(sc, ATH_DEBUG_NODE, "%s: an %p\n", __func__, an);
   2343 	return &an->an_node;
   2344 }
   2345 
   2346 static void
   2347 ath_node_free(struct ieee80211_node *ni)
   2348 {
   2349 	struct ieee80211com *ic = ni->ni_ic;
   2350         struct ath_softc *sc = ic->ic_ifp->if_softc;
   2351 
   2352 	DPRINTF(sc, ATH_DEBUG_NODE, "%s: ni %p\n", __func__, ni);
   2353 
   2354 	ath_rate_node_cleanup(sc, ATH_NODE(ni));
   2355 	sc->sc_node_free(ni);
   2356 }
   2357 
   2358 static u_int8_t
   2359 ath_node_getrssi(const struct ieee80211_node *ni)
   2360 {
   2361 #define	HAL_EP_RND(x, mul) \
   2362 	((((x)%(mul)) >= ((mul)/2)) ? ((x) + ((mul) - 1)) / (mul) : (x)/(mul))
   2363 	u_int32_t avgrssi = ATH_NODE_CONST(ni)->an_avgrssi;
   2364 	int32_t rssi;
   2365 
   2366 	/*
   2367 	 * When only one frame is received there will be no state in
   2368 	 * avgrssi so fallback on the value recorded by the 802.11 layer.
   2369 	 */
   2370 	if (avgrssi != ATH_RSSI_DUMMY_MARKER)
   2371 		rssi = HAL_EP_RND(avgrssi, HAL_RSSI_EP_MULTIPLIER);
   2372 	else
   2373 		rssi = ni->ni_rssi;
   2374 	/* NB: theoretically we shouldn't need this, but be paranoid */
   2375 	return rssi < 0 ? 0 : rssi > 127 ? 127 : rssi;
   2376 #undef HAL_EP_RND
   2377 }
   2378 
   2379 static int
   2380 ath_rxbuf_init(struct ath_softc *sc, struct ath_buf *bf)
   2381 {
   2382 	struct ath_hal *ah = sc->sc_ah;
   2383 	int error;
   2384 	struct mbuf *m;
   2385 	struct ath_desc *ds;
   2386 
   2387 	m = bf->bf_m;
   2388 	if (m == NULL) {
   2389 		/*
   2390 		 * NB: by assigning a page to the rx dma buffer we
   2391 		 * implicitly satisfy the Atheros requirement that
   2392 		 * this buffer be cache-line-aligned and sized to be
   2393 		 * multiple of the cache line size.  Not doing this
   2394 		 * causes weird stuff to happen (for the 5210 at least).
   2395 		 */
   2396 		m = m_getcl(M_DONTWAIT, MT_DATA, M_PKTHDR);
   2397 		if (m == NULL) {
   2398 			DPRINTF(sc, ATH_DEBUG_ANY,
   2399 				"%s: no mbuf/cluster\n", __func__);
   2400 			sc->sc_stats.ast_rx_nombuf++;
   2401 			return ENOMEM;
   2402 		}
   2403 		bf->bf_m = m;
   2404 		m->m_pkthdr.len = m->m_len = m->m_ext.ext_size;
   2405 
   2406 		error = bus_dmamap_load_mbuf_sg(sc->sc_dmat,
   2407 					     bf->bf_dmamap, m,
   2408 					     bf->bf_segs, &bf->bf_nseg,
   2409 					     BUS_DMA_NOWAIT);
   2410 		if (error != 0) {
   2411 			DPRINTF(sc, ATH_DEBUG_ANY,
   2412 			    "%s: bus_dmamap_load_mbuf_sg failed; error %d\n",
   2413 			    __func__, error);
   2414 			sc->sc_stats.ast_rx_busdma++;
   2415 			return error;
   2416 		}
   2417 		KASSERT(bf->bf_nseg == 1,
   2418 			("multi-segment packet; nseg %u", bf->bf_nseg));
   2419 	}
   2420 	bus_dmamap_sync(sc->sc_dmat, bf->bf_dmamap, BUS_DMASYNC_PREREAD);
   2421 
   2422 	/*
   2423 	 * Setup descriptors.  For receive we always terminate
   2424 	 * the descriptor list with a self-linked entry so we'll
   2425 	 * not get overrun under high load (as can happen with a
   2426 	 * 5212 when ANI processing enables PHY error frames).
   2427 	 *
   2428 	 * To insure the last descriptor is self-linked we create
   2429 	 * each descriptor as self-linked and add it to the end.  As
   2430 	 * each additional descriptor is added the previous self-linked
   2431 	 * entry is ``fixed'' naturally.  This should be safe even
   2432 	 * if DMA is happening.  When processing RX interrupts we
   2433 	 * never remove/process the last, self-linked, entry on the
   2434 	 * descriptor list.  This insures the hardware always has
   2435 	 * someplace to write a new frame.
   2436 	 */
   2437 	ds = bf->bf_desc;
   2438 	ds->ds_link = bf->bf_daddr;	/* link to self */
   2439 	ds->ds_data = bf->bf_segs[0].ds_addr;
   2440 	ath_hal_setuprxdesc(ah, ds
   2441 		, m->m_len		/* buffer size */
   2442 		, 0
   2443 	);
   2444 
   2445 	if (sc->sc_rxlink != NULL)
   2446 		*sc->sc_rxlink = bf->bf_daddr;
   2447 	sc->sc_rxlink = &ds->ds_link;
   2448 	return 0;
   2449 }
   2450 
   2451 /*
   2452  * Extend 15-bit time stamp from rx descriptor to
   2453  * a full 64-bit TSF using the current h/w TSF.
   2454  */
   2455 static __inline u_int64_t
   2456 ath_extend_tsf(struct ath_hal *ah, u_int32_t rstamp)
   2457 {
   2458 	u_int64_t tsf;
   2459 
   2460 	tsf = ath_hal_gettsf64(ah);
   2461 	if ((tsf & 0x7fff) < rstamp)
   2462 		tsf -= 0x8000;
   2463 	return ((tsf &~ 0x7fff) | rstamp);
   2464 }
   2465 
   2466 /*
   2467  * Intercept management frames to collect beacon rssi data
   2468  * and to do ibss merges.
   2469  */
   2470 static void
   2471 ath_recv_mgmt(struct ieee80211com *ic, struct mbuf *m,
   2472 	struct ieee80211_node *ni,
   2473 	int subtype, int rssi, u_int32_t rstamp)
   2474 {
   2475 	struct ath_softc *sc = ic->ic_ifp->if_softc;
   2476 
   2477 	/*
   2478 	 * Call up first so subsequent work can use information
   2479 	 * potentially stored in the node (e.g. for ibss merge).
   2480 	 */
   2481 	sc->sc_recv_mgmt(ic, m, ni, subtype, rssi, rstamp);
   2482 	switch (subtype) {
   2483 	case IEEE80211_FC0_SUBTYPE_BEACON:
   2484 		/* update rssi statistics for use by the hal */
   2485 		ATH_RSSI_LPF(ATH_NODE(ni)->an_halstats.ns_avgbrssi, rssi);
   2486 		/* fall thru... */
   2487 	case IEEE80211_FC0_SUBTYPE_PROBE_RESP:
   2488 		if (ic->ic_opmode == IEEE80211_M_IBSS &&
   2489 		    ic->ic_state == IEEE80211_S_RUN) {
   2490 			u_int64_t tsf = ath_extend_tsf(sc->sc_ah, rstamp);
   2491 			/*
   2492 			 * Handle ibss merge as needed; check the tsf on the
   2493 			 * frame before attempting the merge.  The 802.11 spec
   2494 			 * says the station should change it's bssid to match
   2495 			 * the oldest station with the same ssid, where oldest
   2496 			 * is determined by the tsf.  Note that hardware
   2497 			 * reconfiguration happens through callback to
   2498 			 * ath_newstate as the state machine will go from
   2499 			 * RUN -> RUN when this happens.
   2500 			 */
   2501 			if (le64toh(ni->ni_tstamp.tsf) >= tsf) {
   2502 				DPRINTF(sc, ATH_DEBUG_STATE,
   2503 				    "ibss merge, rstamp %u tsf %ju "
   2504 				    "tstamp %ju\n", rstamp, (uintmax_t)tsf,
   2505 				    (uintmax_t)ni->ni_tstamp.tsf);
   2506 				(void) ieee80211_ibss_merge(ic, ni);
   2507 			}
   2508 		}
   2509 		break;
   2510 	}
   2511 }
   2512 
   2513 /*
   2514  * Set the default antenna.
   2515  */
   2516 static void
   2517 ath_setdefantenna(struct ath_softc *sc, u_int antenna)
   2518 {
   2519 	struct ath_hal *ah = sc->sc_ah;
   2520 
   2521 	/* XXX block beacon interrupts */
   2522 	ath_hal_setdefantenna(ah, antenna);
   2523 	if (sc->sc_defant != antenna)
   2524 		sc->sc_stats.ast_ant_defswitch++;
   2525 	sc->sc_defant = antenna;
   2526 	sc->sc_rxotherant = 0;
   2527 }
   2528 
   2529 static void
   2530 ath_rx_proc(void *arg, int npending)
   2531 {
   2532 #define	PA2DESC(_sc, _pa) \
   2533 	((struct ath_desc *)((caddr_t)(_sc)->sc_rxdma.dd_desc + \
   2534 		((_pa) - (_sc)->sc_rxdma.dd_desc_paddr)))
   2535 	struct ath_softc *sc = arg;
   2536 	struct ath_buf *bf;
   2537 	struct ieee80211com *ic = &sc->sc_ic;
   2538 	struct ifnet *ifp = &sc->sc_if;
   2539 	struct ath_hal *ah = sc->sc_ah;
   2540 	struct ath_desc *ds;
   2541 	struct mbuf *m;
   2542 	struct ieee80211_node *ni;
   2543 	struct ath_node *an;
   2544 	int len, type;
   2545 	u_int phyerr;
   2546 	HAL_STATUS status;
   2547 
   2548 	NET_LOCK_GIANT();		/* XXX */
   2549 
   2550 	DPRINTF(sc, ATH_DEBUG_RX_PROC, "%s: pending %u\n", __func__, npending);
   2551 	do {
   2552 		bf = STAILQ_FIRST(&sc->sc_rxbuf);
   2553 		if (bf == NULL) {		/* NB: shouldn't happen */
   2554 			if_printf(ifp, "%s: no buffer!\n", __func__);
   2555 			break;
   2556 		}
   2557 		ds = bf->bf_desc;
   2558 		if (ds->ds_link == bf->bf_daddr) {
   2559 			/* NB: never process the self-linked entry at the end */
   2560 			break;
   2561 		}
   2562 		m = bf->bf_m;
   2563 		if (m == NULL) {		/* NB: shouldn't happen */
   2564 			if_printf(ifp, "%s: no mbuf!\n", __func__);
   2565 			continue;
   2566 		}
   2567 		/* XXX sync descriptor memory */
   2568 		/*
   2569 		 * Must provide the virtual address of the current
   2570 		 * descriptor, the physical address, and the virtual
   2571 		 * address of the next descriptor in the h/w chain.
   2572 		 * This allows the HAL to look ahead to see if the
   2573 		 * hardware is done with a descriptor by checking the
   2574 		 * done bit in the following descriptor and the address
   2575 		 * of the current descriptor the DMA engine is working
   2576 		 * on.  All this is necessary because of our use of
   2577 		 * a self-linked list to avoid rx overruns.
   2578 		 */
   2579 		status = ath_hal_rxprocdesc(ah, ds,
   2580 				bf->bf_daddr, PA2DESC(sc, ds->ds_link));
   2581 #ifdef AR_DEBUG
   2582 		if (sc->sc_debug & ATH_DEBUG_RECV_DESC)
   2583 			ath_printrxbuf(bf, status == HAL_OK);
   2584 #endif
   2585 		if (status == HAL_EINPROGRESS)
   2586 			break;
   2587 		STAILQ_REMOVE_HEAD(&sc->sc_rxbuf, bf_list);
   2588 		if (ds->ds_rxstat.rs_more) {
   2589 			/*
   2590 			 * Frame spans multiple descriptors; this
   2591 			 * cannot happen yet as we don't support
   2592 			 * jumbograms.  If not in monitor mode,
   2593 			 * discard the frame.
   2594 			 */
   2595 			if (ic->ic_opmode != IEEE80211_M_MONITOR) {
   2596 				sc->sc_stats.ast_rx_toobig++;
   2597 				goto rx_next;
   2598 			}
   2599 			/* fall thru for monitor mode handling... */
   2600 		} else if (ds->ds_rxstat.rs_status != 0) {
   2601 			if (ds->ds_rxstat.rs_status & HAL_RXERR_CRC)
   2602 				sc->sc_stats.ast_rx_crcerr++;
   2603 			if (ds->ds_rxstat.rs_status & HAL_RXERR_FIFO)
   2604 				sc->sc_stats.ast_rx_fifoerr++;
   2605 			if (ds->ds_rxstat.rs_status & HAL_RXERR_PHY) {
   2606 				sc->sc_stats.ast_rx_phyerr++;
   2607 				phyerr = ds->ds_rxstat.rs_phyerr & 0x1f;
   2608 				sc->sc_stats.ast_rx_phy[phyerr]++;
   2609 				goto rx_next;
   2610 			}
   2611 			if (ds->ds_rxstat.rs_status & HAL_RXERR_DECRYPT) {
   2612 				/*
   2613 				 * Decrypt error.  If the error occurred
   2614 				 * because there was no hardware key, then
   2615 				 * let the frame through so the upper layers
   2616 				 * can process it.  This is necessary for 5210
   2617 				 * parts which have no way to setup a ``clear''
   2618 				 * key cache entry.
   2619 				 *
   2620 				 * XXX do key cache faulting
   2621 				 */
   2622 				if (ds->ds_rxstat.rs_keyix == HAL_RXKEYIX_INVALID)
   2623 					goto rx_accept;
   2624 				sc->sc_stats.ast_rx_badcrypt++;
   2625 			}
   2626 			if (ds->ds_rxstat.rs_status & HAL_RXERR_MIC) {
   2627 				sc->sc_stats.ast_rx_badmic++;
   2628 				/*
   2629 				 * Do minimal work required to hand off
   2630 				 * the 802.11 header for notifcation.
   2631 				 */
   2632 				/* XXX frag's and qos frames */
   2633 				len = ds->ds_rxstat.rs_datalen;
   2634 				if (len >= sizeof (struct ieee80211_frame)) {
   2635 					bus_dmamap_sync(sc->sc_dmat,
   2636 					    bf->bf_dmamap,
   2637 					    BUS_DMASYNC_POSTREAD);
   2638 					ieee80211_notify_michael_failure(ic,
   2639 					    mtod(m, struct ieee80211_frame *),
   2640 					    sc->sc_splitmic ?
   2641 					        ds->ds_rxstat.rs_keyix-32 :
   2642 					        ds->ds_rxstat.rs_keyix
   2643 					);
   2644 				}
   2645 			}
   2646 			ifp->if_ierrors++;
   2647 			/*
   2648 			 * Reject error frames, we normally don't want
   2649 			 * to see them in monitor mode (in monitor mode
   2650 			 * allow through packets that have crypto problems).
   2651 			 */
   2652 			if ((ds->ds_rxstat.rs_status &~
   2653 				(HAL_RXERR_DECRYPT|HAL_RXERR_MIC)) ||
   2654 			    sc->sc_ic.ic_opmode != IEEE80211_M_MONITOR)
   2655 				goto rx_next;
   2656 		}
   2657 rx_accept:
   2658 		/*
   2659 		 * Sync and unmap the frame.  At this point we're
   2660 		 * committed to passing the mbuf somewhere so clear
   2661 		 * bf_m; this means a new sk_buff must be allocated
   2662 		 * when the rx descriptor is setup again to receive
   2663 		 * another frame.
   2664 		 */
   2665 		bus_dmamap_sync(sc->sc_dmat, bf->bf_dmamap,
   2666 		    BUS_DMASYNC_POSTREAD);
   2667 		bus_dmamap_unload(sc->sc_dmat, bf->bf_dmamap);
   2668 		bf->bf_m = NULL;
   2669 
   2670 		m->m_pkthdr.rcvif = ifp;
   2671 		len = ds->ds_rxstat.rs_datalen;
   2672 		m->m_pkthdr.len = m->m_len = len;
   2673 
   2674 		sc->sc_stats.ast_ant_rx[ds->ds_rxstat.rs_antenna]++;
   2675 
   2676 		if (sc->sc_drvbpf) {
   2677 			u_int8_t rix;
   2678 
   2679 			/*
   2680 			 * Discard anything shorter than an ack or cts.
   2681 			 */
   2682 			if (len < IEEE80211_ACK_LEN) {
   2683 				DPRINTF(sc, ATH_DEBUG_RECV,
   2684 					"%s: runt packet %d\n",
   2685 					__func__, len);
   2686 				sc->sc_stats.ast_rx_tooshort++;
   2687 				m_freem(m);
   2688 				goto rx_next;
   2689 			}
   2690 			rix = ds->ds_rxstat.rs_rate;
   2691 			sc->sc_rx_th.wr_flags = sc->sc_hwmap[rix].rxflags;
   2692 			sc->sc_rx_th.wr_rate = sc->sc_hwmap[rix].ieeerate;
   2693 			sc->sc_rx_th.wr_antsignal = ds->ds_rxstat.rs_rssi;
   2694 			sc->sc_rx_th.wr_antenna = ds->ds_rxstat.rs_antenna;
   2695 			/* XXX TSF */
   2696 
   2697 			bpf_mtap2(sc->sc_drvbpf,
   2698 				&sc->sc_rx_th, sc->sc_rx_th_len, m);
   2699 		}
   2700 
   2701 		/*
   2702 		 * From this point on we assume the frame is at least
   2703 		 * as large as ieee80211_frame_min; verify that.
   2704 		 */
   2705 		if (len < IEEE80211_MIN_LEN) {
   2706 			DPRINTF(sc, ATH_DEBUG_RECV, "%s: short packet %d\n",
   2707 				__func__, len);
   2708 			sc->sc_stats.ast_rx_tooshort++;
   2709 			m_freem(m);
   2710 			goto rx_next;
   2711 		}
   2712 
   2713 		if (IFF_DUMPPKTS(sc, ATH_DEBUG_RECV)) {
   2714 			ieee80211_dump_pkt(mtod(m, caddr_t), len,
   2715 				   sc->sc_hwmap[ds->ds_rxstat.rs_rate].ieeerate,
   2716 				   ds->ds_rxstat.rs_rssi);
   2717 		}
   2718 
   2719 		m_adj(m, -IEEE80211_CRC_LEN);
   2720 
   2721 		/*
   2722 		 * Locate the node for sender, track state, and then
   2723 		 * pass the (referenced) node up to the 802.11 layer
   2724 		 * for its use.
   2725 		 */
   2726 		ni = ieee80211_find_rxnode(ic,
   2727 			mtod(m, const struct ieee80211_frame_min *));
   2728 
   2729 		/*
   2730 		 * Track rx rssi and do any rx antenna management.
   2731 		 */
   2732 		an = ATH_NODE(ni);
   2733 		ATH_RSSI_LPF(an->an_avgrssi, ds->ds_rxstat.rs_rssi);
   2734 		if (sc->sc_diversity) {
   2735 			/*
   2736 			 * When using fast diversity, change the default rx
   2737 			 * antenna if diversity chooses the other antenna 3
   2738 			 * times in a row.
   2739 			 */
   2740 			if (sc->sc_defant != ds->ds_rxstat.rs_antenna) {
   2741 				if (++sc->sc_rxotherant >= 3)
   2742 					ath_setdefantenna(sc,
   2743 						ds->ds_rxstat.rs_antenna);
   2744 			} else
   2745 				sc->sc_rxotherant = 0;
   2746 		}
   2747 
   2748 		/*
   2749 		 * Send frame up for processing.
   2750 		 */
   2751 		type = ieee80211_input(ic, m, ni,
   2752 			ds->ds_rxstat.rs_rssi, ds->ds_rxstat.rs_tstamp);
   2753 
   2754 		if (sc->sc_softled) {
   2755 			/*
   2756 			 * Blink for any data frame.  Otherwise do a
   2757 			 * heartbeat-style blink when idle.  The latter
   2758 			 * is mainly for station mode where we depend on
   2759 			 * periodic beacon frames to trigger the poll event.
   2760 			 */
   2761 			if (type == IEEE80211_FC0_TYPE_DATA) {
   2762 				sc->sc_rxrate = ds->ds_rxstat.rs_rate;
   2763 				ath_led_event(sc, ATH_LED_RX);
   2764 			} else if (ticks - sc->sc_ledevent >= sc->sc_ledidle)
   2765 				ath_led_event(sc, ATH_LED_POLL);
   2766 		}
   2767 
   2768 		/*
   2769 		 * Reclaim node reference.
   2770 		 */
   2771 		ieee80211_free_node(ni);
   2772 rx_next:
   2773 		STAILQ_INSERT_TAIL(&sc->sc_rxbuf, bf, bf_list);
   2774 	} while (ath_rxbuf_init(sc, bf) == 0);
   2775 
   2776 	/* rx signal state monitoring */
   2777 	ath_hal_rxmonitor(ah, &ATH_NODE(ic->ic_bss)->an_halstats);
   2778 
   2779 	NET_UNLOCK_GIANT();		/* XXX */
   2780 #undef PA2DESC
   2781 }
   2782 
   2783 /*
   2784  * Setup a h/w transmit queue.
   2785  */
   2786 static struct ath_txq *
   2787 ath_txq_setup(struct ath_softc *sc, int qtype, int subtype)
   2788 {
   2789 #define	N(a)	(sizeof(a)/sizeof(a[0]))
   2790 	struct ath_hal *ah = sc->sc_ah;
   2791 	HAL_TXQ_INFO qi;
   2792 	int qnum;
   2793 
   2794 	memset(&qi, 0, sizeof(qi));
   2795 	qi.tqi_subtype = subtype;
   2796 	qi.tqi_aifs = HAL_TXQ_USEDEFAULT;
   2797 	qi.tqi_cwmin = HAL_TXQ_USEDEFAULT;
   2798 	qi.tqi_cwmax = HAL_TXQ_USEDEFAULT;
   2799 	/*
   2800 	 * Enable interrupts only for EOL and DESC conditions.
   2801 	 * We mark tx descriptors to receive a DESC interrupt
   2802 	 * when a tx queue gets deep; otherwise waiting for the
   2803 	 * EOL to reap descriptors.  Note that this is done to
   2804 	 * reduce interrupt load and this only defers reaping
   2805 	 * descriptors, never transmitting frames.  Aside from
   2806 	 * reducing interrupts this also permits more concurrency.
   2807 	 * The only potential downside is if the tx queue backs
   2808 	 * up in which case the top half of the kernel may backup
   2809 	 * due to a lack of tx descriptors.
   2810 	 */
   2811 	qi.tqi_qflags = TXQ_FLAG_TXEOLINT_ENABLE | TXQ_FLAG_TXDESCINT_ENABLE;
   2812 	qnum = ath_hal_setuptxqueue(ah, qtype, &qi);
   2813 	if (qnum == -1) {
   2814 		/*
   2815 		 * NB: don't print a message, this happens
   2816 		 * normally on parts with too few tx queues
   2817 		 */
   2818 		return NULL;
   2819 	}
   2820 	if (qnum >= N(sc->sc_txq)) {
   2821 		device_printf(sc->sc_dev,
   2822 			"hal qnum %u out of range, max %zu!\n",
   2823 			qnum, N(sc->sc_txq));
   2824 		ath_hal_releasetxqueue(ah, qnum);
   2825 		return NULL;
   2826 	}
   2827 	if (!ATH_TXQ_SETUP(sc, qnum)) {
   2828 		struct ath_txq *txq = &sc->sc_txq[qnum];
   2829 
   2830 		txq->axq_qnum = qnum;
   2831 		txq->axq_depth = 0;
   2832 		txq->axq_intrcnt = 0;
   2833 		txq->axq_link = NULL;
   2834 		STAILQ_INIT(&txq->axq_q);
   2835 		ATH_TXQ_LOCK_INIT(sc, txq);
   2836 		sc->sc_txqsetup |= 1<<qnum;
   2837 	}
   2838 	return &sc->sc_txq[qnum];
   2839 #undef N
   2840 }
   2841 
   2842 /*
   2843  * Setup a hardware data transmit queue for the specified
   2844  * access control.  The hal may not support all requested
   2845  * queues in which case it will return a reference to a
   2846  * previously setup queue.  We record the mapping from ac's
   2847  * to h/w queues for use by ath_tx_start and also track
   2848  * the set of h/w queues being used to optimize work in the
   2849  * transmit interrupt handler and related routines.
   2850  */
   2851 static int
   2852 ath_tx_setup(struct ath_softc *sc, int ac, int haltype)
   2853 {
   2854 #define	N(a)	(sizeof(a)/sizeof(a[0]))
   2855 	struct ath_txq *txq;
   2856 
   2857 	if (ac >= N(sc->sc_ac2q)) {
   2858 		device_printf(sc->sc_dev, "AC %u out of range, max %zu!\n",
   2859 			ac, N(sc->sc_ac2q));
   2860 		return 0;
   2861 	}
   2862 	txq = ath_txq_setup(sc, HAL_TX_QUEUE_DATA, haltype);
   2863 	if (txq != NULL) {
   2864 		sc->sc_ac2q[ac] = txq;
   2865 		return 1;
   2866 	} else
   2867 		return 0;
   2868 #undef N
   2869 }
   2870 
   2871 /*
   2872  * Update WME parameters for a transmit queue.
   2873  */
   2874 static int
   2875 ath_txq_update(struct ath_softc *sc, int ac)
   2876 {
   2877 #define	ATH_EXPONENT_TO_VALUE(v)	((1<<v)-1)
   2878 #define	ATH_TXOP_TO_US(v)		(v<<5)
   2879 	struct ieee80211com *ic = &sc->sc_ic;
   2880 	struct ath_txq *txq = sc->sc_ac2q[ac];
   2881 	struct wmeParams *wmep = &ic->ic_wme.wme_chanParams.cap_wmeParams[ac];
   2882 	struct ath_hal *ah = sc->sc_ah;
   2883 	HAL_TXQ_INFO qi;
   2884 
   2885 	ath_hal_gettxqueueprops(ah, txq->axq_qnum, &qi);
   2886 	qi.tqi_aifs = wmep->wmep_aifsn;
   2887 	qi.tqi_cwmin = ATH_EXPONENT_TO_VALUE(wmep->wmep_logcwmin);
   2888 	qi.tqi_cwmax = ATH_EXPONENT_TO_VALUE(wmep->wmep_logcwmax);
   2889 	qi.tqi_burstTime = ATH_TXOP_TO_US(wmep->wmep_txopLimit);
   2890 
   2891 	if (!ath_hal_settxqueueprops(ah, txq->axq_qnum, &qi)) {
   2892 		device_printf(sc->sc_dev, "unable to update hardware queue "
   2893 			"parameters for %s traffic!\n",
   2894 			ieee80211_wme_acnames[ac]);
   2895 		return 0;
   2896 	} else {
   2897 		ath_hal_resettxqueue(ah, txq->axq_qnum); /* push to h/w */
   2898 		return 1;
   2899 	}
   2900 #undef ATH_TXOP_TO_US
   2901 #undef ATH_EXPONENT_TO_VALUE
   2902 }
   2903 
   2904 /*
   2905  * Callback from the 802.11 layer to update WME parameters.
   2906  */
   2907 static int
   2908 ath_wme_update(struct ieee80211com *ic)
   2909 {
   2910 	struct ath_softc *sc = ic->ic_ifp->if_softc;
   2911 
   2912 	return !ath_txq_update(sc, WME_AC_BE) ||
   2913 	    !ath_txq_update(sc, WME_AC_BK) ||
   2914 	    !ath_txq_update(sc, WME_AC_VI) ||
   2915 	    !ath_txq_update(sc, WME_AC_VO) ? EIO : 0;
   2916 }
   2917 
   2918 /*
   2919  * Reclaim resources for a setup queue.
   2920  */
   2921 static void
   2922 ath_tx_cleanupq(struct ath_softc *sc, struct ath_txq *txq)
   2923 {
   2924 
   2925 	ath_hal_releasetxqueue(sc->sc_ah, txq->axq_qnum);
   2926 	ATH_TXQ_LOCK_DESTROY(txq);
   2927 	sc->sc_txqsetup &= ~(1<<txq->axq_qnum);
   2928 }
   2929 
   2930 /*
   2931  * Reclaim all tx queue resources.
   2932  */
   2933 static void
   2934 ath_tx_cleanup(struct ath_softc *sc)
   2935 {
   2936 	int i;
   2937 
   2938 	ATH_TXBUF_LOCK_DESTROY(sc);
   2939 	for (i = 0; i < HAL_NUM_TX_QUEUES; i++)
   2940 		if (ATH_TXQ_SETUP(sc, i))
   2941 			ath_tx_cleanupq(sc, &sc->sc_txq[i]);
   2942 }
   2943 
   2944 /*
   2945  * Defragment an mbuf chain, returning at most maxfrags separate
   2946  * mbufs+clusters.  If this is not possible NULL is returned and
   2947  * the original mbuf chain is left in it's present (potentially
   2948  * modified) state.  We use two techniques: collapsing consecutive
   2949  * mbufs and replacing consecutive mbufs by a cluster.
   2950  */
   2951 static struct mbuf *
   2952 ath_defrag(struct mbuf *m0, int how, int maxfrags)
   2953 {
   2954 	struct mbuf *m, *n, *n2, **prev;
   2955 	u_int curfrags;
   2956 
   2957 	/*
   2958 	 * Calculate the current number of frags.
   2959 	 */
   2960 	curfrags = 0;
   2961 	for (m = m0; m != NULL; m = m->m_next)
   2962 		curfrags++;
   2963 	/*
   2964 	 * First, try to collapse mbufs.  Note that we always collapse
   2965 	 * towards the front so we don't need to deal with moving the
   2966 	 * pkthdr.  This may be suboptimal if the first mbuf has much
   2967 	 * less data than the following.
   2968 	 */
   2969 	m = m0;
   2970 again:
   2971 	for (;;) {
   2972 		n = m->m_next;
   2973 		if (n == NULL)
   2974 			break;
   2975 		if ((m->m_flags & M_RDONLY) == 0 &&
   2976 		    n->m_len < M_TRAILINGSPACE(m)) {
   2977 			bcopy(mtod(n, void *), mtod(m, char *) + m->m_len,
   2978 				n->m_len);
   2979 			m->m_len += n->m_len;
   2980 			m->m_next = n->m_next;
   2981 			m_free(n);
   2982 			if (--curfrags <= maxfrags)
   2983 				return m0;
   2984 		} else
   2985 			m = n;
   2986 	}
   2987 	KASSERT(maxfrags > 1,
   2988 		("maxfrags %u, but normal collapse failed", maxfrags));
   2989 	/*
   2990 	 * Collapse consecutive mbufs to a cluster.
   2991 	 */
   2992 	prev = &m0->m_next;		/* NB: not the first mbuf */
   2993 	while ((n = *prev) != NULL) {
   2994 		if ((n2 = n->m_next) != NULL &&
   2995 		    n->m_len + n2->m_len < MCLBYTES) {
   2996 			m = m_getcl(how, MT_DATA, 0);
   2997 			if (m == NULL)
   2998 				goto bad;
   2999 			bcopy(mtod(n, void *), mtod(m, void *), n->m_len);
   3000 			bcopy(mtod(n2, void *), mtod(m, char *) + n->m_len,
   3001 				n2->m_len);
   3002 			m->m_len = n->m_len + n2->m_len;
   3003 			m->m_next = n2->m_next;
   3004 			*prev = m;
   3005 			m_free(n);
   3006 			m_free(n2);
   3007 			if (--curfrags <= maxfrags)	/* +1 cl -2 mbufs */
   3008 				return m0;
   3009 			/*
   3010 			 * Still not there, try the normal collapse
   3011 			 * again before we allocate another cluster.
   3012 			 */
   3013 			goto again;
   3014 		}
   3015 		prev = &n->m_next;
   3016 	}
   3017 	/*
   3018 	 * No place where we can collapse to a cluster; punt.
   3019 	 * This can occur if, for example, you request 2 frags
   3020 	 * but the packet requires that both be clusters (we
   3021 	 * never reallocate the first mbuf to avoid moving the
   3022 	 * packet header).
   3023 	 */
   3024 bad:
   3025 	return NULL;
   3026 }
   3027 
   3028 static int
   3029 ath_tx_start(struct ath_softc *sc, struct ieee80211_node *ni, struct ath_buf *bf,
   3030     struct mbuf *m0)
   3031 {
   3032 #define	CTS_DURATION \
   3033 	ath_hal_computetxtime(ah, rt, IEEE80211_ACK_LEN, cix, AH_TRUE)
   3034 #define	updateCTSForBursting(_ah, _ds, _txq) \
   3035 	ath_hal_updateCTSForBursting(_ah, _ds, \
   3036 	    _txq->axq_linkbuf != NULL ? _txq->axq_linkbuf->bf_desc : NULL, \
   3037 	    _txq->axq_lastdsWithCTS, _txq->axq_gatingds, \
   3038 	    txopLimit, CTS_DURATION)
   3039 	struct ieee80211com *ic = &sc->sc_ic;
   3040 	struct ath_hal *ah = sc->sc_ah;
   3041 	struct ifnet *ifp = &sc->sc_if;
   3042 	const struct chanAccParams *cap = &ic->ic_wme.wme_chanParams;
   3043 	int i, error, iswep, ismcast, keyix, hdrlen, pktlen, try0;
   3044 	u_int8_t rix, txrate, ctsrate;
   3045 	u_int8_t cix = 0xff;		/* NB: silence compiler */
   3046 	struct ath_desc *ds, *ds0;
   3047 	struct ath_txq *txq;
   3048 	struct ieee80211_frame *wh;
   3049 	u_int subtype, flags, ctsduration;
   3050 	HAL_PKT_TYPE atype;
   3051 	const HAL_RATE_TABLE *rt;
   3052 	HAL_BOOL shortPreamble;
   3053 	struct ath_node *an;
   3054 	struct mbuf *m;
   3055 	u_int pri;
   3056 
   3057 	wh = mtod(m0, struct ieee80211_frame *);
   3058 	iswep = wh->i_fc[1] & IEEE80211_FC1_WEP;
   3059 	ismcast = IEEE80211_IS_MULTICAST(wh->i_addr1);
   3060 	hdrlen = ieee80211_anyhdrsize(wh);
   3061 	/*
   3062 	 * Packet length must not include any
   3063 	 * pad bytes; deduct them here.
   3064 	 */
   3065 	pktlen = m0->m_pkthdr.len - (hdrlen & 3);
   3066 
   3067 	if (iswep) {
   3068 		const struct ieee80211_cipher *cip;
   3069 		struct ieee80211_key *k;
   3070 
   3071 		/*
   3072 		 * Construct the 802.11 header+trailer for an encrypted
   3073 		 * frame. The only reason this can fail is because of an
   3074 		 * unknown or unsupported cipher/key type.
   3075 		 */
   3076 		k = ieee80211_crypto_encap(ic, ni, m0);
   3077 		if (k == NULL) {
   3078 			/*
   3079 			 * This can happen when the key is yanked after the
   3080 			 * frame was queued.  Just discard the frame; the
   3081 			 * 802.11 layer counts failures and provides
   3082 			 * debugging/diagnostics.
   3083 			 */
   3084 			m_freem(m0);
   3085 			return EIO;
   3086 		}
   3087 		/*
   3088 		 * Adjust the packet + header lengths for the crypto
   3089 		 * additions and calculate the h/w key index.  When
   3090 		 * a s/w mic is done the frame will have had any mic
   3091 		 * added to it prior to entry so skb->len above will
   3092 		 * account for it. Otherwise we need to add it to the
   3093 		 * packet length.
   3094 		 */
   3095 		cip = k->wk_cipher;
   3096 		hdrlen += cip->ic_header;
   3097 		pktlen += cip->ic_header + cip->ic_trailer;
   3098 		if ((k->wk_flags & IEEE80211_KEY_SWMIC) == 0)
   3099 			pktlen += cip->ic_miclen;
   3100 		keyix = k->wk_keyix;
   3101 
   3102 		/* packet header may have moved, reset our local pointer */
   3103 		wh = mtod(m0, struct ieee80211_frame *);
   3104 	} else
   3105 		keyix = HAL_TXKEYIX_INVALID;
   3106 
   3107 	pktlen += IEEE80211_CRC_LEN;
   3108 
   3109 	/*
   3110 	 * Load the DMA map so any coalescing is done.  This
   3111 	 * also calculates the number of descriptors we need.
   3112 	 */
   3113 	error = bus_dmamap_load_mbuf_sg(sc->sc_dmat, bf->bf_dmamap, m0,
   3114 				     bf->bf_segs, &bf->bf_nseg,
   3115 				     BUS_DMA_NOWAIT);
   3116 	if (error == EFBIG) {
   3117 		/* XXX packet requires too many descriptors */
   3118 		bf->bf_nseg = ATH_TXDESC+1;
   3119 	} else if (error != 0) {
   3120 		sc->sc_stats.ast_tx_busdma++;
   3121 		m_freem(m0);
   3122 		return error;
   3123 	}
   3124 	/*
   3125 	 * Discard null packets and check for packets that
   3126 	 * require too many TX descriptors.  We try to convert
   3127 	 * the latter to a cluster.
   3128 	 */
   3129 	if (bf->bf_nseg > ATH_TXDESC) {		/* too many desc's, linearize */
   3130 		sc->sc_stats.ast_tx_linear++;
   3131 		m = ath_defrag(m0, M_DONTWAIT, ATH_TXDESC);
   3132 		if (m == NULL) {
   3133 			m_freem(m0);
   3134 			sc->sc_stats.ast_tx_nombuf++;
   3135 			return ENOMEM;
   3136 		}
   3137 		m0 = m;
   3138 		error = bus_dmamap_load_mbuf_sg(sc->sc_dmat, bf->bf_dmamap, m0,
   3139 					     bf->bf_segs, &bf->bf_nseg,
   3140 					     BUS_DMA_NOWAIT);
   3141 		if (error != 0) {
   3142 			sc->sc_stats.ast_tx_busdma++;
   3143 			m_freem(m0);
   3144 			return error;
   3145 		}
   3146 		KASSERT(bf->bf_nseg <= ATH_TXDESC,
   3147 		    ("too many segments after defrag; nseg %u", bf->bf_nseg));
   3148 	} else if (bf->bf_nseg == 0) {		/* null packet, discard */
   3149 		sc->sc_stats.ast_tx_nodata++;
   3150 		m_freem(m0);
   3151 		return EIO;
   3152 	}
   3153 	DPRINTF(sc, ATH_DEBUG_XMIT, "%s: m %p len %u\n", __func__, m0, pktlen);
   3154 	bus_dmamap_sync(sc->sc_dmat, bf->bf_dmamap, BUS_DMASYNC_PREWRITE);
   3155 	bf->bf_m = m0;
   3156 	bf->bf_node = ni;			/* NB: held reference */
   3157 
   3158 	/* setup descriptors */
   3159 	ds = bf->bf_desc;
   3160 	rt = sc->sc_currates;
   3161 	KASSERT(rt != NULL, ("no rate table, mode %u", sc->sc_curmode));
   3162 
   3163 	/*
   3164 	 * NB: the 802.11 layer marks whether or not we should
   3165 	 * use short preamble based on the current mode and
   3166 	 * negotiated parameters.
   3167 	 */
   3168 	if ((ic->ic_flags & IEEE80211_F_SHPREAMBLE) &&
   3169 	    (ni->ni_capinfo & IEEE80211_CAPINFO_SHORT_PREAMBLE)) {
   3170 		shortPreamble = AH_TRUE;
   3171 		sc->sc_stats.ast_tx_shortpre++;
   3172 	} else {
   3173 		shortPreamble = AH_FALSE;
   3174 	}
   3175 
   3176 	an = ATH_NODE(ni);
   3177 	flags = HAL_TXDESC_CLRDMASK;		/* XXX needed for crypto errs */
   3178 	/*
   3179 	 * Calculate Atheros packet type from IEEE80211 packet header,
   3180 	 * setup for rate calculations, and select h/w transmit queue.
   3181 	 */
   3182 	switch (wh->i_fc[0] & IEEE80211_FC0_TYPE_MASK) {
   3183 	case IEEE80211_FC0_TYPE_MGT:
   3184 		subtype = wh->i_fc[0] & IEEE80211_FC0_SUBTYPE_MASK;
   3185 		if (subtype == IEEE80211_FC0_SUBTYPE_BEACON)
   3186 			atype = HAL_PKT_TYPE_BEACON;
   3187 		else if (subtype == IEEE80211_FC0_SUBTYPE_PROBE_RESP)
   3188 			atype = HAL_PKT_TYPE_PROBE_RESP;
   3189 		else if (subtype == IEEE80211_FC0_SUBTYPE_ATIM)
   3190 			atype = HAL_PKT_TYPE_ATIM;
   3191 		else
   3192 			atype = HAL_PKT_TYPE_NORMAL;	/* XXX */
   3193 		rix = 0;			/* XXX lowest rate */
   3194 		try0 = ATH_TXMAXTRY;
   3195 		if (shortPreamble)
   3196 			txrate = an->an_tx_mgtratesp;
   3197 		else
   3198 			txrate = an->an_tx_mgtrate;
   3199 		/* NB: force all management frames to highest queue */
   3200 		if (ni->ni_flags & IEEE80211_NODE_QOS) {
   3201 			/* NB: force all management frames to highest queue */
   3202 			pri = WME_AC_VO;
   3203 		} else
   3204 			pri = WME_AC_BE;
   3205 		flags |= HAL_TXDESC_INTREQ;	/* force interrupt */
   3206 		break;
   3207 	case IEEE80211_FC0_TYPE_CTL:
   3208 		atype = HAL_PKT_TYPE_PSPOLL;	/* stop setting of duration */
   3209 		rix = 0;			/* XXX lowest rate */
   3210 		try0 = ATH_TXMAXTRY;
   3211 		if (shortPreamble)
   3212 			txrate = an->an_tx_mgtratesp;
   3213 		else
   3214 			txrate = an->an_tx_mgtrate;
   3215 		/* NB: force all ctl frames to highest queue */
   3216 		if (ni->ni_flags & IEEE80211_NODE_QOS) {
   3217 			/* NB: force all ctl frames to highest queue */
   3218 			pri = WME_AC_VO;
   3219 		} else
   3220 			pri = WME_AC_BE;
   3221 		flags |= HAL_TXDESC_INTREQ;	/* force interrupt */
   3222 		break;
   3223 	case IEEE80211_FC0_TYPE_DATA:
   3224 		atype = HAL_PKT_TYPE_NORMAL;		/* default */
   3225 		/*
   3226 		 * Data frames; consult the rate control module.
   3227 		 */
   3228 		ath_rate_findrate(sc, an, shortPreamble, pktlen,
   3229 			&rix, &try0, &txrate);
   3230 		sc->sc_txrate = txrate;			/* for LED blinking */
   3231 		/*
   3232 		 * Default all non-QoS traffic to the background queue.
   3233 		 */
   3234 		if (wh->i_fc[0] & IEEE80211_FC0_SUBTYPE_QOS) {
   3235 			pri = M_WME_GETAC(m0);
   3236 			if (cap->cap_wmeParams[pri].wmep_noackPolicy) {
   3237 				flags |= HAL_TXDESC_NOACK;
   3238 				sc->sc_stats.ast_tx_noack++;
   3239 			}
   3240 		} else
   3241 			pri = WME_AC_BE;
   3242 		break;
   3243 	default:
   3244 		if_printf(ifp, "bogus frame type 0x%x (%s)\n",
   3245 			wh->i_fc[0] & IEEE80211_FC0_TYPE_MASK, __func__);
   3246 		/* XXX statistic */
   3247 		m_freem(m0);
   3248 		return EIO;
   3249 	}
   3250 	txq = sc->sc_ac2q[pri];
   3251 
   3252 	/*
   3253 	 * When servicing one or more stations in power-save mode
   3254 	 * multicast frames must be buffered until after the beacon.
   3255 	 * We use the CAB queue for that.
   3256 	 */
   3257 	if (ismcast && ic->ic_ps_sta) {
   3258 		txq = sc->sc_cabq;
   3259 		/* XXX? more bit in 802.11 frame header */
   3260 	}
   3261 
   3262 	/*
   3263 	 * Calculate miscellaneous flags.
   3264 	 */
   3265 	if (ismcast) {
   3266 		flags |= HAL_TXDESC_NOACK;	/* no ack on broad/multicast */
   3267 		sc->sc_stats.ast_tx_noack++;
   3268 	} else if (pktlen > ic->ic_rtsthreshold) {
   3269 		flags |= HAL_TXDESC_RTSENA;	/* RTS based on frame length */
   3270 		cix = rt->info[rix].controlRate;
   3271 		sc->sc_stats.ast_tx_rts++;
   3272 	}
   3273 
   3274 	/*
   3275 	 * If 802.11g protection is enabled, determine whether
   3276 	 * to use RTS/CTS or just CTS.  Note that this is only
   3277 	 * done for OFDM unicast frames.
   3278 	 */
   3279 	if ((ic->ic_flags & IEEE80211_F_USEPROT) &&
   3280 	    rt->info[rix].phy == IEEE80211_T_OFDM &&
   3281 	    (flags & HAL_TXDESC_NOACK) == 0) {
   3282 		/* XXX fragments must use CCK rates w/ protection */
   3283 		if (ic->ic_protmode == IEEE80211_PROT_RTSCTS)
   3284 			flags |= HAL_TXDESC_RTSENA;
   3285 		else if (ic->ic_protmode == IEEE80211_PROT_CTSONLY)
   3286 			flags |= HAL_TXDESC_CTSENA;
   3287 		cix = rt->info[sc->sc_protrix].controlRate;
   3288 		sc->sc_stats.ast_tx_protect++;
   3289 	}
   3290 
   3291 	/*
   3292 	 * Calculate duration.  This logically belongs in the 802.11
   3293 	 * layer but it lacks sufficient information to calculate it.
   3294 	 */
   3295 	if ((flags & HAL_TXDESC_NOACK) == 0 &&
   3296 	    (wh->i_fc[0] & IEEE80211_FC0_TYPE_MASK) != IEEE80211_FC0_TYPE_CTL) {
   3297 		u_int16_t dur;
   3298 		/*
   3299 		 * XXX not right with fragmentation.
   3300 		 */
   3301 		if (shortPreamble)
   3302 			dur = rt->info[rix].spAckDuration;
   3303 		else
   3304 			dur = rt->info[rix].lpAckDuration;
   3305 		*(u_int16_t *)wh->i_dur = htole16(dur);
   3306 	}
   3307 
   3308 	/*
   3309 	 * Calculate RTS/CTS rate and duration if needed.
   3310 	 */
   3311 	ctsduration = 0;
   3312 	if (flags & (HAL_TXDESC_RTSENA|HAL_TXDESC_CTSENA)) {
   3313 		/*
   3314 		 * CTS transmit rate is derived from the transmit rate
   3315 		 * by looking in the h/w rate table.  We must also factor
   3316 		 * in whether or not a short preamble is to be used.
   3317 		 */
   3318 		/* NB: cix is set above where RTS/CTS is enabled */
   3319 		KASSERT(cix != 0xff, ("cix not setup"));
   3320 		ctsrate = rt->info[cix].rateCode;
   3321 		/*
   3322 		 * Compute the transmit duration based on the frame
   3323 		 * size and the size of an ACK frame.  We call into the
   3324 		 * HAL to do the computation since it depends on the
   3325 		 * characteristics of the actual PHY being used.
   3326 		 *
   3327 		 * NB: CTS is assumed the same size as an ACK so we can
   3328 		 *     use the precalculated ACK durations.
   3329 		 */
   3330 		if (shortPreamble) {
   3331 			ctsrate |= rt->info[cix].shortPreamble;
   3332 			if (flags & HAL_TXDESC_RTSENA)		/* SIFS + CTS */
   3333 				ctsduration += rt->info[cix].spAckDuration;
   3334 			ctsduration += ath_hal_computetxtime(ah,
   3335 				rt, pktlen, rix, AH_TRUE);
   3336 			if ((flags & HAL_TXDESC_NOACK) == 0)	/* SIFS + ACK */
   3337 				ctsduration += rt->info[cix].spAckDuration;
   3338 		} else {
   3339 			if (flags & HAL_TXDESC_RTSENA)		/* SIFS + CTS */
   3340 				ctsduration += rt->info[cix].lpAckDuration;
   3341 			ctsduration += ath_hal_computetxtime(ah,
   3342 				rt, pktlen, rix, AH_FALSE);
   3343 			if ((flags & HAL_TXDESC_NOACK) == 0)	/* SIFS + ACK */
   3344 				ctsduration += rt->info[cix].lpAckDuration;
   3345 		}
   3346 		/*
   3347 		 * Must disable multi-rate retry when using RTS/CTS.
   3348 		 */
   3349 		try0 = ATH_TXMAXTRY;
   3350 	} else
   3351 		ctsrate = 0;
   3352 
   3353 	if (IFF_DUMPPKTS(sc, ATH_DEBUG_XMIT))
   3354 		ieee80211_dump_pkt(mtod(m0, caddr_t), m0->m_len,
   3355 			sc->sc_hwmap[txrate].ieeerate, -1);
   3356 
   3357 	if (ic->ic_rawbpf)
   3358 		bpf_mtap(ic->ic_rawbpf, m0);
   3359 	if (sc->sc_drvbpf) {
   3360 		sc->sc_tx_th.wt_flags = sc->sc_hwmap[txrate].txflags;
   3361 		if (iswep)
   3362 			sc->sc_tx_th.wt_flags |= IEEE80211_RADIOTAP_F_WEP;
   3363 		sc->sc_tx_th.wt_rate = sc->sc_hwmap[txrate].ieeerate;
   3364 		sc->sc_tx_th.wt_txpower = ni->ni_txpower;
   3365 		sc->sc_tx_th.wt_antenna = sc->sc_txantenna;
   3366 
   3367 		bpf_mtap2(sc->sc_drvbpf,
   3368 			&sc->sc_tx_th, sc->sc_tx_th_len, m0);
   3369 	}
   3370 
   3371 	/*
   3372 	 * Determine if a tx interrupt should be generated for
   3373 	 * this descriptor.  We take a tx interrupt to reap
   3374 	 * descriptors when the h/w hits an EOL condition or
   3375 	 * when the descriptor is specifically marked to generate
   3376 	 * an interrupt.  We periodically mark descriptors in this
   3377 	 * way to insure timely replenishing of the supply needed
   3378 	 * for sending frames.  Defering interrupts reduces system
   3379 	 * load and potentially allows more concurrent work to be
   3380 	 * done but if done to aggressively can cause senders to
   3381 	 * backup.
   3382 	 *
   3383 	 * NB: use >= to deal with sc_txintrperiod changing
   3384 	 *     dynamically through sysctl.
   3385 	 */
   3386 	if (flags & HAL_TXDESC_INTREQ) {
   3387 		txq->axq_intrcnt = 0;
   3388 	} else if (++txq->axq_intrcnt >= sc->sc_txintrperiod) {
   3389 		flags |= HAL_TXDESC_INTREQ;
   3390 		txq->axq_intrcnt = 0;
   3391 	}
   3392 
   3393 	/*
   3394 	 * Formulate first tx descriptor with tx controls.
   3395 	 */
   3396 	/* XXX check return value? */
   3397 	ath_hal_setuptxdesc(ah, ds
   3398 		, pktlen		/* packet length */
   3399 		, hdrlen		/* header length */
   3400 		, atype			/* Atheros packet type */
   3401 		, ni->ni_txpower	/* txpower */
   3402 		, txrate, try0		/* series 0 rate/tries */
   3403 		, keyix			/* key cache index */
   3404 		, sc->sc_txantenna	/* antenna mode */
   3405 		, flags			/* flags */
   3406 		, ctsrate		/* rts/cts rate */
   3407 		, ctsduration		/* rts/cts duration */
   3408 	);
   3409 	/*
   3410 	 * Setup the multi-rate retry state only when we're
   3411 	 * going to use it.  This assumes ath_hal_setuptxdesc
   3412 	 * initializes the descriptors (so we don't have to)
   3413 	 * when the hardware supports multi-rate retry and
   3414 	 * we don't use it.
   3415 	 */
   3416 	if (try0 != ATH_TXMAXTRY)
   3417 		ath_rate_setupxtxdesc(sc, an, ds, shortPreamble, rix);
   3418 
   3419 	/*
   3420 	 * Fillin the remainder of the descriptor info.
   3421 	 */
   3422 	ds0 = ds;
   3423 	for (i = 0; i < bf->bf_nseg; i++, ds++) {
   3424 		ds->ds_data = bf->bf_segs[i].ds_addr;
   3425 		if (i == bf->bf_nseg - 1)
   3426 			ds->ds_link = 0;
   3427 		else
   3428 			ds->ds_link = bf->bf_daddr + sizeof(*ds) * (i + 1);
   3429 		ath_hal_filltxdesc(ah, ds
   3430 			, bf->bf_segs[i].ds_len	/* segment length */
   3431 			, i == 0		/* first segment */
   3432 			, i == bf->bf_nseg - 1	/* last segment */
   3433 			, ds0			/* first descriptor */
   3434 		);
   3435 		DPRINTF(sc, ATH_DEBUG_XMIT,
   3436 			"%s: %d: %08x %08x %08x %08x %08x %08x\n",
   3437 			__func__, i, ds->ds_link, ds->ds_data,
   3438 			ds->ds_ctl0, ds->ds_ctl1, ds->ds_hw[0], ds->ds_hw[1]);
   3439 	}
   3440 	/*
   3441 	 * Insert the frame on the outbound list and
   3442 	 * pass it on to the hardware.
   3443 	 */
   3444 	ATH_TXQ_LOCK(txq);
   3445 	if (flags & (HAL_TXDESC_RTSENA | HAL_TXDESC_CTSENA)) {
   3446 		u_int32_t txopLimit = IEEE80211_TXOP_TO_US(
   3447 			cap->cap_wmeParams[pri].wmep_txopLimit);
   3448 		/*
   3449 		 * When bursting, potentially extend the CTS duration
   3450 		 * of a previously queued frame to cover this frame
   3451 		 * and not exceed the txopLimit.  If that can be done
   3452 		 * then disable RTS/CTS on this frame since it's now
   3453 		 * covered (burst extension).  Otherwise we must terminate
   3454 		 * the burst before this frame goes out so as not to
   3455 		 * violate the WME parameters.  All this is complicated
   3456 		 * as we need to update the state of packets on the
   3457 		 * (live) hardware queue.  The logic is buried in the hal
   3458 		 * because it's highly chip-specific.
   3459 		 */
   3460 		if (txopLimit != 0) {
   3461 			sc->sc_stats.ast_tx_ctsburst++;
   3462 			if (updateCTSForBursting(ah, ds0, txq) == 0) {
   3463 				/*
   3464 				 * This frame was not covered by RTS/CTS from
   3465 				 * the previous frame in the burst; update the
   3466 				 * descriptor pointers so this frame is now
   3467 				 * treated as the last frame for extending a
   3468 				 * burst.
   3469 				 */
   3470 				txq->axq_lastdsWithCTS = ds0;
   3471 				/* set gating Desc to final desc */
   3472 				txq->axq_gatingds =
   3473 					(struct ath_desc *)txq->axq_link;
   3474 			} else
   3475 				sc->sc_stats.ast_tx_ctsext++;
   3476 		}
   3477 	}
   3478 	ATH_TXQ_INSERT_TAIL(txq, bf, bf_list);
   3479 	if (txq->axq_link == NULL) {
   3480 		ath_hal_puttxbuf(ah, txq->axq_qnum, bf->bf_daddr);
   3481 		DPRINTF(sc, ATH_DEBUG_XMIT,
   3482 			"%s: TXDP[%u] = %p (%p) depth %d\n", __func__,
   3483 			txq->axq_qnum, (caddr_t)bf->bf_daddr, bf->bf_desc,
   3484 			txq->axq_depth);
   3485 	} else {
   3486 		*txq->axq_link = bf->bf_daddr;
   3487 		DPRINTF(sc, ATH_DEBUG_XMIT,
   3488 			"%s: link[%u](%p)=%p (%p) depth %d\n", __func__,
   3489 			txq->axq_qnum, txq->axq_link,
   3490 			(caddr_t)bf->bf_daddr, bf->bf_desc, txq->axq_depth);
   3491 	}
   3492 	txq->axq_link = &bf->bf_desc[bf->bf_nseg - 1].ds_link;
   3493 	/*
   3494 	 * The CAB queue is started from the SWBA handler since
   3495 	 * frames only go out on DTIM and to avoid possible races.
   3496 	 */
   3497 	if (txq != sc->sc_cabq)
   3498 		ath_hal_txstart(ah, txq->axq_qnum);
   3499 	ATH_TXQ_UNLOCK(txq);
   3500 
   3501 	return 0;
   3502 #undef updateCTSForBursting
   3503 #undef CTS_DURATION
   3504 }
   3505 
   3506 /*
   3507  * Process completed xmit descriptors from the specified queue.
   3508  */
   3509 static void
   3510 ath_tx_processq(struct ath_softc *sc, struct ath_txq *txq)
   3511 {
   3512 	struct ath_hal *ah = sc->sc_ah;
   3513 	struct ieee80211com *ic = &sc->sc_ic;
   3514 	struct ath_buf *bf;
   3515 	struct ath_desc *ds, *ds0;
   3516 	struct ieee80211_node *ni;
   3517 	struct ath_node *an;
   3518 	int sr, lr, pri;
   3519 	HAL_STATUS status;
   3520 
   3521 	DPRINTF(sc, ATH_DEBUG_TX_PROC, "%s: tx queue %u head %p link %p\n",
   3522 		__func__, txq->axq_qnum,
   3523 		(caddr_t)(uintptr_t) ath_hal_gettxbuf(sc->sc_ah, txq->axq_qnum),
   3524 		txq->axq_link);
   3525 	for (;;) {
   3526 		ATH_TXQ_LOCK(txq);
   3527 		txq->axq_intrcnt = 0;	/* reset periodic desc intr count */
   3528 		bf = STAILQ_FIRST(&txq->axq_q);
   3529 		if (bf == NULL) {
   3530 			txq->axq_link = NULL;
   3531 			ATH_TXQ_UNLOCK(txq);
   3532 			break;
   3533 		}
   3534 		ds0 = &bf->bf_desc[0];
   3535 		ds = &bf->bf_desc[bf->bf_nseg - 1];
   3536 		status = ath_hal_txprocdesc(ah, ds);
   3537 #ifdef AR_DEBUG
   3538 		if (sc->sc_debug & ATH_DEBUG_XMIT_DESC)
   3539 			ath_printtxbuf(bf, status == HAL_OK);
   3540 #endif
   3541 		if (status == HAL_EINPROGRESS) {
   3542 			ATH_TXQ_UNLOCK(txq);
   3543 			break;
   3544 		}
   3545 		if (ds0 == txq->axq_lastdsWithCTS)
   3546 			txq->axq_lastdsWithCTS = NULL;
   3547 		if (ds == txq->axq_gatingds)
   3548 			txq->axq_gatingds = NULL;
   3549 		ATH_TXQ_REMOVE_HEAD(txq, bf_list);
   3550 		ATH_TXQ_UNLOCK(txq);
   3551 
   3552 		ni = bf->bf_node;
   3553 		if (ni != NULL) {
   3554 			an = ATH_NODE(ni);
   3555 			if (ds->ds_txstat.ts_status == 0) {
   3556 				u_int8_t txant = ds->ds_txstat.ts_antenna;
   3557 				sc->sc_stats.ast_ant_tx[txant]++;
   3558 				sc->sc_ant_tx[txant]++;
   3559 				if (ds->ds_txstat.ts_rate & HAL_TXSTAT_ALTRATE)
   3560 					sc->sc_stats.ast_tx_altrate++;
   3561 				sc->sc_stats.ast_tx_rssi =
   3562 					ds->ds_txstat.ts_rssi;
   3563 				ATH_RSSI_LPF(an->an_halstats.ns_avgtxrssi,
   3564 					ds->ds_txstat.ts_rssi);
   3565 				pri = M_WME_GETAC(bf->bf_m);
   3566 				if (pri >= WME_AC_VO)
   3567 					ic->ic_wme.wme_hipri_traffic++;
   3568 				ni->ni_inact = ni->ni_inact_reload;
   3569 			} else {
   3570 				if (ds->ds_txstat.ts_status & HAL_TXERR_XRETRY)
   3571 					sc->sc_stats.ast_tx_xretries++;
   3572 				if (ds->ds_txstat.ts_status & HAL_TXERR_FIFO)
   3573 					sc->sc_stats.ast_tx_fifoerr++;
   3574 				if (ds->ds_txstat.ts_status & HAL_TXERR_FILT)
   3575 					sc->sc_stats.ast_tx_filtered++;
   3576 			}
   3577 			sr = ds->ds_txstat.ts_shortretry;
   3578 			lr = ds->ds_txstat.ts_longretry;
   3579 			sc->sc_stats.ast_tx_shortretry += sr;
   3580 			sc->sc_stats.ast_tx_longretry += lr;
   3581 			/*
   3582 			 * Hand the descriptor to the rate control algorithm.
   3583 			 */
   3584 			ath_rate_tx_complete(sc, an, ds, ds0);
   3585 			/*
   3586 			 * Reclaim reference to node.
   3587 			 *
   3588 			 * NB: the node may be reclaimed here if, for example
   3589 			 *     this is a DEAUTH message that was sent and the
   3590 			 *     node was timed out due to inactivity.
   3591 			 */
   3592 			ieee80211_free_node(ni);
   3593 		}
   3594 		bus_dmamap_sync(sc->sc_dmat, bf->bf_dmamap,
   3595 		    BUS_DMASYNC_POSTWRITE);
   3596 		bus_dmamap_unload(sc->sc_dmat, bf->bf_dmamap);
   3597 		m_freem(bf->bf_m);
   3598 		bf->bf_m = NULL;
   3599 		bf->bf_node = NULL;
   3600 
   3601 		ATH_TXBUF_LOCK(sc);
   3602 		STAILQ_INSERT_TAIL(&sc->sc_txbuf, bf, bf_list);
   3603 		ATH_TXBUF_UNLOCK(sc);
   3604 	}
   3605 }
   3606 
   3607 /*
   3608  * Deferred processing of transmit interrupt; special-cased
   3609  * for a single hardware transmit queue (e.g. 5210 and 5211).
   3610  */
   3611 static void
   3612 ath_tx_proc_q0(void *arg, int npending)
   3613 {
   3614 	struct ath_softc *sc = arg;
   3615 	struct ifnet *ifp = &sc->sc_if;
   3616 
   3617 	ath_tx_processq(sc, &sc->sc_txq[0]);
   3618 	ath_tx_processq(sc, sc->sc_cabq);
   3619 	ifp->if_flags &= ~IFF_OACTIVE;
   3620 	sc->sc_tx_timer = 0;
   3621 
   3622 	if (sc->sc_softled)
   3623 		ath_led_event(sc, ATH_LED_TX);
   3624 
   3625 	ath_start(ifp);
   3626 }
   3627 
   3628 /*
   3629  * Deferred processing of transmit interrupt; special-cased
   3630  * for four hardware queues, 0-3 (e.g. 5212 w/ WME support).
   3631  */
   3632 static void
   3633 ath_tx_proc_q0123(void *arg, int npending)
   3634 {
   3635 	struct ath_softc *sc = arg;
   3636 	struct ifnet *ifp = &sc->sc_if;
   3637 
   3638 	/*
   3639 	 * Process each active queue.
   3640 	 */
   3641 	ath_tx_processq(sc, &sc->sc_txq[0]);
   3642 	ath_tx_processq(sc, &sc->sc_txq[1]);
   3643 	ath_tx_processq(sc, &sc->sc_txq[2]);
   3644 	ath_tx_processq(sc, &sc->sc_txq[3]);
   3645 	ath_tx_processq(sc, sc->sc_cabq);
   3646 
   3647 	ifp->if_flags &= ~IFF_OACTIVE;
   3648 	sc->sc_tx_timer = 0;
   3649 
   3650 	if (sc->sc_softled)
   3651 		ath_led_event(sc, ATH_LED_TX);
   3652 
   3653 	ath_start(ifp);
   3654 }
   3655 
   3656 /*
   3657  * Deferred processing of transmit interrupt.
   3658  */
   3659 static void
   3660 ath_tx_proc(void *arg, int npending)
   3661 {
   3662 	struct ath_softc *sc = arg;
   3663 	struct ifnet *ifp = &sc->sc_if;
   3664 	int i;
   3665 
   3666 	/*
   3667 	 * Process each active queue.
   3668 	 */
   3669 	/* XXX faster to read ISR_S0_S and ISR_S1_S to determine q's? */
   3670 	for (i = 0; i < HAL_NUM_TX_QUEUES; i++)
   3671 		if (ATH_TXQ_SETUP(sc, i))
   3672 			ath_tx_processq(sc, &sc->sc_txq[i]);
   3673 
   3674 	ifp->if_flags &= ~IFF_OACTIVE;
   3675 	sc->sc_tx_timer = 0;
   3676 
   3677 	if (sc->sc_softled)
   3678 		ath_led_event(sc, ATH_LED_TX);
   3679 
   3680 	ath_start(ifp);
   3681 }
   3682 
   3683 static void
   3684 ath_tx_draintxq(struct ath_softc *sc, struct ath_txq *txq)
   3685 {
   3686 	struct ath_hal *ah = sc->sc_ah;
   3687 	struct ieee80211_node *ni;
   3688 	struct ath_buf *bf;
   3689 
   3690 	/*
   3691 	 * NB: this assumes output has been stopped and
   3692 	 *     we do not need to block ath_tx_tasklet
   3693 	 */
   3694 	for (;;) {
   3695 		ATH_TXQ_LOCK(txq);
   3696 		bf = STAILQ_FIRST(&txq->axq_q);
   3697 		if (bf == NULL) {
   3698 			txq->axq_link = NULL;
   3699 			ATH_TXQ_UNLOCK(txq);
   3700 			break;
   3701 		}
   3702 		ATH_TXQ_REMOVE_HEAD(txq, bf_list);
   3703 		ATH_TXQ_UNLOCK(txq);
   3704 #ifdef AR_DEBUG
   3705 		if (sc->sc_debug & ATH_DEBUG_RESET)
   3706 			ath_printtxbuf(bf,
   3707 				ath_hal_txprocdesc(ah, bf->bf_desc) == HAL_OK);
   3708 #endif /* AR_DEBUG */
   3709 		bus_dmamap_unload(sc->sc_dmat, bf->bf_dmamap);
   3710 		m_freem(bf->bf_m);
   3711 		bf->bf_m = NULL;
   3712 		ni = bf->bf_node;
   3713 		bf->bf_node = NULL;
   3714 		if (ni != NULL) {
   3715 			/*
   3716 			 * Reclaim node reference.
   3717 			 */
   3718 			ieee80211_free_node(ni);
   3719 		}
   3720 		ATH_TXBUF_LOCK(sc);
   3721 		STAILQ_INSERT_TAIL(&sc->sc_txbuf, bf, bf_list);
   3722 		ATH_TXBUF_UNLOCK(sc);
   3723 	}
   3724 }
   3725 
   3726 static void
   3727 ath_tx_stopdma(struct ath_softc *sc, struct ath_txq *txq)
   3728 {
   3729 	struct ath_hal *ah = sc->sc_ah;
   3730 
   3731 	(void) ath_hal_stoptxdma(ah, txq->axq_qnum);
   3732 	DPRINTF(sc, ATH_DEBUG_RESET, "%s: tx queue [%u] %p, link %p\n",
   3733 	    __func__, txq->axq_qnum,
   3734 	    (caddr_t)(uintptr_t) ath_hal_gettxbuf(ah, txq->axq_qnum),
   3735 	    txq->axq_link);
   3736 }
   3737 
   3738 /*
   3739  * Drain the transmit queues and reclaim resources.
   3740  */
   3741 static void
   3742 ath_draintxq(struct ath_softc *sc)
   3743 {
   3744 	struct ath_hal *ah = sc->sc_ah;
   3745 	struct ifnet *ifp = &sc->sc_if;
   3746 	int i;
   3747 
   3748 	/* XXX return value */
   3749 	if (!sc->sc_invalid) {
   3750 		/* don't touch the hardware if marked invalid */
   3751 		(void) ath_hal_stoptxdma(ah, sc->sc_bhalq);
   3752 		DPRINTF(sc, ATH_DEBUG_RESET,
   3753 		    "%s: beacon queue %p\n", __func__,
   3754 		    (caddr_t)(uintptr_t) ath_hal_gettxbuf(ah, sc->sc_bhalq));
   3755 		for (i = 0; i < HAL_NUM_TX_QUEUES; i++)
   3756 			if (ATH_TXQ_SETUP(sc, i))
   3757 				ath_tx_stopdma(sc, &sc->sc_txq[i]);
   3758 	}
   3759 	for (i = 0; i < HAL_NUM_TX_QUEUES; i++)
   3760 		if (ATH_TXQ_SETUP(sc, i))
   3761 			ath_tx_draintxq(sc, &sc->sc_txq[i]);
   3762 	ifp->if_flags &= ~IFF_OACTIVE;
   3763 	sc->sc_tx_timer = 0;
   3764 }
   3765 
   3766 /*
   3767  * Disable the receive h/w in preparation for a reset.
   3768  */
   3769 static void
   3770 ath_stoprecv(struct ath_softc *sc)
   3771 {
   3772 #define	PA2DESC(_sc, _pa) \
   3773 	((struct ath_desc *)((caddr_t)(_sc)->sc_rxdma.dd_desc + \
   3774 		((_pa) - (_sc)->sc_rxdma.dd_desc_paddr)))
   3775 	struct ath_hal *ah = sc->sc_ah;
   3776 
   3777 	ath_hal_stoppcurecv(ah);	/* disable PCU */
   3778 	ath_hal_setrxfilter(ah, 0);	/* clear recv filter */
   3779 	ath_hal_stopdmarecv(ah);	/* disable DMA engine */
   3780 	DELAY(3000);			/* 3ms is long enough for 1 frame */
   3781 #ifdef AR_DEBUG
   3782 	if (sc->sc_debug & (ATH_DEBUG_RESET | ATH_DEBUG_FATAL)) {
   3783 		struct ath_buf *bf;
   3784 
   3785 		printf("%s: rx queue %p, link %p\n", __func__,
   3786 			(caddr_t)(uintptr_t) ath_hal_getrxbuf(ah), sc->sc_rxlink);
   3787 		STAILQ_FOREACH(bf, &sc->sc_rxbuf, bf_list) {
   3788 			struct ath_desc *ds = bf->bf_desc;
   3789 			HAL_STATUS status = ath_hal_rxprocdesc(ah, ds,
   3790 				bf->bf_daddr, PA2DESC(sc, ds->ds_link));
   3791 			if (status == HAL_OK || (sc->sc_debug & ATH_DEBUG_FATAL))
   3792 				ath_printrxbuf(bf, status == HAL_OK);
   3793 		}
   3794 	}
   3795 #endif
   3796 	sc->sc_rxlink = NULL;		/* just in case */
   3797 #undef PA2DESC
   3798 }
   3799 
   3800 /*
   3801  * Enable the receive h/w following a reset.
   3802  */
   3803 static int
   3804 ath_startrecv(struct ath_softc *sc)
   3805 {
   3806 	struct ath_hal *ah = sc->sc_ah;
   3807 	struct ath_buf *bf;
   3808 
   3809 	sc->sc_rxlink = NULL;
   3810 	STAILQ_FOREACH(bf, &sc->sc_rxbuf, bf_list) {
   3811 		int error = ath_rxbuf_init(sc, bf);
   3812 		if (error != 0) {
   3813 			DPRINTF(sc, ATH_DEBUG_RECV,
   3814 				"%s: ath_rxbuf_init failed %d\n",
   3815 				__func__, error);
   3816 			return error;
   3817 		}
   3818 	}
   3819 
   3820 	bf = STAILQ_FIRST(&sc->sc_rxbuf);
   3821 	ath_hal_putrxbuf(ah, bf->bf_daddr);
   3822 	ath_hal_rxena(ah);		/* enable recv descriptors */
   3823 	ath_mode_init(sc);		/* set filters, etc. */
   3824 	ath_hal_startpcurecv(ah);	/* re-enable PCU/DMA engine */
   3825 	return 0;
   3826 }
   3827 
   3828 /*
   3829  * Update internal state after a channel change.
   3830  */
   3831 static void
   3832 ath_chan_change(struct ath_softc *sc, struct ieee80211_channel *chan)
   3833 {
   3834 	struct ieee80211com *ic = &sc->sc_ic;
   3835 	enum ieee80211_phymode mode;
   3836 	u_int16_t flags;
   3837 
   3838 	/*
   3839 	 * Change channels and update the h/w rate map
   3840 	 * if we're switching; e.g. 11a to 11b/g.
   3841 	 */
   3842 	mode = ieee80211_chan2mode(ic, chan);
   3843 	if (mode != sc->sc_curmode)
   3844 		ath_setcurmode(sc, mode);
   3845 	/*
   3846 	 * Update BPF state.  NB: ethereal et. al. don't handle
   3847 	 * merged flags well so pick a unique mode for their use.
   3848 	 */
   3849 	if (IEEE80211_IS_CHAN_A(chan))
   3850 		flags = IEEE80211_CHAN_A;
   3851 	/* XXX 11g schizophrenia */
   3852 	else if (IEEE80211_IS_CHAN_G(chan) ||
   3853 	    IEEE80211_IS_CHAN_PUREG(chan))
   3854 		flags = IEEE80211_CHAN_G;
   3855 	else
   3856 		flags = IEEE80211_CHAN_B;
   3857 	if (IEEE80211_IS_CHAN_T(chan))
   3858 		flags |= IEEE80211_CHAN_TURBO;
   3859 	sc->sc_tx_th.wt_chan_freq = sc->sc_rx_th.wr_chan_freq =
   3860 		htole16(chan->ic_freq);
   3861 	sc->sc_tx_th.wt_chan_flags = sc->sc_rx_th.wr_chan_flags =
   3862 		htole16(flags);
   3863 }
   3864 
   3865 /*
   3866  * Set/change channels.  If the channel is really being changed,
   3867  * it's done by reseting the chip.  To accomplish this we must
   3868  * first cleanup any pending DMA, then restart stuff after a la
   3869  * ath_init.
   3870  */
   3871 static int
   3872 ath_chan_set(struct ath_softc *sc, struct ieee80211_channel *chan)
   3873 {
   3874 	struct ath_hal *ah = sc->sc_ah;
   3875 	struct ieee80211com *ic = &sc->sc_ic;
   3876 	HAL_CHANNEL hchan;
   3877 
   3878 	/*
   3879 	 * Convert to a HAL channel description with
   3880 	 * the flags constrained to reflect the current
   3881 	 * operating mode.
   3882 	 */
   3883 	hchan.channel = chan->ic_freq;
   3884 	hchan.channelFlags = ath_chan2flags(ic, chan);
   3885 
   3886 	DPRINTF(sc, ATH_DEBUG_RESET, "%s: %u (%u MHz) -> %u (%u MHz)\n",
   3887 	    __func__,
   3888 	    ath_hal_mhz2ieee(sc->sc_curchan.channel,
   3889 		sc->sc_curchan.channelFlags),
   3890 	    	sc->sc_curchan.channel,
   3891 	    ath_hal_mhz2ieee(hchan.channel, hchan.channelFlags), hchan.channel);
   3892 	if (hchan.channel != sc->sc_curchan.channel ||
   3893 	    hchan.channelFlags != sc->sc_curchan.channelFlags) {
   3894 		HAL_STATUS status;
   3895 
   3896 		/*
   3897 		 * To switch channels clear any pending DMA operations;
   3898 		 * wait long enough for the RX fifo to drain, reset the
   3899 		 * hardware at the new frequency, and then re-enable
   3900 		 * the relevant bits of the h/w.
   3901 		 */
   3902 		ath_hal_intrset(ah, 0);		/* disable interrupts */
   3903 		ath_draintxq(sc);		/* clear pending tx frames */
   3904 		ath_stoprecv(sc);		/* turn off frame recv */
   3905 		if (!ath_hal_reset(ah, ic->ic_opmode, &hchan, AH_TRUE, &status)) {
   3906 			if_printf(ic->ic_ifp, "ath_chan_set: unable to reset "
   3907 				"channel %u (%u Mhz)\n",
   3908 				ieee80211_chan2ieee(ic, chan), chan->ic_freq);
   3909 			return EIO;
   3910 		}
   3911 		sc->sc_curchan = hchan;
   3912 		ath_update_txpow(sc);		/* update tx power state */
   3913 
   3914 		/*
   3915 		 * Re-enable rx framework.
   3916 		 */
   3917 		if (ath_startrecv(sc) != 0) {
   3918 			if_printf(ic->ic_ifp,
   3919 				"ath_chan_set: unable to restart recv logic\n");
   3920 			return EIO;
   3921 		}
   3922 
   3923 		/*
   3924 		 * Change channels and update the h/w rate map
   3925 		 * if we're switching; e.g. 11a to 11b/g.
   3926 		 */
   3927 		ic->ic_ibss_chan = chan;
   3928 		ath_chan_change(sc, chan);
   3929 
   3930 		/*
   3931 		 * Re-enable interrupts.
   3932 		 */
   3933 		ath_hal_intrset(ah, sc->sc_imask);
   3934 	}
   3935 	return 0;
   3936 }
   3937 
   3938 static void
   3939 ath_next_scan(void *arg)
   3940 {
   3941 	struct ath_softc *sc = arg;
   3942 	struct ieee80211com *ic = &sc->sc_ic;
   3943 
   3944 	if (ic->ic_state == IEEE80211_S_SCAN)
   3945 		ieee80211_next_scan(ic);
   3946 }
   3947 
   3948 /*
   3949  * Periodically recalibrate the PHY to account
   3950  * for temperature/environment changes.
   3951  */
   3952 static void
   3953 ath_calibrate(void *arg)
   3954 {
   3955 	struct ath_softc *sc = arg;
   3956 	struct ath_hal *ah = sc->sc_ah;
   3957 
   3958 	sc->sc_stats.ast_per_cal++;
   3959 
   3960 	DPRINTF(sc, ATH_DEBUG_CALIBRATE, "%s: channel %u/%x\n",
   3961 		__func__, sc->sc_curchan.channel, sc->sc_curchan.channelFlags);
   3962 
   3963 	if (ath_hal_getrfgain(ah) == HAL_RFGAIN_NEED_CHANGE) {
   3964 		/*
   3965 		 * Rfgain is out of bounds, reset the chip
   3966 		 * to load new gain values.
   3967 		 */
   3968 		sc->sc_stats.ast_per_rfgain++;
   3969 		ath_reset(&sc->sc_if);
   3970 	}
   3971 	if (!ath_hal_calibrate(ah, &sc->sc_curchan)) {
   3972 		DPRINTF(sc, ATH_DEBUG_ANY,
   3973 			"%s: calibration of channel %u failed\n",
   3974 			__func__, sc->sc_curchan.channel);
   3975 		sc->sc_stats.ast_per_calfail++;
   3976 	}
   3977 	callout_reset(&sc->sc_cal_ch, ath_calinterval * hz, ath_calibrate, sc);
   3978 }
   3979 
   3980 static int
   3981 ath_newstate(struct ieee80211com *ic, enum ieee80211_state nstate, int arg)
   3982 {
   3983 	struct ifnet *ifp = ic->ic_ifp;
   3984 	struct ath_softc *sc = ifp->if_softc;
   3985 	struct ath_hal *ah = sc->sc_ah;
   3986 	struct ieee80211_node *ni;
   3987 	int i, error;
   3988 	const u_int8_t *bssid;
   3989 	u_int32_t rfilt;
   3990 	static const HAL_LED_STATE leds[] = {
   3991 	    HAL_LED_INIT,	/* IEEE80211_S_INIT */
   3992 	    HAL_LED_SCAN,	/* IEEE80211_S_SCAN */
   3993 	    HAL_LED_AUTH,	/* IEEE80211_S_AUTH */
   3994 	    HAL_LED_ASSOC, 	/* IEEE80211_S_ASSOC */
   3995 	    HAL_LED_RUN, 	/* IEEE80211_S_RUN */
   3996 	};
   3997 
   3998 	DPRINTF(sc, ATH_DEBUG_STATE, "%s: %s -> %s\n", __func__,
   3999 		ieee80211_state_name[ic->ic_state],
   4000 		ieee80211_state_name[nstate]);
   4001 
   4002 	callout_stop(&sc->sc_scan_ch);
   4003 	callout_stop(&sc->sc_cal_ch);
   4004 	ath_hal_setledstate(ah, leds[nstate]);	/* set LED */
   4005 
   4006 	if (nstate == IEEE80211_S_INIT) {
   4007 		sc->sc_imask &= ~(HAL_INT_SWBA | HAL_INT_BMISS);
   4008 		/*
   4009 		 * NB: disable interrupts so we don't rx frames.
   4010 		 */
   4011 		ath_hal_intrset(ah, sc->sc_imask &~ ~HAL_INT_GLOBAL);
   4012 		/*
   4013 		 * Notify the rate control algorithm.
   4014 		 */
   4015 		ath_rate_newstate(sc, nstate);
   4016 		goto done;
   4017 	}
   4018 	ni = ic->ic_bss;
   4019 	error = ath_chan_set(sc, ni->ni_chan);
   4020 	if (error != 0)
   4021 		goto bad;
   4022 	rfilt = ath_calcrxfilter(sc, nstate);
   4023 	if (nstate == IEEE80211_S_SCAN)
   4024 		bssid = ifp->if_broadcastaddr;
   4025 	else
   4026 		bssid = ni->ni_bssid;
   4027 	ath_hal_setrxfilter(ah, rfilt);
   4028 	DPRINTF(sc, ATH_DEBUG_STATE, "%s: RX filter 0x%x bssid %s\n",
   4029 		 __func__, rfilt, ether_sprintf(bssid));
   4030 
   4031 	if (nstate == IEEE80211_S_RUN && ic->ic_opmode == IEEE80211_M_STA)
   4032 		ath_hal_setassocid(ah, bssid, ni->ni_associd);
   4033 	else
   4034 		ath_hal_setassocid(ah, bssid, 0);
   4035 	if (ic->ic_flags & IEEE80211_F_PRIVACY) {
   4036 		for (i = 0; i < IEEE80211_WEP_NKID; i++)
   4037 			if (ath_hal_keyisvalid(ah, i))
   4038 				ath_hal_keysetmac(ah, i, bssid);
   4039 	}
   4040 
   4041 	/*
   4042 	 * Notify the rate control algorithm so rates
   4043 	 * are setup should ath_beacon_alloc be called.
   4044 	 */
   4045 	ath_rate_newstate(sc, nstate);
   4046 
   4047 	if (ic->ic_opmode == IEEE80211_M_MONITOR) {
   4048 		/* nothing to do */;
   4049 	} else if (nstate == IEEE80211_S_RUN) {
   4050 		DPRINTF(sc, ATH_DEBUG_STATE,
   4051 			"%s(RUN): ic_flags=0x%08x iv=%d bssid=%s "
   4052 			"capinfo=0x%04x chan=%d\n"
   4053 			 , __func__
   4054 			 , ic->ic_flags
   4055 			 , ni->ni_intval
   4056 			 , ether_sprintf(ni->ni_bssid)
   4057 			 , ni->ni_capinfo
   4058 			 , ieee80211_chan2ieee(ic, ni->ni_chan));
   4059 
   4060 		/*
   4061 		 * Allocate and setup the beacon frame for AP or adhoc mode.
   4062 		 */
   4063 		if (ic->ic_opmode == IEEE80211_M_HOSTAP ||
   4064 		    ic->ic_opmode == IEEE80211_M_IBSS) {
   4065 			/*
   4066 			 * Stop any previous beacon DMA.  This may be
   4067 			 * necessary, for example, when an ibss merge
   4068 			 * causes reconfiguration; there will be a state
   4069 			 * transition from RUN->RUN that means we may
   4070 			 * be called with beacon transmission active.
   4071 			 */
   4072 			ath_hal_stoptxdma(ah, sc->sc_bhalq);
   4073 			ath_beacon_free(sc);
   4074 			error = ath_beacon_alloc(sc, ni);
   4075 			if (error != 0)
   4076 				goto bad;
   4077 		}
   4078 
   4079 		/*
   4080 		 * Configure the beacon and sleep timers.
   4081 		 */
   4082 		ath_beacon_config(sc);
   4083 	} else {
   4084 		ath_hal_intrset(ah,
   4085 			sc->sc_imask &~ (HAL_INT_SWBA | HAL_INT_BMISS));
   4086 		sc->sc_imask &= ~(HAL_INT_SWBA | HAL_INT_BMISS);
   4087 	}
   4088 done:
   4089 	/*
   4090 	 * Invoke the parent method to complete the work.
   4091 	 */
   4092 	error = sc->sc_newstate(ic, nstate, arg);
   4093 	/*
   4094 	 * Finally, start any timers.
   4095 	 */
   4096 	if (nstate == IEEE80211_S_RUN) {
   4097 		/* start periodic recalibration timer */
   4098 		callout_reset(&sc->sc_cal_ch, ath_calinterval * hz,
   4099 			ath_calibrate, sc);
   4100 	} else if (nstate == IEEE80211_S_SCAN) {
   4101 		/* start ap/neighbor scan timer */
   4102 		callout_reset(&sc->sc_scan_ch, (ath_dwelltime * hz) / 1000,
   4103 			ath_next_scan, sc);
   4104 	}
   4105 bad:
   4106 	return error;
   4107 }
   4108 
   4109 /*
   4110  * Setup driver-specific state for a newly associated node.
   4111  * Note that we're called also on a re-associate, the isnew
   4112  * param tells us if this is the first time or not.
   4113  */
   4114 static void
   4115 ath_newassoc(struct ieee80211com *ic, struct ieee80211_node *ni, int isnew)
   4116 {
   4117 	struct ath_softc *sc = ic->ic_ifp->if_softc;
   4118 
   4119 	ath_rate_newassoc(sc, ATH_NODE(ni), isnew);
   4120 }
   4121 
   4122 static int
   4123 ath_getchannels(struct ath_softc *sc, u_int cc,
   4124 	HAL_BOOL outdoor, HAL_BOOL xchanmode)
   4125 {
   4126 	struct ieee80211com *ic = &sc->sc_ic;
   4127 	struct ifnet *ifp = &sc->sc_if;
   4128 	struct ath_hal *ah = sc->sc_ah;
   4129 	HAL_CHANNEL *chans;
   4130 	int i, ix, nchan;
   4131 
   4132 	chans = malloc(IEEE80211_CHAN_MAX * sizeof(HAL_CHANNEL),
   4133 			M_TEMP, M_NOWAIT);
   4134 	if (chans == NULL) {
   4135 		if_printf(ifp, "unable to allocate channel table\n");
   4136 		return ENOMEM;
   4137 	}
   4138 	if (!ath_hal_init_channels(ah, chans, IEEE80211_CHAN_MAX, &nchan,
   4139 	    cc, HAL_MODE_ALL, outdoor, xchanmode)) {
   4140 		u_int32_t rd;
   4141 
   4142 		ath_hal_getregdomain(ah, &rd);
   4143 		if_printf(ifp, "unable to collect channel list from hal; "
   4144 			"regdomain likely %u country code %u\n", rd, cc);
   4145 		free(chans, M_TEMP);
   4146 		return EINVAL;
   4147 	}
   4148 
   4149 	/*
   4150 	 * Convert HAL channels to ieee80211 ones and insert
   4151 	 * them in the table according to their channel number.
   4152 	 */
   4153 	for (i = 0; i < nchan; i++) {
   4154 		HAL_CHANNEL *c = &chans[i];
   4155 		ix = ath_hal_mhz2ieee(c->channel, c->channelFlags);
   4156 		if (ix > IEEE80211_CHAN_MAX) {
   4157 			if_printf(ifp, "bad hal channel %u (%u/%x) ignored\n",
   4158 				ix, c->channel, c->channelFlags);
   4159 			continue;
   4160 		}
   4161 		/* NB: flags are known to be compatible */
   4162 		if (ic->ic_channels[ix].ic_freq == 0) {
   4163 			ic->ic_channels[ix].ic_freq = c->channel;
   4164 			ic->ic_channels[ix].ic_flags = c->channelFlags;
   4165 		} else {
   4166 			/* channels overlap; e.g. 11g and 11b */
   4167 			ic->ic_channels[ix].ic_flags |= c->channelFlags;
   4168 		}
   4169 	}
   4170 	free(chans, M_TEMP);
   4171 	return 0;
   4172 }
   4173 
   4174 static void
   4175 ath_led_done(void *arg)
   4176 {
   4177 	struct ath_softc *sc = arg;
   4178 
   4179 	sc->sc_blinking = 0;
   4180 }
   4181 
   4182 /*
   4183  * Turn the LED off: flip the pin and then set a timer so no
   4184  * update will happen for the specified duration.
   4185  */
   4186 static void
   4187 ath_led_off(void *arg)
   4188 {
   4189 	struct ath_softc *sc = arg;
   4190 
   4191 	ath_hal_gpioset(sc->sc_ah, sc->sc_ledpin, !sc->sc_ledon);
   4192 	callout_reset(&sc->sc_ledtimer, sc->sc_ledoff, ath_led_done, sc);
   4193 }
   4194 
   4195 /*
   4196  * Blink the LED according to the specified on/off times.
   4197  */
   4198 static void
   4199 ath_led_blink(struct ath_softc *sc, int on, int off)
   4200 {
   4201 	DPRINTF(sc, ATH_DEBUG_LED, "%s: on %u off %u\n", __func__, on, off);
   4202 	ath_hal_gpioset(sc->sc_ah, sc->sc_ledpin, sc->sc_ledon);
   4203 	sc->sc_blinking = 1;
   4204 	sc->sc_ledoff = off;
   4205 	callout_reset(&sc->sc_ledtimer, on, ath_led_off, sc);
   4206 }
   4207 
   4208 static void
   4209 ath_led_event(struct ath_softc *sc, int event)
   4210 {
   4211 
   4212 	sc->sc_ledevent = ticks;	/* time of last event */
   4213 	if (sc->sc_blinking)		/* don't interrupt active blink */
   4214 		return;
   4215 	switch (event) {
   4216 	case ATH_LED_POLL:
   4217 		ath_led_blink(sc, sc->sc_hwmap[0].ledon,
   4218 			sc->sc_hwmap[0].ledoff);
   4219 		break;
   4220 	case ATH_LED_TX:
   4221 		ath_led_blink(sc, sc->sc_hwmap[sc->sc_txrate].ledon,
   4222 			sc->sc_hwmap[sc->sc_txrate].ledoff);
   4223 		break;
   4224 	case ATH_LED_RX:
   4225 		ath_led_blink(sc, sc->sc_hwmap[sc->sc_rxrate].ledon,
   4226 			sc->sc_hwmap[sc->sc_rxrate].ledoff);
   4227 		break;
   4228 	}
   4229 }
   4230 
   4231 static void
   4232 ath_update_txpow(struct ath_softc *sc)
   4233 {
   4234 	struct ieee80211com *ic = &sc->sc_ic;
   4235 	struct ath_hal *ah = sc->sc_ah;
   4236 	u_int32_t txpow;
   4237 
   4238 	if (sc->sc_curtxpow != ic->ic_txpowlimit) {
   4239 		ath_hal_settxpowlimit(ah, ic->ic_txpowlimit);
   4240 		/* read back in case value is clamped */
   4241 		ath_hal_gettxpowlimit(ah, &txpow);
   4242 		ic->ic_txpowlimit = sc->sc_curtxpow = txpow;
   4243 	}
   4244 	/*
   4245 	 * Fetch max tx power level for status requests.
   4246 	 */
   4247 	ath_hal_getmaxtxpow(sc->sc_ah, &txpow);
   4248 	ic->ic_bss->ni_txpower = txpow;
   4249 }
   4250 
   4251 static int
   4252 ath_rate_setup(struct ath_softc *sc, u_int mode)
   4253 {
   4254 	struct ath_hal *ah = sc->sc_ah;
   4255 	struct ieee80211com *ic = &sc->sc_ic;
   4256 	const HAL_RATE_TABLE *rt;
   4257 	struct ieee80211_rateset *rs;
   4258 	int i, maxrates;
   4259 
   4260 	switch (mode) {
   4261 	case IEEE80211_MODE_11A:
   4262 		sc->sc_rates[mode] = ath_hal_getratetable(ah, HAL_MODE_11A);
   4263 		break;
   4264 	case IEEE80211_MODE_11B:
   4265 		sc->sc_rates[mode] = ath_hal_getratetable(ah, HAL_MODE_11B);
   4266 		break;
   4267 	case IEEE80211_MODE_11G:
   4268 		sc->sc_rates[mode] = ath_hal_getratetable(ah, HAL_MODE_11G);
   4269 		break;
   4270 	case IEEE80211_MODE_TURBO_A:
   4271 		sc->sc_rates[mode] = ath_hal_getratetable(ah, HAL_MODE_TURBO);
   4272 		break;
   4273 	case IEEE80211_MODE_TURBO_G:
   4274 		sc->sc_rates[mode] = ath_hal_getratetable(ah, HAL_MODE_108G);
   4275 		break;
   4276 	default:
   4277 		DPRINTF(sc, ATH_DEBUG_ANY, "%s: invalid mode %u\n",
   4278 			__func__, mode);
   4279 		return 0;
   4280 	}
   4281 	rt = sc->sc_rates[mode];
   4282 	if (rt == NULL)
   4283 		return 0;
   4284 	if (rt->rateCount > IEEE80211_RATE_MAXSIZE) {
   4285 		DPRINTF(sc, ATH_DEBUG_ANY,
   4286 			"%s: rate table too small (%u > %u)\n",
   4287 			__func__, rt->rateCount, IEEE80211_RATE_MAXSIZE);
   4288 		maxrates = IEEE80211_RATE_MAXSIZE;
   4289 	} else
   4290 		maxrates = rt->rateCount;
   4291 	rs = &ic->ic_sup_rates[mode];
   4292 	for (i = 0; i < maxrates; i++)
   4293 		rs->rs_rates[i] = rt->info[i].dot11Rate;
   4294 	rs->rs_nrates = maxrates;
   4295 	return 1;
   4296 }
   4297 
   4298 static void
   4299 ath_setcurmode(struct ath_softc *sc, enum ieee80211_phymode mode)
   4300 {
   4301 #define	N(a)	(sizeof(a)/sizeof(a[0]))
   4302 	/* NB: on/off times from the Atheros NDIS driver, w/ permission */
   4303 	static const struct {
   4304 		u_int		rate;		/* tx/rx 802.11 rate */
   4305 		u_int16_t	timeOn;		/* LED on time (ms) */
   4306 		u_int16_t	timeOff;	/* LED off time (ms) */
   4307 	} blinkrates[] = {
   4308 		{ 108,  40,  10 },
   4309 		{  96,  44,  11 },
   4310 		{  72,  50,  13 },
   4311 		{  48,  57,  14 },
   4312 		{  36,  67,  16 },
   4313 		{  24,  80,  20 },
   4314 		{  22, 100,  25 },
   4315 		{  18, 133,  34 },
   4316 		{  12, 160,  40 },
   4317 		{  10, 200,  50 },
   4318 		{   6, 240,  58 },
   4319 		{   4, 267,  66 },
   4320 		{   2, 400, 100 },
   4321 		{   0, 500, 130 },
   4322 	};
   4323 	const HAL_RATE_TABLE *rt;
   4324 	int i, j;
   4325 
   4326 	memset(sc->sc_rixmap, 0xff, sizeof(sc->sc_rixmap));
   4327 	rt = sc->sc_rates[mode];
   4328 	KASSERT(rt != NULL, ("no h/w rate set for phy mode %u", mode));
   4329 	for (i = 0; i < rt->rateCount; i++)
   4330 		sc->sc_rixmap[rt->info[i].dot11Rate & IEEE80211_RATE_VAL] = i;
   4331 	memset(sc->sc_hwmap, 0, sizeof(sc->sc_hwmap));
   4332 	for (i = 0; i < 32; i++) {
   4333 		u_int8_t ix = rt->rateCodeToIndex[i];
   4334 		if (ix == 0xff) {
   4335 			sc->sc_hwmap[i].ledon = (500 * hz) / 1000;
   4336 			sc->sc_hwmap[i].ledoff = (130 * hz) / 1000;
   4337 			continue;
   4338 		}
   4339 		sc->sc_hwmap[i].ieeerate =
   4340 			rt->info[ix].dot11Rate & IEEE80211_RATE_VAL;
   4341 		sc->sc_hwmap[i].txflags = IEEE80211_RADIOTAP_F_DATAPAD;
   4342 		if (rt->info[ix].shortPreamble ||
   4343 		    rt->info[ix].phy == IEEE80211_T_OFDM)
   4344 			sc->sc_hwmap[i].txflags |= IEEE80211_RADIOTAP_F_SHORTPRE;
   4345 		/* NB: receive frames include FCS */
   4346 		sc->sc_hwmap[i].rxflags = sc->sc_hwmap[i].txflags |
   4347 			IEEE80211_RADIOTAP_F_FCS;
   4348 		/* setup blink rate table to avoid per-packet lookup */
   4349 		for (j = 0; j < N(blinkrates)-1; j++)
   4350 			if (blinkrates[j].rate == sc->sc_hwmap[i].ieeerate)
   4351 				break;
   4352 		/* NB: this uses the last entry if the rate isn't found */
   4353 		/* XXX beware of overlow */
   4354 		sc->sc_hwmap[i].ledon = (blinkrates[j].timeOn * hz) / 1000;
   4355 		sc->sc_hwmap[i].ledoff = (blinkrates[j].timeOff * hz) / 1000;
   4356 	}
   4357 	sc->sc_currates = rt;
   4358 	sc->sc_curmode = mode;
   4359 	/*
   4360 	 * All protection frames are transmited at 2Mb/s for
   4361 	 * 11g, otherwise at 1Mb/s.
   4362 	 * XXX select protection rate index from rate table.
   4363 	 */
   4364 	sc->sc_protrix = (mode == IEEE80211_MODE_11G ? 1 : 0);
   4365 	/* NB: caller is responsible for reseting rate control state */
   4366 #undef N
   4367 }
   4368 
   4369 #ifdef AR_DEBUG
   4370 static void
   4371 ath_printrxbuf(struct ath_buf *bf, int done)
   4372 {
   4373 	struct ath_desc *ds;
   4374 	int i;
   4375 
   4376 	for (i = 0, ds = bf->bf_desc; i < bf->bf_nseg; i++, ds++) {
   4377 		printf("R%d (%p %p) %08x %08x %08x %08x %08x %08x %c\n",
   4378 		    i, ds, (struct ath_desc *)bf->bf_daddr + i,
   4379 		    ds->ds_link, ds->ds_data,
   4380 		    ds->ds_ctl0, ds->ds_ctl1,
   4381 		    ds->ds_hw[0], ds->ds_hw[1],
   4382 		    !done ? ' ' : (ds->ds_rxstat.rs_status == 0) ? '*' : '!');
   4383 	}
   4384 }
   4385 
   4386 static void
   4387 ath_printtxbuf(struct ath_buf *bf, int done)
   4388 {
   4389 	struct ath_desc *ds;
   4390 	int i;
   4391 
   4392 	for (i = 0, ds = bf->bf_desc; i < bf->bf_nseg; i++, ds++) {
   4393 		printf("T%d (%p %p) %08x %08x %08x %08x %08x %08x %08x %08x %c\n",
   4394 		    i, ds, (struct ath_desc *)bf->bf_daddr + i,
   4395 		    ds->ds_link, ds->ds_data,
   4396 		    ds->ds_ctl0, ds->ds_ctl1,
   4397 		    ds->ds_hw[0], ds->ds_hw[1], ds->ds_hw[2], ds->ds_hw[3],
   4398 		    !done ? ' ' : (ds->ds_txstat.ts_status == 0) ? '*' : '!');
   4399 	}
   4400 }
   4401 #endif /* AR_DEBUG */
   4402 
   4403 static void
   4404 ath_watchdog(struct ifnet *ifp)
   4405 {
   4406 	struct ath_softc *sc = ifp->if_softc;
   4407 	struct ieee80211com *ic = &sc->sc_ic;
   4408 
   4409 	ifp->if_timer = 0;
   4410 	if ((ifp->if_flags & IFF_RUNNING) == 0 || sc->sc_invalid)
   4411 		return;
   4412 	if (sc->sc_tx_timer) {
   4413 		if (--sc->sc_tx_timer == 0) {
   4414 			if_printf(ifp, "device timeout\n");
   4415 			ath_reset(ifp);
   4416 			ifp->if_oerrors++;
   4417 			sc->sc_stats.ast_watchdog++;
   4418 		} else
   4419 			ifp->if_timer = 1;
   4420 	}
   4421 	ieee80211_watchdog(ic);
   4422 }
   4423 
   4424 /*
   4425  * Diagnostic interface to the HAL.  This is used by various
   4426  * tools to do things like retrieve register contents for
   4427  * debugging.  The mechanism is intentionally opaque so that
   4428  * it can change frequently w/o concern for compatiblity.
   4429  */
   4430 static int
   4431 ath_ioctl_diag(struct ath_softc *sc, struct ath_diag *ad)
   4432 {
   4433 	struct ath_hal *ah = sc->sc_ah;
   4434 	u_int id = ad->ad_id & ATH_DIAG_ID;
   4435 	void *indata = NULL;
   4436 	void *outdata = NULL;
   4437 	u_int32_t insize = ad->ad_in_size;
   4438 	u_int32_t outsize = ad->ad_out_size;
   4439 	int error = 0;
   4440 
   4441 	if (ad->ad_id & ATH_DIAG_IN) {
   4442 		/*
   4443 		 * Copy in data.
   4444 		 */
   4445 		indata = malloc(insize, M_TEMP, M_NOWAIT);
   4446 		if (indata == NULL) {
   4447 			error = ENOMEM;
   4448 			goto bad;
   4449 		}
   4450 		error = copyin(ad->ad_in_data, indata, insize);
   4451 		if (error)
   4452 			goto bad;
   4453 	}
   4454 	if (ad->ad_id & ATH_DIAG_DYN) {
   4455 		/*
   4456 		 * Allocate a buffer for the results (otherwise the HAL
   4457 		 * returns a pointer to a buffer where we can read the
   4458 		 * results).  Note that we depend on the HAL leaving this
   4459 		 * pointer for us to use below in reclaiming the buffer;
   4460 		 * may want to be more defensive.
   4461 		 */
   4462 		outdata = malloc(outsize, M_TEMP, M_NOWAIT);
   4463 		if (outdata == NULL) {
   4464 			error = ENOMEM;
   4465 			goto bad;
   4466 		}
   4467 	}
   4468 	if (ath_hal_getdiagstate(ah, id, indata, insize, &outdata, &outsize)) {
   4469 		if (outsize < ad->ad_out_size)
   4470 			ad->ad_out_size = outsize;
   4471 		if (outdata != NULL)
   4472 			error = copyout(outdata, ad->ad_out_data,
   4473 					ad->ad_out_size);
   4474 	} else {
   4475 		error = EINVAL;
   4476 	}
   4477 bad:
   4478 	if ((ad->ad_id & ATH_DIAG_IN) && indata != NULL)
   4479 		free(indata, M_TEMP);
   4480 	if ((ad->ad_id & ATH_DIAG_DYN) && outdata != NULL)
   4481 		free(outdata, M_TEMP);
   4482 	return error;
   4483 }
   4484 
   4485 static int
   4486 ath_ioctl(struct ifnet *ifp, u_long cmd, caddr_t data)
   4487 {
   4488 #define	IS_RUNNING(ifp) \
   4489 	((ifp->if_flags & (IFF_RUNNING|IFF_UP)) == (IFF_RUNNING|IFF_UP))
   4490 	struct ath_softc *sc = ifp->if_softc;
   4491 	struct ieee80211com *ic = &sc->sc_ic;
   4492 	struct ifreq *ifr = (struct ifreq *)data;
   4493 	int error = 0;
   4494 
   4495 	ATH_LOCK(sc);
   4496 	switch (cmd) {
   4497 	case SIOCSIFFLAGS:
   4498 		if (IS_RUNNING(ifp)) {
   4499 			/*
   4500 			 * To avoid rescanning another access point,
   4501 			 * do not call ath_init() here.  Instead,
   4502 			 * only reflect promisc mode settings.
   4503 			 */
   4504 			ath_mode_init(sc);
   4505 		} else if (ifp->if_flags & IFF_UP) {
   4506 			/*
   4507 			 * Beware of being called during attach/detach
   4508 			 * to reset promiscuous mode.  In that case we
   4509 			 * will still be marked UP but not RUNNING.
   4510 			 * However trying to re-init the interface
   4511 			 * is the wrong thing to do as we've already
   4512 			 * torn down much of our state.  There's
   4513 			 * probably a better way to deal with this.
   4514 			 */
   4515 			if (!sc->sc_invalid && ic->ic_bss != NULL)
   4516 				ath_init(ifp);	/* XXX lose error */
   4517 		} else
   4518 			ath_stop_locked(ifp);
   4519 		break;
   4520 	case SIOCADDMULTI:
   4521 	case SIOCDELMULTI:
   4522 		/*
   4523 		 * The upper layer has already installed/removed
   4524 		 * the multicast address(es), just recalculate the
   4525 		 * multicast filter for the card.
   4526 		 */
   4527 		if (ifp->if_flags & IFF_RUNNING)
   4528 			ath_mode_init(sc);
   4529 		break;
   4530 	case SIOCGATHSTATS:
   4531 		/* NB: embed these numbers to get a consistent view */
   4532 		sc->sc_stats.ast_tx_packets = ifp->if_opackets;
   4533 		sc->sc_stats.ast_rx_packets = ifp->if_ipackets;
   4534 		sc->sc_stats.ast_rx_rssi = ieee80211_getrssi(ic);
   4535 		ATH_UNLOCK(sc);
   4536 		/*
   4537 		 * NB: Drop the softc lock in case of a page fault;
   4538 		 * we'll accept any potential inconsisentcy in the
   4539 		 * statistics.  The alternative is to copy the data
   4540 		 * to a local structure.
   4541 		 */
   4542 		return copyout(&sc->sc_stats,
   4543 				ifr->ifr_data, sizeof (sc->sc_stats));
   4544 	case SIOCGATHDIAG:
   4545 		error = ath_ioctl_diag(sc, (struct ath_diag *) ifr);
   4546 		break;
   4547 	default:
   4548 		error = ieee80211_ioctl(ic, cmd, data);
   4549 		if (error == ENETRESET) {
   4550 			if (IS_RUNNING(ifp) &&
   4551 			    ic->ic_roaming != IEEE80211_ROAMING_MANUAL)
   4552 				ath_init(ifp);	/* XXX lose error */
   4553 			error = 0;
   4554 		}
   4555 		if (error == ERESTART)
   4556 			error = IS_RUNNING(ifp) ? ath_reset(ifp) : 0;
   4557 		break;
   4558 	}
   4559 	ATH_UNLOCK(sc);
   4560 	return error;
   4561 #undef IS_RUNNING
   4562 }
   4563 
   4564 static int
   4565 ath_sysctl_slottime(SYSCTL_HANDLER_ARGS)
   4566 {
   4567 	struct ath_softc *sc = arg1;
   4568 	u_int slottime = ath_hal_getslottime(sc->sc_ah);
   4569 	int error;
   4570 
   4571 	error = sysctl_handle_int(oidp, &slottime, 0, req);
   4572 	if (error || !req->newptr)
   4573 		return error;
   4574 	return !ath_hal_setslottime(sc->sc_ah, slottime) ? EINVAL : 0;
   4575 }
   4576 
   4577 static int
   4578 ath_sysctl_acktimeout(SYSCTL_HANDLER_ARGS)
   4579 {
   4580 	struct ath_softc *sc = arg1;
   4581 	u_int acktimeout = ath_hal_getacktimeout(sc->sc_ah);
   4582 	int error;
   4583 
   4584 	error = sysctl_handle_int(oidp, &acktimeout, 0, req);
   4585 	if (error || !req->newptr)
   4586 		return error;
   4587 	return !ath_hal_setacktimeout(sc->sc_ah, acktimeout) ? EINVAL : 0;
   4588 }
   4589 
   4590 static int
   4591 ath_sysctl_ctstimeout(SYSCTL_HANDLER_ARGS)
   4592 {
   4593 	struct ath_softc *sc = arg1;
   4594 	u_int ctstimeout = ath_hal_getctstimeout(sc->sc_ah);
   4595 	int error;
   4596 
   4597 	error = sysctl_handle_int(oidp, &ctstimeout, 0, req);
   4598 	if (error || !req->newptr)
   4599 		return error;
   4600 	return !ath_hal_setctstimeout(sc->sc_ah, ctstimeout) ? EINVAL : 0;
   4601 }
   4602 
   4603 static int
   4604 ath_sysctl_softled(SYSCTL_HANDLER_ARGS)
   4605 {
   4606 	struct ath_softc *sc = arg1;
   4607 	int softled = sc->sc_softled;
   4608 	int error;
   4609 
   4610 	error = sysctl_handle_int(oidp, &softled, 0, req);
   4611 	if (error || !req->newptr)
   4612 		return error;
   4613 	softled = (softled != 0);
   4614 	if (softled != sc->sc_softled) {
   4615 		if (softled) {
   4616 			/* NB: handle any sc_ledpin change */
   4617 			ath_hal_gpioCfgOutput(sc->sc_ah, sc->sc_ledpin);
   4618 			ath_hal_gpioset(sc->sc_ah, sc->sc_ledpin,
   4619 				!sc->sc_ledon);
   4620 		}
   4621 		sc->sc_softled = softled;
   4622 	}
   4623 	return 0;
   4624 }
   4625 
   4626 static int
   4627 ath_sysctl_rxantenna(SYSCTL_HANDLER_ARGS)
   4628 {
   4629 	struct ath_softc *sc = arg1;
   4630 	u_int defantenna = ath_hal_getdefantenna(sc->sc_ah);
   4631 	int error;
   4632 
   4633 	error = sysctl_handle_int(oidp, &defantenna, 0, req);
   4634 	if (!error && req->newptr)
   4635 		ath_hal_setdefantenna(sc->sc_ah, defantenna);
   4636 	return error;
   4637 }
   4638 
   4639 static int
   4640 ath_sysctl_diversity(SYSCTL_HANDLER_ARGS)
   4641 {
   4642 	struct ath_softc *sc = arg1;
   4643 	u_int diversity = sc->sc_diversity;
   4644 	int error;
   4645 
   4646 	error = sysctl_handle_int(oidp, &diversity, 0, req);
   4647 	if (error || !req->newptr)
   4648 		return error;
   4649 	sc->sc_diversity = diversity;
   4650 	return !ath_hal_setdiversity(sc->sc_ah, diversity) ? EINVAL : 0;
   4651 }
   4652 
   4653 static int
   4654 ath_sysctl_diag(SYSCTL_HANDLER_ARGS)
   4655 {
   4656 	struct ath_softc *sc = arg1;
   4657 	u_int32_t diag;
   4658 	int error;
   4659 
   4660 	if (!ath_hal_getdiag(sc->sc_ah, &diag))
   4661 		return EINVAL;
   4662 	error = sysctl_handle_int(oidp, &diag, 0, req);
   4663 	if (error || !req->newptr)
   4664 		return error;
   4665 	return !ath_hal_setdiag(sc->sc_ah, diag) ? EINVAL : 0;
   4666 }
   4667 
   4668 static int
   4669 ath_sysctl_tpscale(SYSCTL_HANDLER_ARGS)
   4670 {
   4671 	struct ath_softc *sc = arg1;
   4672 	struct ifnet *ifp = &sc->sc_if;
   4673 	u_int32_t scale;
   4674 	int error;
   4675 
   4676 	ath_hal_gettpscale(sc->sc_ah, &scale);
   4677 	error = sysctl_handle_int(oidp, &scale, 0, req);
   4678 	if (error || !req->newptr)
   4679 		return error;
   4680 	return !ath_hal_settpscale(sc->sc_ah, scale) ? EINVAL : ath_reset(ifp);
   4681 }
   4682 
   4683 static int
   4684 ath_sysctl_tpc(SYSCTL_HANDLER_ARGS)
   4685 {
   4686 	struct ath_softc *sc = arg1;
   4687 	u_int tpc = ath_hal_gettpc(sc->sc_ah);
   4688 	int error;
   4689 
   4690 	error = sysctl_handle_int(oidp, &tpc, 0, req);
   4691 	if (error || !req->newptr)
   4692 		return error;
   4693 	return !ath_hal_settpc(sc->sc_ah, tpc) ? EINVAL : 0;
   4694 }
   4695 
   4696 static void
   4697 ath_sysctlattach(struct ath_softc *sc)
   4698 {
   4699 	struct sysctl_ctx_list *ctx = device_get_sysctl_ctx(sc->sc_dev);
   4700 	struct sysctl_oid *tree = device_get_sysctl_tree(sc->sc_dev);
   4701 
   4702 	ath_hal_getcountrycode(sc->sc_ah, &sc->sc_countrycode);
   4703 	SYSCTL_ADD_INT(ctx, SYSCTL_CHILDREN(tree), OID_AUTO,
   4704 		"countrycode", CTLFLAG_RD, &sc->sc_countrycode, 0,
   4705 		"EEPROM country code");
   4706 	ath_hal_getregdomain(sc->sc_ah, &sc->sc_regdomain);
   4707 	SYSCTL_ADD_INT(ctx, SYSCTL_CHILDREN(tree), OID_AUTO,
   4708 		"regdomain", CTLFLAG_RD, &sc->sc_regdomain, 0,
   4709 		"EEPROM regdomain code");
   4710 	sc->sc_debug = ath_debug;
   4711 	SYSCTL_ADD_INT(ctx, SYSCTL_CHILDREN(tree), OID_AUTO,
   4712 		"debug", CTLFLAG_RW, &sc->sc_debug, 0,
   4713 		"control debugging printfs");
   4714 
   4715 	SYSCTL_ADD_PROC(ctx, SYSCTL_CHILDREN(tree), OID_AUTO,
   4716 		"slottime", CTLTYPE_INT | CTLFLAG_RW, sc, 0,
   4717 		ath_sysctl_slottime, "I", "802.11 slot time (us)");
   4718 	SYSCTL_ADD_PROC(ctx, SYSCTL_CHILDREN(tree), OID_AUTO,
   4719 		"acktimeout", CTLTYPE_INT | CTLFLAG_RW, sc, 0,
   4720 		ath_sysctl_acktimeout, "I", "802.11 ACK timeout (us)");
   4721 	SYSCTL_ADD_PROC(ctx, SYSCTL_CHILDREN(tree), OID_AUTO,
   4722 		"ctstimeout", CTLTYPE_INT | CTLFLAG_RW, sc, 0,
   4723 		ath_sysctl_ctstimeout, "I", "802.11 CTS timeout (us)");
   4724 	SYSCTL_ADD_PROC(ctx, SYSCTL_CHILDREN(tree), OID_AUTO,
   4725 		"softled", CTLTYPE_INT | CTLFLAG_RW, sc, 0,
   4726 		ath_sysctl_softled, "I", "enable/disable software LED support");
   4727 	SYSCTL_ADD_INT(ctx, SYSCTL_CHILDREN(tree), OID_AUTO,
   4728 		"ledpin", CTLFLAG_RW, &sc->sc_ledpin, 0,
   4729 		"GPIO pin connected to LED");
   4730 	SYSCTL_ADD_INT(ctx, SYSCTL_CHILDREN(tree), OID_AUTO,
   4731 		"ledon", CTLFLAG_RW, &sc->sc_ledon, 0,
   4732 		"setting to turn LED on");
   4733 	SYSCTL_ADD_INT(ctx, SYSCTL_CHILDREN(tree), OID_AUTO,
   4734 		"ledidle", CTLFLAG_RW, &sc->sc_ledidle, 0,
   4735 		"idle time for inactivity LED (ticks)");
   4736 	SYSCTL_ADD_INT(ctx, SYSCTL_CHILDREN(tree), OID_AUTO,
   4737 		"txantenna", CTLFLAG_RW, &sc->sc_txantenna, 0,
   4738 		"tx antenna (0=auto)");
   4739 	SYSCTL_ADD_PROC(ctx, SYSCTL_CHILDREN(tree), OID_AUTO,
   4740 		"rxantenna", CTLTYPE_INT | CTLFLAG_RW, sc, 0,
   4741 		ath_sysctl_rxantenna, "I", "default/rx antenna");
   4742 	if (sc->sc_hasdiversity)
   4743 		SYSCTL_ADD_PROC(ctx, SYSCTL_CHILDREN(tree), OID_AUTO,
   4744 			"diversity", CTLTYPE_INT | CTLFLAG_RW, sc, 0,
   4745 			ath_sysctl_diversity, "I", "antenna diversity");
   4746 	sc->sc_txintrperiod = ATH_TXINTR_PERIOD;
   4747 	SYSCTL_ADD_INT(ctx, SYSCTL_CHILDREN(tree), OID_AUTO,
   4748 		"txintrperiod", CTLFLAG_RW, &sc->sc_txintrperiod, 0,
   4749 		"tx descriptor batching");
   4750 	SYSCTL_ADD_PROC(ctx, SYSCTL_CHILDREN(tree), OID_AUTO,
   4751 		"diag", CTLTYPE_INT | CTLFLAG_RW, sc, 0,
   4752 		ath_sysctl_diag, "I", "h/w diagnostic control");
   4753 	SYSCTL_ADD_PROC(ctx, SYSCTL_CHILDREN(tree), OID_AUTO,
   4754 		"tpscale", CTLTYPE_INT | CTLFLAG_RW, sc, 0,
   4755 		ath_sysctl_tpscale, "I", "tx power scaling");
   4756 	if (sc->sc_hastpc)
   4757 		SYSCTL_ADD_PROC(ctx, SYSCTL_CHILDREN(tree), OID_AUTO,
   4758 			"tpc", CTLTYPE_INT | CTLFLAG_RW, sc, 0,
   4759 			ath_sysctl_tpc, "I", "enable/disable per-packet TPC");
   4760 }
   4761 
   4762 static void
   4763 ath_bpfattach(struct ath_softc *sc)
   4764 {
   4765 	struct ifnet *ifp = &sc->sc_if;
   4766 
   4767 	bpfattach2(ifp, DLT_IEEE802_11_RADIO,
   4768 		sizeof(struct ieee80211_frame) + sizeof(sc->sc_tx_th),
   4769 		&sc->sc_drvbpf);
   4770 	/*
   4771 	 * Initialize constant fields.
   4772 	 * XXX make header lengths a multiple of 32-bits so subsequent
   4773 	 *     headers are properly aligned; this is a kludge to keep
   4774 	 *     certain applications happy.
   4775 	 *
   4776 	 * NB: the channel is setup each time we transition to the
   4777 	 *     RUN state to avoid filling it in for each frame.
   4778 	 */
   4779 	sc->sc_tx_th_len = roundup(sizeof(sc->sc_tx_th), sizeof(u_int32_t));
   4780 	sc->sc_tx_th.wt_ihdr.it_len = htole16(sc->sc_tx_th_len);
   4781 	sc->sc_tx_th.wt_ihdr.it_present = htole32(ATH_TX_RADIOTAP_PRESENT);
   4782 
   4783 	sc->sc_rx_th_len = roundup(sizeof(sc->sc_rx_th), sizeof(u_int32_t));
   4784 	sc->sc_rx_th.wr_ihdr.it_len = htole16(sc->sc_rx_th_len);
   4785 	sc->sc_rx_th.wr_ihdr.it_present = htole32(ATH_RX_RADIOTAP_PRESENT);
   4786 }
   4787 
   4788 /*
   4789  * Announce various information on device/driver attach.
   4790  */
   4791 static void
   4792 ath_announce(struct ath_softc *sc)
   4793 {
   4794 #define	HAL_MODE_DUALBAND	(HAL_MODE_11A|HAL_MODE_11B)
   4795 	struct ifnet *ifp = &sc->sc_if;
   4796 	struct ath_hal *ah = sc->sc_ah;
   4797 	u_int modes, cc;
   4798 
   4799 	if_printf(ifp, "mac %d.%d phy %d.%d",
   4800 		ah->ah_macVersion, ah->ah_macRev,
   4801 		ah->ah_phyRev >> 4, ah->ah_phyRev & 0xf);
   4802 	/*
   4803 	 * Print radio revision(s).  We check the wireless modes
   4804 	 * to avoid falsely printing revs for inoperable parts.
   4805 	 * Dual-band radio revs are returned in the 5Ghz rev number.
   4806 	 */
   4807 	ath_hal_getcountrycode(ah, &cc);
   4808 	modes = ath_hal_getwirelessmodes(ah, cc);
   4809 	if ((modes & HAL_MODE_DUALBAND) == HAL_MODE_DUALBAND) {
   4810 		if (ah->ah_analog5GhzRev && ah->ah_analog2GhzRev)
   4811 			printf(" 5ghz radio %d.%d 2ghz radio %d.%d",
   4812 				ah->ah_analog5GhzRev >> 4,
   4813 				ah->ah_analog5GhzRev & 0xf,
   4814 				ah->ah_analog2GhzRev >> 4,
   4815 				ah->ah_analog2GhzRev & 0xf);
   4816 		else
   4817 			printf(" radio %d.%d", ah->ah_analog5GhzRev >> 4,
   4818 				ah->ah_analog5GhzRev & 0xf);
   4819 	} else
   4820 		printf(" radio %d.%d", ah->ah_analog5GhzRev >> 4,
   4821 			ah->ah_analog5GhzRev & 0xf);
   4822 	printf("\n");
   4823 	if (bootverbose) {
   4824 		int i;
   4825 		for (i = 0; i <= WME_AC_VO; i++) {
   4826 			struct ath_txq *txq = sc->sc_ac2q[i];
   4827 			if_printf(ifp, "Use hw queue %u for %s traffic\n",
   4828 				txq->axq_qnum, ieee80211_wme_acnames[i]);
   4829 		}
   4830 		if_printf(ifp, "Use hw queue %u for CAB traffic\n",
   4831 			sc->sc_cabq->axq_qnum);
   4832 		if_printf(ifp, "Use hw queue %u for beacons\n", sc->sc_bhalq);
   4833 	}
   4834 #undef HAL_MODE_DUALBAND
   4835 }
   4836