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