Home | History | Annotate | Line # | Download | only in ic
ath.c revision 1.55
      1 /*	$NetBSD: ath.c,v 1.55 2005/07/26 22:52:48 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.55 2005/07/26 22:52:48 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 	/* XXX bus_dmamap_sync? -dcy */
   2029 #undef USE_SHPREAMBLE
   2030 }
   2031 
   2032 /*
   2033  * Transmit a beacon frame at SWBA.  Dynamic updates to the
   2034  * frame contents are done as needed and the slot time is
   2035  * also adjusted based on current state.
   2036  */
   2037 static void
   2038 ath_beacon_proc(void *arg, int pending)
   2039 {
   2040 	struct ath_softc *sc = arg;
   2041 	struct ath_buf *bf = STAILQ_FIRST(&sc->sc_bbuf);
   2042 	struct ieee80211_node *ni = bf->bf_node;
   2043 	struct ieee80211com *ic = ni->ni_ic;
   2044 	struct ath_hal *ah = sc->sc_ah;
   2045 	struct mbuf *m;
   2046 	int ncabq, error, otherant;
   2047 
   2048 	DPRINTF(sc, ATH_DEBUG_BEACON_PROC, "%s: pending %u\n",
   2049 		__func__, pending);
   2050 
   2051 	if (ic->ic_opmode == IEEE80211_M_STA ||
   2052 	    ic->ic_opmode == IEEE80211_M_MONITOR ||
   2053 	    bf == NULL || bf->bf_m == NULL) {
   2054 		DPRINTF(sc, ATH_DEBUG_ANY, "%s: ic_flags=%x bf=%p bf_m=%p\n",
   2055 			__func__, ic->ic_flags, bf, bf ? bf->bf_m : NULL);
   2056 		return;
   2057 	}
   2058 	/*
   2059 	 * Check if the previous beacon has gone out.  If
   2060 	 * not don't don't try to post another, skip this
   2061 	 * period and wait for the next.  Missed beacons
   2062 	 * indicate a problem and should not occur.  If we
   2063 	 * miss too many consecutive beacons reset the device.
   2064 	 */
   2065 	if (ath_hal_numtxpending(ah, sc->sc_bhalq) != 0) {
   2066 		sc->sc_bmisscount++;
   2067 		DPRINTF(sc, ATH_DEBUG_BEACON_PROC,
   2068 			"%s: missed %u consecutive beacons\n",
   2069 			__func__, sc->sc_bmisscount);
   2070 		if (sc->sc_bmisscount > 3)		/* NB: 3 is a guess */
   2071 			TASK_RUN_OR_ENQUEUE(&sc->sc_bstucktask);
   2072 		return;
   2073 	}
   2074 	if (sc->sc_bmisscount != 0) {
   2075 		DPRINTF(sc, ATH_DEBUG_BEACON,
   2076 			"%s: resume beacon xmit after %u misses\n",
   2077 			__func__, sc->sc_bmisscount);
   2078 		sc->sc_bmisscount = 0;
   2079 	}
   2080 
   2081 	/*
   2082 	 * Update dynamic beacon contents.  If this returns
   2083 	 * non-zero then we need to remap the memory because
   2084 	 * the beacon frame changed size (probably because
   2085 	 * of the TIM bitmap).
   2086 	 */
   2087 	m = bf->bf_m;
   2088 	ncabq = ath_hal_numtxpending(ah, sc->sc_cabq->axq_qnum);
   2089 	if (ieee80211_beacon_update(ic, bf->bf_node, &sc->sc_boff, m, ncabq)) {
   2090 		/* XXX too conservative? */
   2091 		bus_dmamap_unload(sc->sc_dmat, bf->bf_dmamap);
   2092 		error = bus_dmamap_load_mbuf(sc->sc_dmat, bf->bf_dmamap, m,
   2093 					     BUS_DMA_NOWAIT);
   2094 		if (error != 0) {
   2095 			if_printf(&sc->sc_if,
   2096 			    "%s: bus_dmamap_load_mbuf failed, error %u\n",
   2097 			    __func__, error);
   2098 			return;
   2099 		}
   2100 	}
   2101 
   2102 	/*
   2103 	 * Handle slot time change when a non-ERP station joins/leaves
   2104 	 * an 11g network.  The 802.11 layer notifies us via callback,
   2105 	 * we mark updateslot, then wait one beacon before effecting
   2106 	 * the change.  This gives associated stations at least one
   2107 	 * beacon interval to note the state change.
   2108 	 */
   2109 	/* XXX locking */
   2110 	if (sc->sc_updateslot == UPDATE)
   2111 		sc->sc_updateslot = COMMIT;	/* commit next beacon */
   2112 	else if (sc->sc_updateslot == COMMIT)
   2113 		ath_setslottime(sc);		/* commit change to h/w */
   2114 
   2115 	/*
   2116 	 * Check recent per-antenna transmit statistics and flip
   2117 	 * the default antenna if noticeably more frames went out
   2118 	 * on the non-default antenna.
   2119 	 * XXX assumes 2 anntenae
   2120 	 */
   2121 	otherant = sc->sc_defant & 1 ? 2 : 1;
   2122 	if (sc->sc_ant_tx[otherant] > sc->sc_ant_tx[sc->sc_defant] + 2)
   2123 		ath_setdefantenna(sc, otherant);
   2124 	sc->sc_ant_tx[1] = sc->sc_ant_tx[2] = 0;
   2125 
   2126 	/*
   2127 	 * Construct tx descriptor.
   2128 	 */
   2129 	ath_beacon_setup(sc, bf);
   2130 
   2131 	/*
   2132 	 * Stop any current dma and put the new frame on the queue.
   2133 	 * This should never fail since we check above that no frames
   2134 	 * are still pending on the queue.
   2135 	 */
   2136 	if (!ath_hal_stoptxdma(ah, sc->sc_bhalq)) {
   2137 		DPRINTF(sc, ATH_DEBUG_ANY,
   2138 			"%s: beacon queue %u did not stop?\n",
   2139 			__func__, sc->sc_bhalq);
   2140 	}
   2141 	bus_dmamap_sync(sc->sc_dmat, bf->bf_dmamap, 0,
   2142 	    bf->bf_dmamap->dm_mapsize, BUS_DMASYNC_PREWRITE);
   2143 
   2144 	/*
   2145 	 * Enable the CAB queue before the beacon queue to
   2146 	 * insure cab frames are triggered by this beacon.
   2147 	 */
   2148 	if (sc->sc_boff.bo_tim[4] & 1)		/* NB: only at DTIM */
   2149 		ath_hal_txstart(ah, sc->sc_cabq->axq_qnum);
   2150 	ath_hal_puttxbuf(ah, sc->sc_bhalq, bf->bf_daddr);
   2151 	ath_hal_txstart(ah, sc->sc_bhalq);
   2152 	DPRINTF(sc, ATH_DEBUG_BEACON_PROC,
   2153 		"%s: TXDP[%u] = %p (%p)\n", __func__,
   2154 		sc->sc_bhalq, (caddr_t)bf->bf_daddr, bf->bf_desc);
   2155 
   2156 	sc->sc_stats.ast_be_xmit++;
   2157 }
   2158 
   2159 /*
   2160  * Reset the hardware after detecting beacons have stopped.
   2161  */
   2162 static void
   2163 ath_bstuck_proc(void *arg, int pending)
   2164 {
   2165 	struct ath_softc *sc = arg;
   2166 	struct ifnet *ifp = &sc->sc_if;
   2167 
   2168 	if_printf(ifp, "stuck beacon; resetting (bmiss count %u)\n",
   2169 		sc->sc_bmisscount);
   2170 	ath_reset(ifp);
   2171 }
   2172 
   2173 /*
   2174  * Reclaim beacon resources.
   2175  */
   2176 static void
   2177 ath_beacon_free(struct ath_softc *sc)
   2178 {
   2179 	struct ath_buf *bf;
   2180 
   2181 	STAILQ_FOREACH(bf, &sc->sc_bbuf, bf_list) {
   2182 		if (bf->bf_m != NULL) {
   2183 			bus_dmamap_unload(sc->sc_dmat, bf->bf_dmamap);
   2184 			m_freem(bf->bf_m);
   2185 			bf->bf_m = NULL;
   2186 		}
   2187 		if (bf->bf_node != NULL) {
   2188 			ieee80211_free_node(bf->bf_node);
   2189 			bf->bf_node = NULL;
   2190 		}
   2191 	}
   2192 }
   2193 
   2194 /*
   2195  * Configure the beacon and sleep timers.
   2196  *
   2197  * When operating as an AP this resets the TSF and sets
   2198  * up the hardware to notify us when we need to issue beacons.
   2199  *
   2200  * When operating in station mode this sets up the beacon
   2201  * timers according to the timestamp of the last received
   2202  * beacon and the current TSF, configures PCF and DTIM
   2203  * handling, programs the sleep registers so the hardware
   2204  * will wakeup in time to receive beacons, and configures
   2205  * the beacon miss handling so we'll receive a BMISS
   2206  * interrupt when we stop seeing beacons from the AP
   2207  * we've associated with.
   2208  */
   2209 static void
   2210 ath_beacon_config(struct ath_softc *sc)
   2211 {
   2212 #define	TSF_TO_TU(_h,_l)	(((_h) << 22) | ((_l) >> 10))
   2213 	struct ath_hal *ah = sc->sc_ah;
   2214 	struct ieee80211com *ic = &sc->sc_ic;
   2215 	struct ieee80211_node *ni = ic->ic_bss;
   2216 	u_int32_t nexttbtt, intval;
   2217 
   2218 	/* extract tstamp from last beacon and convert to TU */
   2219 	nexttbtt = TSF_TO_TU(LE_READ_4(ni->ni_tstamp.data + 4),
   2220 			     LE_READ_4(ni->ni_tstamp.data));
   2221 	/* NB: the beacon interval is kept internally in TU's */
   2222 	intval = ni->ni_intval & HAL_BEACON_PERIOD;
   2223 	if (nexttbtt == 0)		/* e.g. for ap mode */
   2224 		nexttbtt = intval;
   2225 	else if (intval)		/* NB: can be 0 for monitor mode */
   2226 		nexttbtt = roundup(nexttbtt, intval);
   2227 	DPRINTF(sc, ATH_DEBUG_BEACON, "%s: nexttbtt %u intval %u (%u)\n",
   2228 		__func__, nexttbtt, intval, ni->ni_intval);
   2229 	if (ic->ic_opmode == IEEE80211_M_STA) {
   2230 		HAL_BEACON_STATE bs;
   2231 		u_int64_t tsf;
   2232 		u_int32_t tsftu;
   2233 		int dtimperiod, dtimcount;
   2234 		int cfpperiod, cfpcount;
   2235 
   2236 		/*
   2237 		 * Setup dtim and cfp parameters according to
   2238 		 * last beacon we received (which may be none).
   2239 		 */
   2240 		dtimperiod = ni->ni_dtim_period;
   2241 		if (dtimperiod <= 0)		/* NB: 0 if not known */
   2242 			dtimperiod = 1;
   2243 		dtimcount = ni->ni_dtim_count;
   2244 		if (dtimcount >= dtimperiod)	/* NB: sanity check */
   2245 			dtimcount = 0;		/* XXX? */
   2246 		cfpperiod = 1;			/* NB: no PCF support yet */
   2247 		cfpcount = 0;
   2248 #define	FUDGE	2
   2249 		/*
   2250 		 * Pull nexttbtt forward to reflect the current
   2251 		 * TSF and calculate dtim+cfp state for the result.
   2252 		 */
   2253 		tsf = ath_hal_gettsf64(ah);
   2254 		tsftu = TSF_TO_TU((u_int32_t)(tsf>>32), (u_int32_t)tsf) + FUDGE;
   2255 		do {
   2256 			nexttbtt += intval;
   2257 			if (--dtimcount < 0) {
   2258 				dtimcount = dtimperiod - 1;
   2259 				if (--cfpcount < 0)
   2260 					cfpcount = cfpperiod - 1;
   2261 			}
   2262 		} while (nexttbtt < tsftu);
   2263 #undef FUDGE
   2264 		memset(&bs, 0, sizeof(bs));
   2265 		bs.bs_intval = intval;
   2266 		bs.bs_nexttbtt = nexttbtt;
   2267 		bs.bs_dtimperiod = dtimperiod*intval;
   2268 		bs.bs_nextdtim = bs.bs_nexttbtt + dtimcount*intval;
   2269 		bs.bs_cfpperiod = cfpperiod*bs.bs_dtimperiod;
   2270 		bs.bs_cfpnext = bs.bs_nextdtim + cfpcount*bs.bs_dtimperiod;
   2271 		bs.bs_cfpmaxduration = 0;
   2272 #if 0
   2273 		/*
   2274 		 * The 802.11 layer records the offset to the DTIM
   2275 		 * bitmap while receiving beacons; use it here to
   2276 		 * enable h/w detection of our AID being marked in
   2277 		 * the bitmap vector (to indicate frames for us are
   2278 		 * pending at the AP).
   2279 		 * XXX do DTIM handling in s/w to WAR old h/w bugs
   2280 		 * XXX enable based on h/w rev for newer chips
   2281 		 */
   2282 		bs.bs_timoffset = ni->ni_timoff;
   2283 #endif
   2284 		/*
   2285 		 * Calculate the number of consecutive beacons to miss
   2286 		 * before taking a BMISS interrupt.  The configuration
   2287 		 * is specified in ms, so we need to convert that to
   2288 		 * TU's and then calculate based on the beacon interval.
   2289 		 * Note that we clamp the result to at most 10 beacons.
   2290 		 */
   2291 		bs.bs_bmissthreshold = howmany(ic->ic_bmisstimeout, intval);
   2292 		if (bs.bs_bmissthreshold > 10)
   2293 			bs.bs_bmissthreshold = 10;
   2294 		else if (bs.bs_bmissthreshold <= 0)
   2295 			bs.bs_bmissthreshold = 1;
   2296 
   2297 		/*
   2298 		 * Calculate sleep duration.  The configuration is
   2299 		 * given in ms.  We insure a multiple of the beacon
   2300 		 * period is used.  Also, if the sleep duration is
   2301 		 * greater than the DTIM period then it makes senses
   2302 		 * to make it a multiple of that.
   2303 		 *
   2304 		 * XXX fixed at 100ms
   2305 		 */
   2306 		bs.bs_sleepduration =
   2307 			roundup(IEEE80211_MS_TO_TU(100), bs.bs_intval);
   2308 		if (bs.bs_sleepduration > bs.bs_dtimperiod)
   2309 			bs.bs_sleepduration = roundup(bs.bs_sleepduration, bs.bs_dtimperiod);
   2310 
   2311 		DPRINTF(sc, ATH_DEBUG_BEACON,
   2312 			"%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"
   2313 			, __func__
   2314 			, tsf, tsftu
   2315 			, bs.bs_intval
   2316 			, bs.bs_nexttbtt
   2317 			, bs.bs_dtimperiod
   2318 			, bs.bs_nextdtim
   2319 			, bs.bs_bmissthreshold
   2320 			, bs.bs_sleepduration
   2321 			, bs.bs_cfpperiod
   2322 			, bs.bs_cfpmaxduration
   2323 			, bs.bs_cfpnext
   2324 			, bs.bs_timoffset
   2325 		);
   2326 		ath_hal_intrset(ah, 0);
   2327 		ath_hal_beacontimers(ah, &bs);
   2328 		sc->sc_imask |= HAL_INT_BMISS;
   2329 		ath_hal_intrset(ah, sc->sc_imask);
   2330 	} else {
   2331 		ath_hal_intrset(ah, 0);
   2332 		if (nexttbtt == intval)
   2333 			intval |= HAL_BEACON_RESET_TSF;
   2334 		if (ic->ic_opmode == IEEE80211_M_IBSS) {
   2335 			/*
   2336 			 * In IBSS mode enable the beacon timers but only
   2337 			 * enable SWBA interrupts if we need to manually
   2338 			 * prepare beacon frames.  Otherwise we use a
   2339 			 * self-linked tx descriptor and let the hardware
   2340 			 * deal with things.
   2341 			 */
   2342 			intval |= HAL_BEACON_ENA;
   2343 			if (!sc->sc_hasveol)
   2344 				sc->sc_imask |= HAL_INT_SWBA;
   2345 			ath_beaconq_config(sc);
   2346 		} else if (ic->ic_opmode == IEEE80211_M_HOSTAP) {
   2347 			/*
   2348 			 * In AP mode we enable the beacon timers and
   2349 			 * SWBA interrupts to prepare beacon frames.
   2350 			 */
   2351 			intval |= HAL_BEACON_ENA;
   2352 			sc->sc_imask |= HAL_INT_SWBA;	/* beacon prepare */
   2353 			ath_beaconq_config(sc);
   2354 		}
   2355 		ath_hal_beaconinit(ah, nexttbtt, intval);
   2356 		sc->sc_bmisscount = 0;
   2357 		ath_hal_intrset(ah, sc->sc_imask);
   2358 		/*
   2359 		 * When using a self-linked beacon descriptor in
   2360 		 * ibss mode load it once here.
   2361 		 */
   2362 		if (ic->ic_opmode == IEEE80211_M_IBSS && sc->sc_hasveol)
   2363 			ath_beacon_proc(sc, 0);
   2364 	}
   2365 #undef TSF_TO_TU
   2366 }
   2367 
   2368 static int
   2369 ath_descdma_setup(struct ath_softc *sc,
   2370 	struct ath_descdma *dd, ath_bufhead *head,
   2371 	const char *name, int nbuf, int ndesc)
   2372 {
   2373 #define	DS2PHYS(_dd, _ds) \
   2374 	((_dd)->dd_desc_paddr + ((caddr_t)(_ds) - (caddr_t)(_dd)->dd_desc))
   2375 	struct ifnet *ifp = &sc->sc_if;
   2376 	struct ath_desc *ds;
   2377 	struct ath_buf *bf;
   2378 	int i, bsize, error;
   2379 
   2380 	DPRINTF(sc, ATH_DEBUG_RESET, "%s: %s DMA: %u buffers %u desc/buf\n",
   2381 	    __func__, name, nbuf, ndesc);
   2382 
   2383 	dd->dd_name = name;
   2384 	dd->dd_desc_len = sizeof(struct ath_desc) * nbuf * ndesc;
   2385 
   2386 	/*
   2387 	 * Setup DMA descriptor area.
   2388 	 */
   2389 	dd->dd_dmat = sc->sc_dmat;
   2390 
   2391 	error = bus_dmamem_alloc(dd->dd_dmat, dd->dd_desc_len, PAGE_SIZE,
   2392 	    0, &dd->dd_dseg, 1, &dd->dd_dnseg, 0);
   2393 
   2394 	if (error != 0) {
   2395 		if_printf(ifp, "unable to alloc memory for %u %s descriptors, "
   2396 			"error %u\n", nbuf * ndesc, dd->dd_name, error);
   2397 		goto fail0;
   2398 	}
   2399 
   2400 	error = bus_dmamem_map(dd->dd_dmat, &dd->dd_dseg, dd->dd_dnseg,
   2401 	    dd->dd_desc_len, (caddr_t *)&dd->dd_desc, BUS_DMA_COHERENT);
   2402 	if (error != 0) {
   2403 		if_printf(ifp, "unable to map %u %s descriptors, error = %u\n",
   2404 		    nbuf * ndesc, dd->dd_name, error);
   2405 		goto fail1;
   2406 	}
   2407 
   2408 	/* allocate descriptors */
   2409 	error = bus_dmamap_create(dd->dd_dmat, dd->dd_desc_len, 1,
   2410 	    dd->dd_desc_len, 0, BUS_DMA_NOWAIT, &dd->dd_dmamap);
   2411 	if (error != 0) {
   2412 		if_printf(ifp, "unable to create dmamap for %s descriptors, "
   2413 			"error %u\n", dd->dd_name, error);
   2414 		goto fail2;
   2415 	}
   2416 
   2417 	error = bus_dmamap_load(dd->dd_dmat, dd->dd_dmamap, dd->dd_desc,
   2418 	    dd->dd_desc_len, NULL, BUS_DMA_NOWAIT);
   2419 	if (error != 0) {
   2420 		if_printf(ifp, "unable to map %s descriptors, error %u\n",
   2421 			dd->dd_name, error);
   2422 		goto fail3;
   2423 	}
   2424 
   2425 	ds = dd->dd_desc;
   2426 	dd->dd_desc_paddr = dd->dd_dmamap->dm_segs[0].ds_addr;
   2427 	DPRINTF(sc, ATH_DEBUG_RESET, "%s: %s DMA map: %p (%lu) -> %p (%lu)\n",
   2428 	    __func__, dd->dd_name, ds, (u_long) dd->dd_desc_len,
   2429 	    (caddr_t) dd->dd_desc_paddr, /*XXX*/ (u_long) dd->dd_desc_len);
   2430 
   2431 	/* allocate rx buffers */
   2432 	bsize = sizeof(struct ath_buf) * nbuf;
   2433 	bf = malloc(bsize, M_ATHDEV, M_NOWAIT | M_ZERO);
   2434 	if (bf == NULL) {
   2435 		if_printf(ifp, "malloc of %s buffers failed, size %u\n",
   2436 			dd->dd_name, bsize);
   2437 		goto fail4;
   2438 	}
   2439 	dd->dd_bufptr = bf;
   2440 
   2441 	STAILQ_INIT(head);
   2442 	for (i = 0; i < nbuf; i++, bf++, ds += ndesc) {
   2443 		bf->bf_desc = ds;
   2444 		bf->bf_daddr = DS2PHYS(dd, ds);
   2445 		error = bus_dmamap_create(sc->sc_dmat, MCLBYTES, ndesc,
   2446 				MCLBYTES, 0, BUS_DMA_NOWAIT, &bf->bf_dmamap);
   2447 		if (error != 0) {
   2448 			if_printf(ifp, "unable to create dmamap for %s "
   2449 				"buffer %u, error %u\n", dd->dd_name, i, error);
   2450 			ath_descdma_cleanup(sc, dd, head);
   2451 			return error;
   2452 		}
   2453 		STAILQ_INSERT_TAIL(head, bf, bf_list);
   2454 	}
   2455 	return 0;
   2456 fail4:
   2457 	bus_dmamap_unload(dd->dd_dmat, dd->dd_dmamap);
   2458 fail3:
   2459 	bus_dmamap_destroy(dd->dd_dmat, dd->dd_dmamap);
   2460 fail2:
   2461 	bus_dmamem_unmap(dd->dd_dmat, (caddr_t)dd->dd_desc, dd->dd_desc_len);
   2462 fail1:
   2463 	bus_dmamem_free(dd->dd_dmat, &dd->dd_dseg, dd->dd_dnseg);
   2464 fail0:
   2465 	memset(dd, 0, sizeof(*dd));
   2466 	return error;
   2467 #undef DS2PHYS
   2468 }
   2469 
   2470 static void
   2471 ath_descdma_cleanup(struct ath_softc *sc,
   2472 	struct ath_descdma *dd, ath_bufhead *head)
   2473 {
   2474 	struct ath_buf *bf;
   2475 	struct ieee80211_node *ni;
   2476 
   2477 	bus_dmamap_unload(dd->dd_dmat, dd->dd_dmamap);
   2478 	bus_dmamap_destroy(dd->dd_dmat, dd->dd_dmamap);
   2479 	bus_dmamem_unmap(dd->dd_dmat, (caddr_t)dd->dd_desc, dd->dd_desc_len);
   2480 	bus_dmamem_free(dd->dd_dmat, &dd->dd_dseg, dd->dd_dnseg);
   2481 
   2482 	STAILQ_FOREACH(bf, head, bf_list) {
   2483 		if (bf->bf_m) {
   2484 			m_freem(bf->bf_m);
   2485 			bf->bf_m = NULL;
   2486 		}
   2487 		if (bf->bf_dmamap != NULL) {
   2488 			bus_dmamap_destroy(sc->sc_dmat, bf->bf_dmamap);
   2489 			bf->bf_dmamap = NULL;
   2490 		}
   2491 		ni = bf->bf_node;
   2492 		bf->bf_node = NULL;
   2493 		if (ni != NULL) {
   2494 			/*
   2495 			 * Reclaim node reference.
   2496 			 */
   2497 			ieee80211_free_node(ni);
   2498 		}
   2499 	}
   2500 
   2501 	STAILQ_INIT(head);
   2502 	free(dd->dd_bufptr, M_ATHDEV);
   2503 	memset(dd, 0, sizeof(*dd));
   2504 }
   2505 
   2506 static int
   2507 ath_desc_alloc(struct ath_softc *sc)
   2508 {
   2509 	int error;
   2510 
   2511 	error = ath_descdma_setup(sc, &sc->sc_rxdma, &sc->sc_rxbuf,
   2512 			"rx", ATH_RXBUF, 1);
   2513 	if (error != 0)
   2514 		return error;
   2515 
   2516 	error = ath_descdma_setup(sc, &sc->sc_txdma, &sc->sc_txbuf,
   2517 			"tx", ATH_TXBUF, ATH_TXDESC);
   2518 	if (error != 0) {
   2519 		ath_descdma_cleanup(sc, &sc->sc_rxdma, &sc->sc_rxbuf);
   2520 		return error;
   2521 	}
   2522 
   2523 	error = ath_descdma_setup(sc, &sc->sc_bdma, &sc->sc_bbuf,
   2524 			"beacon", 1, 1);
   2525 	if (error != 0) {
   2526 		ath_descdma_cleanup(sc, &sc->sc_txdma, &sc->sc_txbuf);
   2527 		ath_descdma_cleanup(sc, &sc->sc_rxdma, &sc->sc_rxbuf);
   2528 		return error;
   2529 	}
   2530 	return 0;
   2531 }
   2532 
   2533 static void
   2534 ath_desc_free(struct ath_softc *sc)
   2535 {
   2536 
   2537 	if (sc->sc_bdma.dd_desc_len != 0)
   2538 		ath_descdma_cleanup(sc, &sc->sc_bdma, &sc->sc_bbuf);
   2539 	if (sc->sc_txdma.dd_desc_len != 0)
   2540 		ath_descdma_cleanup(sc, &sc->sc_txdma, &sc->sc_txbuf);
   2541 	if (sc->sc_rxdma.dd_desc_len != 0)
   2542 		ath_descdma_cleanup(sc, &sc->sc_rxdma, &sc->sc_rxbuf);
   2543 }
   2544 
   2545 static struct ieee80211_node *
   2546 ath_node_alloc(struct ieee80211_node_table *nt)
   2547 {
   2548 	struct ieee80211com *ic = nt->nt_ic;
   2549 	struct ath_softc *sc = ic->ic_ifp->if_softc;
   2550 	const size_t space = sizeof(struct ath_node) + sc->sc_rc->arc_space;
   2551 	struct ath_node *an;
   2552 
   2553 	an = malloc(space, M_80211_NODE, M_NOWAIT|M_ZERO);
   2554 	if (an == NULL) {
   2555 		/* XXX stat+msg */
   2556 		return NULL;
   2557 	}
   2558 	an->an_avgrssi = ATH_RSSI_DUMMY_MARKER;
   2559 	an->an_halstats.ns_avgbrssi = ATH_RSSI_DUMMY_MARKER;
   2560 	an->an_halstats.ns_avgrssi = ATH_RSSI_DUMMY_MARKER;
   2561 	an->an_halstats.ns_avgtxrssi = ATH_RSSI_DUMMY_MARKER;
   2562 	ath_rate_node_init(sc, an);
   2563 
   2564 	DPRINTF(sc, ATH_DEBUG_NODE, "%s: an %p\n", __func__, an);
   2565 	return &an->an_node;
   2566 }
   2567 
   2568 static void
   2569 ath_node_free(struct ieee80211_node *ni)
   2570 {
   2571 	struct ieee80211com *ic = ni->ni_ic;
   2572         struct ath_softc *sc = ic->ic_ifp->if_softc;
   2573 
   2574 	DPRINTF(sc, ATH_DEBUG_NODE, "%s: ni %p\n", __func__, ni);
   2575 
   2576 	ath_rate_node_cleanup(sc, ATH_NODE(ni));
   2577 	sc->sc_node_free(ni);
   2578 }
   2579 
   2580 static u_int8_t
   2581 ath_node_getrssi(const struct ieee80211_node *ni)
   2582 {
   2583 #define	HAL_EP_RND(x, mul) \
   2584 	((((x)%(mul)) >= ((mul)/2)) ? ((x) + ((mul) - 1)) / (mul) : (x)/(mul))
   2585 	u_int32_t avgrssi = ATH_NODE_CONST(ni)->an_avgrssi;
   2586 	int32_t rssi;
   2587 
   2588 	/*
   2589 	 * When only one frame is received there will be no state in
   2590 	 * avgrssi so fallback on the value recorded by the 802.11 layer.
   2591 	 */
   2592 	if (avgrssi != ATH_RSSI_DUMMY_MARKER)
   2593 		rssi = HAL_EP_RND(avgrssi, HAL_RSSI_EP_MULTIPLIER);
   2594 	else
   2595 		rssi = ni->ni_rssi;
   2596 	/* NB: theoretically we shouldn't need this, but be paranoid */
   2597 	return rssi < 0 ? 0 : rssi > 127 ? 127 : rssi;
   2598 #undef HAL_EP_RND
   2599 }
   2600 
   2601 static int
   2602 ath_rxbuf_init(struct ath_softc *sc, struct ath_buf *bf)
   2603 {
   2604 	struct ath_hal *ah = sc->sc_ah;
   2605 	int error;
   2606 	struct mbuf *m;
   2607 	struct ath_desc *ds;
   2608 
   2609 	m = bf->bf_m;
   2610 	if (m == NULL) {
   2611 		/*
   2612 		 * NB: by assigning a page to the rx dma buffer we
   2613 		 * implicitly satisfy the Atheros requirement that
   2614 		 * this buffer be cache-line-aligned and sized to be
   2615 		 * multiple of the cache line size.  Not doing this
   2616 		 * causes weird stuff to happen (for the 5210 at least).
   2617 		 */
   2618 		m = m_getcl(M_DONTWAIT, MT_DATA, M_PKTHDR);
   2619 		if (m == NULL) {
   2620 			DPRINTF(sc, ATH_DEBUG_ANY,
   2621 				"%s: no mbuf/cluster\n", __func__);
   2622 			sc->sc_stats.ast_rx_nombuf++;
   2623 			return ENOMEM;
   2624 		}
   2625 		bf->bf_m = m;
   2626 		m->m_pkthdr.len = m->m_len = m->m_ext.ext_size;
   2627 
   2628 		error = bus_dmamap_load_mbuf(sc->sc_dmat,
   2629 					     bf->bf_dmamap, m,
   2630 					     BUS_DMA_NOWAIT);
   2631 		if (error != 0) {
   2632 			DPRINTF(sc, ATH_DEBUG_ANY,
   2633 			    "%s: bus_dmamap_load_mbuf failed; error %d\n",
   2634 			    __func__, error);
   2635 			sc->sc_stats.ast_rx_busdma++;
   2636 			return error;
   2637 		}
   2638 		KASSERT(bf->bf_nseg == 1,
   2639 			("multi-segment packet; nseg %u", bf->bf_nseg));
   2640 	}
   2641 	bus_dmamap_sync(sc->sc_dmat, bf->bf_dmamap, 0,
   2642 	    bf->bf_dmamap->dm_mapsize, BUS_DMASYNC_PREREAD);
   2643 
   2644 	/*
   2645 	 * Setup descriptors.  For receive we always terminate
   2646 	 * the descriptor list with a self-linked entry so we'll
   2647 	 * not get overrun under high load (as can happen with a
   2648 	 * 5212 when ANI processing enables PHY error frames).
   2649 	 *
   2650 	 * To insure the last descriptor is self-linked we create
   2651 	 * each descriptor as self-linked and add it to the end.  As
   2652 	 * each additional descriptor is added the previous self-linked
   2653 	 * entry is ``fixed'' naturally.  This should be safe even
   2654 	 * if DMA is happening.  When processing RX interrupts we
   2655 	 * never remove/process the last, self-linked, entry on the
   2656 	 * descriptor list.  This insures the hardware always has
   2657 	 * someplace to write a new frame.
   2658 	 */
   2659 	ds = bf->bf_desc;
   2660 	ds->ds_link = bf->bf_daddr;	/* link to self */
   2661 	ds->ds_data = bf->bf_segs[0].ds_addr;
   2662 	ath_hal_setuprxdesc(ah, ds
   2663 		, m->m_len		/* buffer size */
   2664 		, 0
   2665 	);
   2666 
   2667 	if (sc->sc_rxlink != NULL)
   2668 		*sc->sc_rxlink = bf->bf_daddr;
   2669 	sc->sc_rxlink = &ds->ds_link;
   2670 	return 0;
   2671 }
   2672 
   2673 static uint64_t
   2674 ath_tsf_extend(struct ath_hal *ah, uint32_t rstamp)
   2675 {
   2676 	uint64_t tsf;
   2677 
   2678 	KASSERT((rstamp & 0xffff0000) == 0,
   2679 	    ("rx timestamp > 16 bits wide, %" PRIu32, rstamp));
   2680 
   2681 	tsf = ath_hal_gettsf64(ah);
   2682 
   2683 	/* Compensate for rollover. */
   2684 	if ((tsf & 0xffff) <= rstamp)
   2685 		tsf -= 0x10000;
   2686 
   2687 	return (tsf & ~(uint64_t)0xffff) | rstamp;
   2688 }
   2689 
   2690 /*
   2691  * Extend 15-bit time stamp from rx descriptor to
   2692  * a full 64-bit TSF using the current h/w TSF.
   2693  */
   2694 static __inline u_int64_t
   2695 ath_extend_tsf(struct ath_hal *ah, u_int32_t rstamp)
   2696 {
   2697 	u_int64_t tsf;
   2698 
   2699 	tsf = ath_hal_gettsf64(ah);
   2700 	if ((tsf & 0x7fff) < rstamp)
   2701 		tsf -= 0x8000;
   2702 	return ((tsf &~ 0x7fff) | rstamp);
   2703 }
   2704 
   2705 /*
   2706  * Intercept management frames to collect beacon rssi data
   2707  * and to do ibss merges.
   2708  */
   2709 static void
   2710 ath_recv_mgmt(struct ieee80211com *ic, struct mbuf *m,
   2711 	struct ieee80211_node *ni,
   2712 	int subtype, int rssi, u_int32_t rstamp)
   2713 {
   2714 	struct ath_softc *sc = ic->ic_ifp->if_softc;
   2715 
   2716 	/*
   2717 	 * Call up first so subsequent work can use information
   2718 	 * potentially stored in the node (e.g. for ibss merge).
   2719 	 */
   2720 	sc->sc_recv_mgmt(ic, m, ni, subtype, rssi, rstamp);
   2721 	switch (subtype) {
   2722 	case IEEE80211_FC0_SUBTYPE_BEACON:
   2723 		/* update rssi statistics for use by the hal */
   2724 		ATH_RSSI_LPF(ATH_NODE(ni)->an_halstats.ns_avgbrssi, rssi);
   2725 		/* fall thru... */
   2726 	case IEEE80211_FC0_SUBTYPE_PROBE_RESP:
   2727 		if (ic->ic_opmode == IEEE80211_M_IBSS &&
   2728 		    ic->ic_state == IEEE80211_S_RUN) {
   2729 			u_int64_t tsf = ath_tsf_extend(sc->sc_ah, rstamp);
   2730 
   2731 			/*
   2732 			 * Handle ibss merge as needed; check the tsf on the
   2733 			 * frame before attempting the merge.  The 802.11 spec
   2734 			 * says the station should change it's bssid to match
   2735 			 * the oldest station with the same ssid, where oldest
   2736 			 * is determined by the tsf.  Note that hardware
   2737 			 * reconfiguration happens through callback to
   2738 			 * ath_newstate as the state machine will go from
   2739 			 * RUN -> RUN when this happens.
   2740 			 */
   2741 			if (le64toh(ni->ni_tstamp.tsf) >= tsf) {
   2742 				DPRINTF(sc, ATH_DEBUG_STATE,
   2743 				    "ibss merge, rstamp %u tsf %ju "
   2744 				    "tstamp %ju\n", rstamp, (uintmax_t)tsf,
   2745 				    (uintmax_t)ni->ni_tstamp.tsf);
   2746 				(void) ieee80211_ibss_merge(ic, ni);
   2747 			}
   2748 		}
   2749 		break;
   2750 	}
   2751 }
   2752 
   2753 /*
   2754  * Set the default antenna.
   2755  */
   2756 static void
   2757 ath_setdefantenna(struct ath_softc *sc, u_int antenna)
   2758 {
   2759 	struct ath_hal *ah = sc->sc_ah;
   2760 
   2761 	/* XXX block beacon interrupts */
   2762 	ath_hal_setdefantenna(ah, antenna);
   2763 	if (sc->sc_defant != antenna)
   2764 		sc->sc_stats.ast_ant_defswitch++;
   2765 	sc->sc_defant = antenna;
   2766 	sc->sc_rxotherant = 0;
   2767 }
   2768 
   2769 static void
   2770 ath_rx_proc(void *arg, int npending)
   2771 {
   2772 #define	PA2DESC(_sc, _pa) \
   2773 	((struct ath_desc *)((caddr_t)(_sc)->sc_rxdma.dd_desc + \
   2774 		((_pa) - (_sc)->sc_rxdma.dd_desc_paddr)))
   2775 	struct ath_softc *sc = arg;
   2776 	struct ath_buf *bf;
   2777 	struct ieee80211com *ic = &sc->sc_ic;
   2778 	struct ifnet *ifp = &sc->sc_if;
   2779 	struct ath_hal *ah = sc->sc_ah;
   2780 	struct ath_desc *ds;
   2781 	struct mbuf *m;
   2782 	struct ieee80211_node *ni;
   2783 	struct ath_node *an;
   2784 	int len, type;
   2785 	u_int phyerr;
   2786 	HAL_STATUS status;
   2787 
   2788 	NET_LOCK_GIANT();		/* XXX */
   2789 
   2790 	DPRINTF(sc, ATH_DEBUG_RX_PROC, "%s: pending %u\n", __func__, npending);
   2791 	do {
   2792 		bf = STAILQ_FIRST(&sc->sc_rxbuf);
   2793 		if (bf == NULL) {		/* NB: shouldn't happen */
   2794 			if_printf(ifp, "%s: no buffer!\n", __func__);
   2795 			break;
   2796 		}
   2797 		ds = bf->bf_desc;
   2798 		if (ds->ds_link == bf->bf_daddr) {
   2799 			/* NB: never process the self-linked entry at the end */
   2800 			break;
   2801 		}
   2802 		m = bf->bf_m;
   2803 		if (m == NULL) {		/* NB: shouldn't happen */
   2804 			if_printf(ifp, "%s: no mbuf!\n", __func__);
   2805 			continue;
   2806 		}
   2807 		/* XXX sync descriptor memory */
   2808 		/*
   2809 		 * Must provide the virtual address of the current
   2810 		 * descriptor, the physical address, and the virtual
   2811 		 * address of the next descriptor in the h/w chain.
   2812 		 * This allows the HAL to look ahead to see if the
   2813 		 * hardware is done with a descriptor by checking the
   2814 		 * done bit in the following descriptor and the address
   2815 		 * of the current descriptor the DMA engine is working
   2816 		 * on.  All this is necessary because of our use of
   2817 		 * a self-linked list to avoid rx overruns.
   2818 		 */
   2819 		status = ath_hal_rxprocdesc(ah, ds,
   2820 				bf->bf_daddr, PA2DESC(sc, ds->ds_link));
   2821 #ifdef AR_DEBUG
   2822 		if (sc->sc_debug & ATH_DEBUG_RECV_DESC)
   2823 			ath_printrxbuf(bf, status == HAL_OK);
   2824 #endif
   2825 		if (status == HAL_EINPROGRESS)
   2826 			break;
   2827 		STAILQ_REMOVE_HEAD(&sc->sc_rxbuf, bf_list);
   2828 		if (ds->ds_rxstat.rs_more) {
   2829 			/*
   2830 			 * Frame spans multiple descriptors; this
   2831 			 * cannot happen yet as we don't support
   2832 			 * jumbograms.  If not in monitor mode,
   2833 			 * discard the frame.
   2834 			 */
   2835 			if (ic->ic_opmode != IEEE80211_M_MONITOR) {
   2836 				sc->sc_stats.ast_rx_toobig++;
   2837 				goto rx_next;
   2838 			}
   2839 			/* fall thru for monitor mode handling... */
   2840 		} else if (ds->ds_rxstat.rs_status != 0) {
   2841 			if (ds->ds_rxstat.rs_status & HAL_RXERR_CRC)
   2842 				sc->sc_stats.ast_rx_crcerr++;
   2843 			if (ds->ds_rxstat.rs_status & HAL_RXERR_FIFO)
   2844 				sc->sc_stats.ast_rx_fifoerr++;
   2845 			if (ds->ds_rxstat.rs_status & HAL_RXERR_PHY) {
   2846 				sc->sc_stats.ast_rx_phyerr++;
   2847 				phyerr = ds->ds_rxstat.rs_phyerr & 0x1f;
   2848 				sc->sc_stats.ast_rx_phy[phyerr]++;
   2849 				goto rx_next;
   2850 			}
   2851 			if (ds->ds_rxstat.rs_status & HAL_RXERR_DECRYPT) {
   2852 				/*
   2853 				 * Decrypt error.  If the error occurred
   2854 				 * because there was no hardware key, then
   2855 				 * let the frame through so the upper layers
   2856 				 * can process it.  This is necessary for 5210
   2857 				 * parts which have no way to setup a ``clear''
   2858 				 * key cache entry.
   2859 				 *
   2860 				 * XXX do key cache faulting
   2861 				 */
   2862 				if (ds->ds_rxstat.rs_keyix == HAL_RXKEYIX_INVALID)
   2863 					goto rx_accept;
   2864 				sc->sc_stats.ast_rx_badcrypt++;
   2865 			}
   2866 			if (ds->ds_rxstat.rs_status & HAL_RXERR_MIC) {
   2867 				sc->sc_stats.ast_rx_badmic++;
   2868 				/*
   2869 				 * Do minimal work required to hand off
   2870 				 * the 802.11 header for notifcation.
   2871 				 */
   2872 				/* XXX frag's and qos frames */
   2873 				len = ds->ds_rxstat.rs_datalen;
   2874 				if (len >= sizeof (struct ieee80211_frame)) {
   2875 					bus_dmamap_sync(sc->sc_dmat,
   2876 					    bf->bf_dmamap,
   2877 					    0, bf->bf_dmamap->dm_mapsize,
   2878 					    BUS_DMASYNC_POSTREAD);
   2879 					ieee80211_notify_michael_failure(ic,
   2880 					    mtod(m, struct ieee80211_frame *),
   2881 					    sc->sc_splitmic ?
   2882 					        ds->ds_rxstat.rs_keyix-32 :
   2883 					        ds->ds_rxstat.rs_keyix
   2884 					);
   2885 				}
   2886 			}
   2887 			ifp->if_ierrors++;
   2888 			/*
   2889 			 * Reject error frames, we normally don't want
   2890 			 * to see them in monitor mode (in monitor mode
   2891 			 * allow through packets that have crypto problems).
   2892 			 */
   2893 			if ((ds->ds_rxstat.rs_status &~
   2894 				(HAL_RXERR_DECRYPT|HAL_RXERR_MIC)) ||
   2895 			    sc->sc_ic.ic_opmode != IEEE80211_M_MONITOR)
   2896 				goto rx_next;
   2897 		}
   2898 rx_accept:
   2899 		/*
   2900 		 * Sync and unmap the frame.  At this point we're
   2901 		 * committed to passing the mbuf somewhere so clear
   2902 		 * bf_m; this means a new sk_buff must be allocated
   2903 		 * when the rx descriptor is setup again to receive
   2904 		 * another frame.
   2905 		 */
   2906 		bus_dmamap_sync(sc->sc_dmat, bf->bf_dmamap,
   2907 		    0, bf->bf_dmamap->dm_mapsize,
   2908 		    BUS_DMASYNC_POSTREAD);
   2909 		bus_dmamap_unload(sc->sc_dmat, bf->bf_dmamap);
   2910 		bf->bf_m = NULL;
   2911 
   2912 		m->m_pkthdr.rcvif = ifp;
   2913 		len = ds->ds_rxstat.rs_datalen;
   2914 		m->m_pkthdr.len = m->m_len = len;
   2915 
   2916 		sc->sc_stats.ast_ant_rx[ds->ds_rxstat.rs_antenna]++;
   2917 
   2918 #if NBPFILTER > 0
   2919 		if (sc->sc_drvbpf) {
   2920 			u_int8_t rix;
   2921 
   2922 			/*
   2923 			 * Discard anything shorter than an ack or cts.
   2924 			 */
   2925 			if (len < IEEE80211_ACK_LEN) {
   2926 				DPRINTF(sc, ATH_DEBUG_RECV,
   2927 					"%s: runt packet %d\n",
   2928 					__func__, len);
   2929 				sc->sc_stats.ast_rx_tooshort++;
   2930 				m_freem(m);
   2931 				goto rx_next;
   2932 			}
   2933 			rix = ds->ds_rxstat.rs_rate;
   2934 			sc->sc_rx_th.wr_flags = sc->sc_hwmap[rix].rxflags;
   2935 			sc->sc_rx_th.wr_rate = sc->sc_hwmap[rix].ieeerate;
   2936 			sc->sc_rx_th.wr_antsignal = ds->ds_rxstat.rs_rssi;
   2937 			sc->sc_rx_th.wr_antenna = ds->ds_rxstat.rs_antenna;
   2938 			/* XXX TSF */
   2939 
   2940 			bpf_mtap2(sc->sc_drvbpf,
   2941 				&sc->sc_rx_th, sc->sc_rx_th_len, m);
   2942 		}
   2943 #endif
   2944 
   2945 		/*
   2946 		 * From this point on we assume the frame is at least
   2947 		 * as large as ieee80211_frame_min; verify that.
   2948 		 */
   2949 		if (len < IEEE80211_MIN_LEN) {
   2950 			DPRINTF(sc, ATH_DEBUG_RECV, "%s: short packet %d\n",
   2951 				__func__, len);
   2952 			sc->sc_stats.ast_rx_tooshort++;
   2953 			m_freem(m);
   2954 			goto rx_next;
   2955 		}
   2956 
   2957 		if (IFF_DUMPPKTS(sc, ATH_DEBUG_RECV)) {
   2958 			ieee80211_dump_pkt(mtod(m, caddr_t), len,
   2959 				   sc->sc_hwmap[ds->ds_rxstat.rs_rate].ieeerate,
   2960 				   ds->ds_rxstat.rs_rssi);
   2961 		}
   2962 
   2963 		m_adj(m, -IEEE80211_CRC_LEN);
   2964 
   2965 		/*
   2966 		 * Locate the node for sender, track state, and then
   2967 		 * pass the (referenced) node up to the 802.11 layer
   2968 		 * for its use.  If the sender is unknown spam the
   2969 		 * frame; it'll be dropped where it's not wanted.
   2970 		 */
   2971 		if (ds->ds_rxstat.rs_keyix != HAL_RXKEYIX_INVALID &&
   2972 		    (ni = sc->sc_keyixmap[ds->ds_rxstat.rs_keyix]) != NULL) {
   2973 			/*
   2974 			 * Fast path: node is present in the key map;
   2975 			 * grab a reference for processing the frame.
   2976 			 */
   2977 			an = ATH_NODE(ieee80211_ref_node(ni));
   2978 			ATH_RSSI_LPF(an->an_avgrssi, ds->ds_rxstat.rs_rssi);
   2979 			type = ieee80211_input(ic, m, ni,
   2980 				ds->ds_rxstat.rs_rssi, ds->ds_rxstat.rs_tstamp);
   2981 		} else {
   2982 			/*
   2983 			 * Locate the node for sender, track state, and then
   2984 			 * pass the (referenced) node up to the 802.11 layer
   2985 			 * for its use.
   2986 			 */
   2987 			ni = ieee80211_find_rxnode(ic,
   2988 				mtod(m, const struct ieee80211_frame_min *));
   2989 			/*
   2990 			 * Track rx rssi and do any rx antenna management.
   2991 			 */
   2992 			an = ATH_NODE(ni);
   2993 			ATH_RSSI_LPF(an->an_avgrssi, ds->ds_rxstat.rs_rssi);
   2994 			/*
   2995 			 * Send frame up for processing.
   2996 			 */
   2997 			type = ieee80211_input(ic, m, ni,
   2998 				ds->ds_rxstat.rs_rssi, ds->ds_rxstat.rs_tstamp);
   2999 			if (ni != ic->ic_bss) {
   3000 				u_int16_t keyix;
   3001 				/*
   3002 				 * If the station has a key cache slot assigned
   3003 				 * update the key->node mapping table.
   3004 				 */
   3005 				keyix = ni->ni_ucastkey.wk_keyix;
   3006 				if (keyix != IEEE80211_KEYIX_NONE &&
   3007 				    sc->sc_keyixmap[keyix] == NULL)
   3008 					sc->sc_keyixmap[keyix] =
   3009 						ieee80211_ref_node(ni);
   3010 			}
   3011 		}
   3012 		ieee80211_free_node(ni);
   3013 		if (sc->sc_diversity) {
   3014 			/*
   3015 			 * When using fast diversity, change the default rx
   3016 			 * antenna if diversity chooses the other antenna 3
   3017 			 * times in a row.
   3018 			 */
   3019 			if (sc->sc_defant != ds->ds_rxstat.rs_antenna) {
   3020 				if (++sc->sc_rxotherant >= 3)
   3021 					ath_setdefantenna(sc,
   3022 						ds->ds_rxstat.rs_antenna);
   3023 			} else
   3024 				sc->sc_rxotherant = 0;
   3025 		}
   3026 		if (sc->sc_softled) {
   3027 			/*
   3028 			 * Blink for any data frame.  Otherwise do a
   3029 			 * heartbeat-style blink when idle.  The latter
   3030 			 * is mainly for station mode where we depend on
   3031 			 * periodic beacon frames to trigger the poll event.
   3032 			 */
   3033 			if (type == IEEE80211_FC0_TYPE_DATA) {
   3034 				sc->sc_rxrate = ds->ds_rxstat.rs_rate;
   3035 				ath_led_event(sc, ATH_LED_RX);
   3036 			} else if (ticks - sc->sc_ledevent >= sc->sc_ledidle)
   3037 				ath_led_event(sc, ATH_LED_POLL);
   3038 		}
   3039 rx_next:
   3040 		STAILQ_INSERT_TAIL(&sc->sc_rxbuf, bf, bf_list);
   3041 	} while (ath_rxbuf_init(sc, bf) == 0);
   3042 
   3043 	/* rx signal state monitoring */
   3044 	ath_hal_rxmonitor(ah, &ATH_NODE(ic->ic_bss)->an_halstats);
   3045 
   3046 #ifdef __NetBSD__
   3047 	/* XXX Why isn't this necessary in FreeBSD? */
   3048 	if ((ifp->if_flags & IFF_OACTIVE) == 0 && !IFQ_IS_EMPTY(&ifp->if_snd))
   3049 		ath_start(ifp);
   3050 #endif /* __NetBSD__ */
   3051 
   3052 	NET_UNLOCK_GIANT();		/* XXX */
   3053 #undef PA2DESC
   3054 }
   3055 
   3056 /*
   3057  * Setup a h/w transmit queue.
   3058  */
   3059 static struct ath_txq *
   3060 ath_txq_setup(struct ath_softc *sc, int qtype, int subtype)
   3061 {
   3062 #define	N(a)	(sizeof(a)/sizeof(a[0]))
   3063 	struct ath_hal *ah = sc->sc_ah;
   3064 	HAL_TXQ_INFO qi;
   3065 	int qnum;
   3066 
   3067 	memset(&qi, 0, sizeof(qi));
   3068 	qi.tqi_subtype = subtype;
   3069 	qi.tqi_aifs = HAL_TXQ_USEDEFAULT;
   3070 	qi.tqi_cwmin = HAL_TXQ_USEDEFAULT;
   3071 	qi.tqi_cwmax = HAL_TXQ_USEDEFAULT;
   3072 	/*
   3073 	 * Enable interrupts only for EOL and DESC conditions.
   3074 	 * We mark tx descriptors to receive a DESC interrupt
   3075 	 * when a tx queue gets deep; otherwise waiting for the
   3076 	 * EOL to reap descriptors.  Note that this is done to
   3077 	 * reduce interrupt load and this only defers reaping
   3078 	 * descriptors, never transmitting frames.  Aside from
   3079 	 * reducing interrupts this also permits more concurrency.
   3080 	 * The only potential downside is if the tx queue backs
   3081 	 * up in which case the top half of the kernel may backup
   3082 	 * due to a lack of tx descriptors.
   3083 	 */
   3084 	qi.tqi_qflags = TXQ_FLAG_TXEOLINT_ENABLE | TXQ_FLAG_TXDESCINT_ENABLE;
   3085 	qnum = ath_hal_setuptxqueue(ah, qtype, &qi);
   3086 	if (qnum == -1) {
   3087 		/*
   3088 		 * NB: don't print a message, this happens
   3089 		 * normally on parts with too few tx queues
   3090 		 */
   3091 		return NULL;
   3092 	}
   3093 	if (qnum >= N(sc->sc_txq)) {
   3094 		device_printf(sc->sc_dev,
   3095 			"hal qnum %u out of range, max %zu!\n",
   3096 			qnum, N(sc->sc_txq));
   3097 		ath_hal_releasetxqueue(ah, qnum);
   3098 		return NULL;
   3099 	}
   3100 	if (!ATH_TXQ_SETUP(sc, qnum)) {
   3101 		struct ath_txq *txq = &sc->sc_txq[qnum];
   3102 
   3103 		txq->axq_qnum = qnum;
   3104 		txq->axq_depth = 0;
   3105 		txq->axq_intrcnt = 0;
   3106 		txq->axq_link = NULL;
   3107 		STAILQ_INIT(&txq->axq_q);
   3108 		ATH_TXQ_LOCK_INIT(sc, txq);
   3109 		sc->sc_txqsetup |= 1<<qnum;
   3110 	}
   3111 	return &sc->sc_txq[qnum];
   3112 #undef N
   3113 }
   3114 
   3115 /*
   3116  * Setup a hardware data transmit queue for the specified
   3117  * access control.  The hal may not support all requested
   3118  * queues in which case it will return a reference to a
   3119  * previously setup queue.  We record the mapping from ac's
   3120  * to h/w queues for use by ath_tx_start and also track
   3121  * the set of h/w queues being used to optimize work in the
   3122  * transmit interrupt handler and related routines.
   3123  */
   3124 static int
   3125 ath_tx_setup(struct ath_softc *sc, int ac, int haltype)
   3126 {
   3127 #define	N(a)	(sizeof(a)/sizeof(a[0]))
   3128 	struct ath_txq *txq;
   3129 
   3130 	if (ac >= N(sc->sc_ac2q)) {
   3131 		device_printf(sc->sc_dev, "AC %u out of range, max %zu!\n",
   3132 			ac, N(sc->sc_ac2q));
   3133 		return 0;
   3134 	}
   3135 	txq = ath_txq_setup(sc, HAL_TX_QUEUE_DATA, haltype);
   3136 	if (txq != NULL) {
   3137 		sc->sc_ac2q[ac] = txq;
   3138 		return 1;
   3139 	} else
   3140 		return 0;
   3141 #undef N
   3142 }
   3143 
   3144 /*
   3145  * Update WME parameters for a transmit queue.
   3146  */
   3147 static int
   3148 ath_txq_update(struct ath_softc *sc, int ac)
   3149 {
   3150 #define	ATH_EXPONENT_TO_VALUE(v)	((1<<v)-1)
   3151 #define	ATH_TXOP_TO_US(v)		(v<<5)
   3152 	struct ieee80211com *ic = &sc->sc_ic;
   3153 	struct ath_txq *txq = sc->sc_ac2q[ac];
   3154 	struct wmeParams *wmep = &ic->ic_wme.wme_chanParams.cap_wmeParams[ac];
   3155 	struct ath_hal *ah = sc->sc_ah;
   3156 	HAL_TXQ_INFO qi;
   3157 
   3158 	ath_hal_gettxqueueprops(ah, txq->axq_qnum, &qi);
   3159 	qi.tqi_aifs = wmep->wmep_aifsn;
   3160 	qi.tqi_cwmin = ATH_EXPONENT_TO_VALUE(wmep->wmep_logcwmin);
   3161 	qi.tqi_cwmax = ATH_EXPONENT_TO_VALUE(wmep->wmep_logcwmax);
   3162 	qi.tqi_burstTime = ATH_TXOP_TO_US(wmep->wmep_txopLimit);
   3163 
   3164 	if (!ath_hal_settxqueueprops(ah, txq->axq_qnum, &qi)) {
   3165 		device_printf(sc->sc_dev, "unable to update hardware queue "
   3166 			"parameters for %s traffic!\n",
   3167 			ieee80211_wme_acnames[ac]);
   3168 		return 0;
   3169 	} else {
   3170 		ath_hal_resettxqueue(ah, txq->axq_qnum); /* push to h/w */
   3171 		return 1;
   3172 	}
   3173 #undef ATH_TXOP_TO_US
   3174 #undef ATH_EXPONENT_TO_VALUE
   3175 }
   3176 
   3177 /*
   3178  * Callback from the 802.11 layer to update WME parameters.
   3179  */
   3180 static int
   3181 ath_wme_update(struct ieee80211com *ic)
   3182 {
   3183 	struct ath_softc *sc = ic->ic_ifp->if_softc;
   3184 
   3185 	return !ath_txq_update(sc, WME_AC_BE) ||
   3186 	    !ath_txq_update(sc, WME_AC_BK) ||
   3187 	    !ath_txq_update(sc, WME_AC_VI) ||
   3188 	    !ath_txq_update(sc, WME_AC_VO) ? EIO : 0;
   3189 }
   3190 
   3191 /*
   3192  * Reclaim resources for a setup queue.
   3193  */
   3194 static void
   3195 ath_tx_cleanupq(struct ath_softc *sc, struct ath_txq *txq)
   3196 {
   3197 
   3198 	ath_hal_releasetxqueue(sc->sc_ah, txq->axq_qnum);
   3199 	ATH_TXQ_LOCK_DESTROY(txq);
   3200 	sc->sc_txqsetup &= ~(1<<txq->axq_qnum);
   3201 }
   3202 
   3203 /*
   3204  * Reclaim all tx queue resources.
   3205  */
   3206 static void
   3207 ath_tx_cleanup(struct ath_softc *sc)
   3208 {
   3209 	int i;
   3210 
   3211 	ATH_TXBUF_LOCK_DESTROY(sc);
   3212 	for (i = 0; i < HAL_NUM_TX_QUEUES; i++)
   3213 		if (ATH_TXQ_SETUP(sc, i))
   3214 			ath_tx_cleanupq(sc, &sc->sc_txq[i]);
   3215 }
   3216 
   3217 /*
   3218  * Defragment an mbuf chain, returning at most maxfrags separate
   3219  * mbufs+clusters.  If this is not possible NULL is returned and
   3220  * the original mbuf chain is left in it's present (potentially
   3221  * modified) state.  We use two techniques: collapsing consecutive
   3222  * mbufs and replacing consecutive mbufs by a cluster.
   3223  */
   3224 static struct mbuf *
   3225 ath_defrag(struct mbuf *m0, int how, int maxfrags)
   3226 {
   3227 	struct mbuf *m, *n, *n2, **prev;
   3228 	u_int curfrags;
   3229 
   3230 	/*
   3231 	 * Calculate the current number of frags.
   3232 	 */
   3233 	curfrags = 0;
   3234 	for (m = m0; m != NULL; m = m->m_next)
   3235 		curfrags++;
   3236 	/*
   3237 	 * First, try to collapse mbufs.  Note that we always collapse
   3238 	 * towards the front so we don't need to deal with moving the
   3239 	 * pkthdr.  This may be suboptimal if the first mbuf has much
   3240 	 * less data than the following.
   3241 	 */
   3242 	m = m0;
   3243 again:
   3244 	for (;;) {
   3245 		n = m->m_next;
   3246 		if (n == NULL)
   3247 			break;
   3248 		if ((m->m_flags & M_RDONLY) == 0 &&
   3249 		    n->m_len < M_TRAILINGSPACE(m)) {
   3250 			bcopy(mtod(n, void *), mtod(m, char *) + m->m_len,
   3251 				n->m_len);
   3252 			m->m_len += n->m_len;
   3253 			m->m_next = n->m_next;
   3254 			m_free(n);
   3255 			if (--curfrags <= maxfrags)
   3256 				return m0;
   3257 		} else
   3258 			m = n;
   3259 	}
   3260 	KASSERT(maxfrags > 1,
   3261 		("maxfrags %u, but normal collapse failed", maxfrags));
   3262 	/*
   3263 	 * Collapse consecutive mbufs to a cluster.
   3264 	 */
   3265 	prev = &m0->m_next;		/* NB: not the first mbuf */
   3266 	while ((n = *prev) != NULL) {
   3267 		if ((n2 = n->m_next) != NULL &&
   3268 		    n->m_len + n2->m_len < MCLBYTES) {
   3269 			m = m_getcl(how, MT_DATA, 0);
   3270 			if (m == NULL)
   3271 				goto bad;
   3272 			bcopy(mtod(n, void *), mtod(m, void *), n->m_len);
   3273 			bcopy(mtod(n2, void *), mtod(m, char *) + n->m_len,
   3274 				n2->m_len);
   3275 			m->m_len = n->m_len + n2->m_len;
   3276 			m->m_next = n2->m_next;
   3277 			*prev = m;
   3278 			m_free(n);
   3279 			m_free(n2);
   3280 			if (--curfrags <= maxfrags)	/* +1 cl -2 mbufs */
   3281 				return m0;
   3282 			/*
   3283 			 * Still not there, try the normal collapse
   3284 			 * again before we allocate another cluster.
   3285 			 */
   3286 			goto again;
   3287 		}
   3288 		prev = &n->m_next;
   3289 	}
   3290 	/*
   3291 	 * No place where we can collapse to a cluster; punt.
   3292 	 * This can occur if, for example, you request 2 frags
   3293 	 * but the packet requires that both be clusters (we
   3294 	 * never reallocate the first mbuf to avoid moving the
   3295 	 * packet header).
   3296 	 */
   3297 bad:
   3298 	return NULL;
   3299 }
   3300 
   3301 static int
   3302 ath_tx_start(struct ath_softc *sc, struct ieee80211_node *ni, struct ath_buf *bf,
   3303     struct mbuf *m0)
   3304 {
   3305 #define	CTS_DURATION \
   3306 	ath_hal_computetxtime(ah, rt, IEEE80211_ACK_LEN, cix, AH_TRUE)
   3307 #define	updateCTSForBursting(_ah, _ds, _txq) \
   3308 	ath_hal_updateCTSForBursting(_ah, _ds, \
   3309 	    _txq->axq_linkbuf != NULL ? _txq->axq_linkbuf->bf_desc : NULL, \
   3310 	    _txq->axq_lastdsWithCTS, _txq->axq_gatingds, \
   3311 	    txopLimit, CTS_DURATION)
   3312 	struct ieee80211com *ic = &sc->sc_ic;
   3313 	struct ath_hal *ah = sc->sc_ah;
   3314 	struct ifnet *ifp = &sc->sc_if;
   3315 	const struct chanAccParams *cap = &ic->ic_wme.wme_chanParams;
   3316 	int i, error, iswep, ismcast, keyix, hdrlen, pktlen, try0;
   3317 	u_int8_t rix, txrate, ctsrate;
   3318 	u_int8_t cix = 0xff;		/* NB: silence compiler */
   3319 	struct ath_desc *ds, *ds0;
   3320 	struct ath_txq *txq;
   3321 	struct ieee80211_frame *wh;
   3322 	u_int subtype, flags, ctsduration;
   3323 	HAL_PKT_TYPE atype;
   3324 	const HAL_RATE_TABLE *rt;
   3325 	HAL_BOOL shortPreamble;
   3326 	struct ath_node *an;
   3327 	struct mbuf *m;
   3328 	u_int pri;
   3329 
   3330 	wh = mtod(m0, struct ieee80211_frame *);
   3331 	iswep = wh->i_fc[1] & IEEE80211_FC1_WEP;
   3332 	ismcast = IEEE80211_IS_MULTICAST(wh->i_addr1);
   3333 	hdrlen = ieee80211_anyhdrsize(wh);
   3334 	/*
   3335 	 * Packet length must not include any
   3336 	 * pad bytes; deduct them here.
   3337 	 */
   3338 	pktlen = m0->m_pkthdr.len - (hdrlen & 3);
   3339 
   3340 	if (iswep) {
   3341 		const struct ieee80211_cipher *cip;
   3342 		struct ieee80211_key *k;
   3343 
   3344 		/*
   3345 		 * Construct the 802.11 header+trailer for an encrypted
   3346 		 * frame. The only reason this can fail is because of an
   3347 		 * unknown or unsupported cipher/key type.
   3348 		 */
   3349 		k = ieee80211_crypto_encap(ic, ni, m0);
   3350 		if (k == NULL) {
   3351 			/*
   3352 			 * This can happen when the key is yanked after the
   3353 			 * frame was queued.  Just discard the frame; the
   3354 			 * 802.11 layer counts failures and provides
   3355 			 * debugging/diagnostics.
   3356 			 */
   3357 			m_freem(m0);
   3358 			return EIO;
   3359 		}
   3360 		/*
   3361 		 * Adjust the packet + header lengths for the crypto
   3362 		 * additions and calculate the h/w key index.  When
   3363 		 * a s/w mic is done the frame will have had any mic
   3364 		 * added to it prior to entry so skb->len above will
   3365 		 * account for it. Otherwise we need to add it to the
   3366 		 * packet length.
   3367 		 */
   3368 		cip = k->wk_cipher;
   3369 		hdrlen += cip->ic_header;
   3370 		pktlen += cip->ic_header + cip->ic_trailer;
   3371 		if ((k->wk_flags & IEEE80211_KEY_SWMIC) == 0)
   3372 			pktlen += cip->ic_miclen;
   3373 		keyix = k->wk_keyix;
   3374 
   3375 		/* packet header may have moved, reset our local pointer */
   3376 		wh = mtod(m0, struct ieee80211_frame *);
   3377 	} else if (ni->ni_ucastkey.wk_cipher == &ieee80211_cipher_none) {
   3378 		/*
   3379 		 * Use station key cache slot, if assigned.
   3380 		 */
   3381 		keyix = ni->ni_ucastkey.wk_keyix;
   3382 		if (keyix == IEEE80211_KEYIX_NONE)
   3383 			keyix = HAL_TXKEYIX_INVALID;
   3384 	} else
   3385 		keyix = HAL_TXKEYIX_INVALID;
   3386 
   3387 	pktlen += IEEE80211_CRC_LEN;
   3388 
   3389 	/*
   3390 	 * Load the DMA map so any coalescing is done.  This
   3391 	 * also calculates the number of descriptors we need.
   3392 	 */
   3393 	error = bus_dmamap_load_mbuf(sc->sc_dmat, bf->bf_dmamap, m0,
   3394 				     BUS_DMA_NOWAIT);
   3395 	if (error == EFBIG) {
   3396 		/* XXX packet requires too many descriptors */
   3397 		bf->bf_nseg = ATH_TXDESC+1;
   3398 	} else if (error != 0) {
   3399 		sc->sc_stats.ast_tx_busdma++;
   3400 		m_freem(m0);
   3401 		return error;
   3402 	}
   3403 	/*
   3404 	 * Discard null packets and check for packets that
   3405 	 * require too many TX descriptors.  We try to convert
   3406 	 * the latter to a cluster.
   3407 	 */
   3408 	if (error == EFBIG) {		/* too many desc's, linearize */
   3409 		sc->sc_stats.ast_tx_linear++;
   3410 		m = ath_defrag(m0, M_DONTWAIT, ATH_TXDESC);
   3411 		if (m == NULL) {
   3412 			m_freem(m0);
   3413 			sc->sc_stats.ast_tx_nombuf++;
   3414 			return ENOMEM;
   3415 		}
   3416 		m0 = m;
   3417 		error = bus_dmamap_load_mbuf(sc->sc_dmat, bf->bf_dmamap, m0,
   3418 					     BUS_DMA_NOWAIT);
   3419 		if (error != 0) {
   3420 			sc->sc_stats.ast_tx_busdma++;
   3421 			m_freem(m0);
   3422 			return error;
   3423 		}
   3424 		KASSERT(bf->bf_nseg <= ATH_TXDESC,
   3425 		    ("too many segments after defrag; nseg %u", bf->bf_nseg));
   3426 	} else if (bf->bf_nseg == 0) {		/* null packet, discard */
   3427 		sc->sc_stats.ast_tx_nodata++;
   3428 		m_freem(m0);
   3429 		return EIO;
   3430 	}
   3431 	DPRINTF(sc, ATH_DEBUG_XMIT, "%s: m %p len %u\n", __func__, m0, pktlen);
   3432 	bus_dmamap_sync(sc->sc_dmat, bf->bf_dmamap, 0,
   3433             bf->bf_dmamap->dm_mapsize, BUS_DMASYNC_PREWRITE);
   3434 	bf->bf_m = m0;
   3435 	bf->bf_node = ni;			/* NB: held reference */
   3436 
   3437 	/* setup descriptors */
   3438 	ds = bf->bf_desc;
   3439 	rt = sc->sc_currates;
   3440 	KASSERT(rt != NULL, ("no rate table, mode %u", sc->sc_curmode));
   3441 
   3442 	/*
   3443 	 * NB: the 802.11 layer marks whether or not we should
   3444 	 * use short preamble based on the current mode and
   3445 	 * negotiated parameters.
   3446 	 */
   3447 	if ((ic->ic_flags & IEEE80211_F_SHPREAMBLE) &&
   3448 	    (ni->ni_capinfo & IEEE80211_CAPINFO_SHORT_PREAMBLE) && !ismcast) {
   3449 		shortPreamble = AH_TRUE;
   3450 		sc->sc_stats.ast_tx_shortpre++;
   3451 	} else {
   3452 		shortPreamble = AH_FALSE;
   3453 	}
   3454 
   3455 	an = ATH_NODE(ni);
   3456 	flags = HAL_TXDESC_CLRDMASK;		/* XXX needed for crypto errs */
   3457 	/*
   3458 	 * Calculate Atheros packet type from IEEE80211 packet header,
   3459 	 * setup for rate calculations, and select h/w transmit queue.
   3460 	 */
   3461 	switch (wh->i_fc[0] & IEEE80211_FC0_TYPE_MASK) {
   3462 	case IEEE80211_FC0_TYPE_MGT:
   3463 		subtype = wh->i_fc[0] & IEEE80211_FC0_SUBTYPE_MASK;
   3464 		if (subtype == IEEE80211_FC0_SUBTYPE_BEACON)
   3465 			atype = HAL_PKT_TYPE_BEACON;
   3466 		else if (subtype == IEEE80211_FC0_SUBTYPE_PROBE_RESP)
   3467 			atype = HAL_PKT_TYPE_PROBE_RESP;
   3468 		else if (subtype == IEEE80211_FC0_SUBTYPE_ATIM)
   3469 			atype = HAL_PKT_TYPE_ATIM;
   3470 		else
   3471 			atype = HAL_PKT_TYPE_NORMAL;	/* XXX */
   3472 		rix = 0;			/* XXX lowest rate */
   3473 		try0 = ATH_TXMAXTRY;
   3474 		if (shortPreamble)
   3475 			txrate = an->an_tx_mgtratesp;
   3476 		else
   3477 			txrate = an->an_tx_mgtrate;
   3478 		/* NB: force all management frames to highest queue */
   3479 		if (ni->ni_flags & IEEE80211_NODE_QOS) {
   3480 			/* NB: force all management frames to highest queue */
   3481 			pri = WME_AC_VO;
   3482 		} else
   3483 			pri = WME_AC_BE;
   3484 		flags |= HAL_TXDESC_INTREQ;	/* force interrupt */
   3485 		break;
   3486 	case IEEE80211_FC0_TYPE_CTL:
   3487 		atype = HAL_PKT_TYPE_PSPOLL;	/* stop setting of duration */
   3488 		rix = 0;			/* XXX lowest rate */
   3489 		try0 = ATH_TXMAXTRY;
   3490 		if (shortPreamble)
   3491 			txrate = an->an_tx_mgtratesp;
   3492 		else
   3493 			txrate = an->an_tx_mgtrate;
   3494 		/* NB: force all ctl frames to highest queue */
   3495 		if (ni->ni_flags & IEEE80211_NODE_QOS) {
   3496 			/* NB: force all ctl frames to highest queue */
   3497 			pri = WME_AC_VO;
   3498 		} else
   3499 			pri = WME_AC_BE;
   3500 		flags |= HAL_TXDESC_INTREQ;	/* force interrupt */
   3501 		break;
   3502 	case IEEE80211_FC0_TYPE_DATA:
   3503 		atype = HAL_PKT_TYPE_NORMAL;		/* default */
   3504 		/*
   3505 		 * Data frames; consult the rate control module for
   3506 		 * unicast frames.  Send multicast frames at the
   3507 		 * lowest rate.
   3508 		 */
   3509 		if (!ismcast) {
   3510 			ath_rate_findrate(sc, an, shortPreamble, pktlen,
   3511 				&rix, &try0, &txrate);
   3512 		} else {
   3513 			rix = 0;
   3514 			try0 = ATH_TXMAXTRY;
   3515 			txrate = an->an_tx_mgtrate;
   3516 		}
   3517 		sc->sc_txrate = txrate;			/* for LED blinking */
   3518 		/*
   3519 		 * Default all non-QoS traffic to the background queue.
   3520 		 */
   3521 		if (wh->i_fc[0] & IEEE80211_FC0_SUBTYPE_QOS) {
   3522 			pri = M_WME_GETAC(m0);
   3523 			if (cap->cap_wmeParams[pri].wmep_noackPolicy) {
   3524 				flags |= HAL_TXDESC_NOACK;
   3525 				sc->sc_stats.ast_tx_noack++;
   3526 			}
   3527 		} else
   3528 			pri = WME_AC_BE;
   3529 		break;
   3530 	default:
   3531 		if_printf(ifp, "bogus frame type 0x%x (%s)\n",
   3532 			wh->i_fc[0] & IEEE80211_FC0_TYPE_MASK, __func__);
   3533 		/* XXX statistic */
   3534 		m_freem(m0);
   3535 		return EIO;
   3536 	}
   3537 	txq = sc->sc_ac2q[pri];
   3538 
   3539 	/*
   3540 	 * When servicing one or more stations in power-save mode
   3541 	 * multicast frames must be buffered until after the beacon.
   3542 	 * We use the CAB queue for that.
   3543 	 */
   3544 	if (ismcast && ic->ic_ps_sta) {
   3545 		txq = sc->sc_cabq;
   3546 		/* XXX? more bit in 802.11 frame header */
   3547 	}
   3548 
   3549 	/*
   3550 	 * Calculate miscellaneous flags.
   3551 	 */
   3552 	if (ismcast) {
   3553 		flags |= HAL_TXDESC_NOACK;	/* no ack on broad/multicast */
   3554 		sc->sc_stats.ast_tx_noack++;
   3555 	} else if (pktlen > ic->ic_rtsthreshold) {
   3556 		flags |= HAL_TXDESC_RTSENA;	/* RTS based on frame length */
   3557 		cix = rt->info[rix].controlRate;
   3558 		sc->sc_stats.ast_tx_rts++;
   3559 	}
   3560 
   3561 	/*
   3562 	 * If 802.11g protection is enabled, determine whether
   3563 	 * to use RTS/CTS or just CTS.  Note that this is only
   3564 	 * done for OFDM unicast frames.
   3565 	 */
   3566 	if ((ic->ic_flags & IEEE80211_F_USEPROT) &&
   3567 	    rt->info[rix].phy == IEEE80211_T_OFDM &&
   3568 	    (flags & HAL_TXDESC_NOACK) == 0) {
   3569 		/* XXX fragments must use CCK rates w/ protection */
   3570 		if (ic->ic_protmode == IEEE80211_PROT_RTSCTS)
   3571 			flags |= HAL_TXDESC_RTSENA;
   3572 		else if (ic->ic_protmode == IEEE80211_PROT_CTSONLY)
   3573 			flags |= HAL_TXDESC_CTSENA;
   3574 		cix = rt->info[sc->sc_protrix].controlRate;
   3575 		sc->sc_stats.ast_tx_protect++;
   3576 	}
   3577 
   3578 	/*
   3579 	 * Calculate duration.  This logically belongs in the 802.11
   3580 	 * layer but it lacks sufficient information to calculate it.
   3581 	 */
   3582 	if ((flags & HAL_TXDESC_NOACK) == 0 &&
   3583 	    (wh->i_fc[0] & IEEE80211_FC0_TYPE_MASK) != IEEE80211_FC0_TYPE_CTL) {
   3584 		u_int16_t dur;
   3585 		/*
   3586 		 * XXX not right with fragmentation.
   3587 		 */
   3588 		if (shortPreamble)
   3589 			dur = rt->info[rix].spAckDuration;
   3590 		else
   3591 			dur = rt->info[rix].lpAckDuration;
   3592 		*(u_int16_t *)wh->i_dur = htole16(dur);
   3593 	}
   3594 
   3595 	/*
   3596 	 * Calculate RTS/CTS rate and duration if needed.
   3597 	 */
   3598 	ctsduration = 0;
   3599 	if (flags & (HAL_TXDESC_RTSENA|HAL_TXDESC_CTSENA)) {
   3600 		/*
   3601 		 * CTS transmit rate is derived from the transmit rate
   3602 		 * by looking in the h/w rate table.  We must also factor
   3603 		 * in whether or not a short preamble is to be used.
   3604 		 */
   3605 		/* NB: cix is set above where RTS/CTS is enabled */
   3606 		KASSERT(cix != 0xff, ("cix not setup"));
   3607 		ctsrate = rt->info[cix].rateCode;
   3608 		/*
   3609 		 * Compute the transmit duration based on the frame
   3610 		 * size and the size of an ACK frame.  We call into the
   3611 		 * HAL to do the computation since it depends on the
   3612 		 * characteristics of the actual PHY being used.
   3613 		 *
   3614 		 * NB: CTS is assumed the same size as an ACK so we can
   3615 		 *     use the precalculated ACK durations.
   3616 		 */
   3617 		if (shortPreamble) {
   3618 			ctsrate |= rt->info[cix].shortPreamble;
   3619 			if (flags & HAL_TXDESC_RTSENA)		/* SIFS + CTS */
   3620 				ctsduration += rt->info[cix].spAckDuration;
   3621 			ctsduration += ath_hal_computetxtime(ah,
   3622 				rt, pktlen, rix, AH_TRUE);
   3623 			if ((flags & HAL_TXDESC_NOACK) == 0)	/* SIFS + ACK */
   3624 				ctsduration += rt->info[cix].spAckDuration;
   3625 		} else {
   3626 			if (flags & HAL_TXDESC_RTSENA)		/* SIFS + CTS */
   3627 				ctsduration += rt->info[cix].lpAckDuration;
   3628 			ctsduration += ath_hal_computetxtime(ah,
   3629 				rt, pktlen, rix, AH_FALSE);
   3630 			if ((flags & HAL_TXDESC_NOACK) == 0)	/* SIFS + ACK */
   3631 				ctsduration += rt->info[cix].lpAckDuration;
   3632 		}
   3633 		/*
   3634 		 * Must disable multi-rate retry when using RTS/CTS.
   3635 		 */
   3636 		try0 = ATH_TXMAXTRY;
   3637 	} else
   3638 		ctsrate = 0;
   3639 
   3640 	if (IFF_DUMPPKTS(sc, ATH_DEBUG_XMIT))
   3641 		ieee80211_dump_pkt(mtod(m0, caddr_t), m0->m_len,
   3642 			sc->sc_hwmap[txrate].ieeerate, -1);
   3643 
   3644 	if (ic->ic_rawbpf)
   3645 		bpf_mtap(ic->ic_rawbpf, m0);
   3646 	if (sc->sc_drvbpf) {
   3647 		sc->sc_tx_th.wt_flags = sc->sc_hwmap[txrate].txflags;
   3648 		if (iswep)
   3649 			sc->sc_tx_th.wt_flags |= IEEE80211_RADIOTAP_F_WEP;
   3650 		sc->sc_tx_th.wt_rate = sc->sc_hwmap[txrate].ieeerate;
   3651 		sc->sc_tx_th.wt_txpower = ni->ni_txpower;
   3652 		sc->sc_tx_th.wt_antenna = sc->sc_txantenna;
   3653 
   3654 		bpf_mtap2(sc->sc_drvbpf,
   3655 			&sc->sc_tx_th, sc->sc_tx_th_len, m0);
   3656 	}
   3657 
   3658 	/*
   3659 	 * Determine if a tx interrupt should be generated for
   3660 	 * this descriptor.  We take a tx interrupt to reap
   3661 	 * descriptors when the h/w hits an EOL condition or
   3662 	 * when the descriptor is specifically marked to generate
   3663 	 * an interrupt.  We periodically mark descriptors in this
   3664 	 * way to insure timely replenishing of the supply needed
   3665 	 * for sending frames.  Defering interrupts reduces system
   3666 	 * load and potentially allows more concurrent work to be
   3667 	 * done but if done to aggressively can cause senders to
   3668 	 * backup.
   3669 	 *
   3670 	 * NB: use >= to deal with sc_txintrperiod changing
   3671 	 *     dynamically through sysctl.
   3672 	 */
   3673 	if (flags & HAL_TXDESC_INTREQ) {
   3674 		txq->axq_intrcnt = 0;
   3675 	} else if (++txq->axq_intrcnt >= sc->sc_txintrperiod) {
   3676 		flags |= HAL_TXDESC_INTREQ;
   3677 		txq->axq_intrcnt = 0;
   3678 	}
   3679 
   3680 	/*
   3681 	 * Formulate first tx descriptor with tx controls.
   3682 	 */
   3683 	/* XXX check return value? */
   3684 	ath_hal_setuptxdesc(ah, ds
   3685 		, pktlen		/* packet length */
   3686 		, hdrlen		/* header length */
   3687 		, atype			/* Atheros packet type */
   3688 		, ni->ni_txpower	/* txpower */
   3689 		, txrate, try0		/* series 0 rate/tries */
   3690 		, keyix			/* key cache index */
   3691 		, sc->sc_txantenna	/* antenna mode */
   3692 		, flags			/* flags */
   3693 		, ctsrate		/* rts/cts rate */
   3694 		, ctsduration		/* rts/cts duration */
   3695 	);
   3696 	bf->bf_flags = flags;
   3697 	/*
   3698 	 * Setup the multi-rate retry state only when we're
   3699 	 * going to use it.  This assumes ath_hal_setuptxdesc
   3700 	 * initializes the descriptors (so we don't have to)
   3701 	 * when the hardware supports multi-rate retry and
   3702 	 * we don't use it.
   3703 	 */
   3704 	if (try0 != ATH_TXMAXTRY)
   3705 		ath_rate_setupxtxdesc(sc, an, ds, shortPreamble, rix);
   3706 
   3707 	/*
   3708 	 * Fillin the remainder of the descriptor info.
   3709 	 */
   3710 	ds0 = ds;
   3711 	for (i = 0; i < bf->bf_nseg; i++, ds++) {
   3712 		ds->ds_data = bf->bf_segs[i].ds_addr;
   3713 		if (i == bf->bf_nseg - 1)
   3714 			ds->ds_link = 0;
   3715 		else
   3716 			ds->ds_link = bf->bf_daddr + sizeof(*ds) * (i + 1);
   3717 		ath_hal_filltxdesc(ah, ds
   3718 			, bf->bf_segs[i].ds_len	/* segment length */
   3719 			, i == 0		/* first segment */
   3720 			, i == bf->bf_nseg - 1	/* last segment */
   3721 			, ds0			/* first descriptor */
   3722 		);
   3723 		DPRINTF(sc, ATH_DEBUG_XMIT,
   3724 			"%s: %d: %08x %08x %08x %08x %08x %08x\n",
   3725 			__func__, i, ds->ds_link, ds->ds_data,
   3726 			ds->ds_ctl0, ds->ds_ctl1, ds->ds_hw[0], ds->ds_hw[1]);
   3727 	}
   3728 	/*
   3729 	 * Insert the frame on the outbound list and
   3730 	 * pass it on to the hardware.
   3731 	 */
   3732 	ATH_TXQ_LOCK(txq);
   3733 	if (flags & (HAL_TXDESC_RTSENA | HAL_TXDESC_CTSENA)) {
   3734 		u_int32_t txopLimit = IEEE80211_TXOP_TO_US(
   3735 			cap->cap_wmeParams[pri].wmep_txopLimit);
   3736 		/*
   3737 		 * When bursting, potentially extend the CTS duration
   3738 		 * of a previously queued frame to cover this frame
   3739 		 * and not exceed the txopLimit.  If that can be done
   3740 		 * then disable RTS/CTS on this frame since it's now
   3741 		 * covered (burst extension).  Otherwise we must terminate
   3742 		 * the burst before this frame goes out so as not to
   3743 		 * violate the WME parameters.  All this is complicated
   3744 		 * as we need to update the state of packets on the
   3745 		 * (live) hardware queue.  The logic is buried in the hal
   3746 		 * because it's highly chip-specific.
   3747 		 */
   3748 		if (txopLimit != 0) {
   3749 			sc->sc_stats.ast_tx_ctsburst++;
   3750 			if (updateCTSForBursting(ah, ds0, txq) == 0) {
   3751 				/*
   3752 				 * This frame was not covered by RTS/CTS from
   3753 				 * the previous frame in the burst; update the
   3754 				 * descriptor pointers so this frame is now
   3755 				 * treated as the last frame for extending a
   3756 				 * burst.
   3757 				 */
   3758 				txq->axq_lastdsWithCTS = ds0;
   3759 				/* set gating Desc to final desc */
   3760 				txq->axq_gatingds =
   3761 					(struct ath_desc *)txq->axq_link;
   3762 			} else
   3763 				sc->sc_stats.ast_tx_ctsext++;
   3764 		}
   3765 	}
   3766 	ATH_TXQ_INSERT_TAIL(txq, bf, bf_list);
   3767 	if (txq->axq_link == NULL) {
   3768 		ath_hal_puttxbuf(ah, txq->axq_qnum, bf->bf_daddr);
   3769 		DPRINTF(sc, ATH_DEBUG_XMIT,
   3770 			"%s: TXDP[%u] = %p (%p) depth %d\n", __func__,
   3771 			txq->axq_qnum, (caddr_t)bf->bf_daddr, bf->bf_desc,
   3772 			txq->axq_depth);
   3773 	} else {
   3774 		*txq->axq_link = bf->bf_daddr;
   3775 		DPRINTF(sc, ATH_DEBUG_XMIT,
   3776 			"%s: link[%u](%p)=%p (%p) depth %d\n", __func__,
   3777 			txq->axq_qnum, txq->axq_link,
   3778 			(caddr_t)bf->bf_daddr, bf->bf_desc, txq->axq_depth);
   3779 	}
   3780 	txq->axq_link = &bf->bf_desc[bf->bf_nseg - 1].ds_link;
   3781 	/*
   3782 	 * The CAB queue is started from the SWBA handler since
   3783 	 * frames only go out on DTIM and to avoid possible races.
   3784 	 */
   3785 	if (txq != sc->sc_cabq)
   3786 		ath_hal_txstart(ah, txq->axq_qnum);
   3787 	ATH_TXQ_UNLOCK(txq);
   3788 
   3789 	return 0;
   3790 #undef updateCTSForBursting
   3791 #undef CTS_DURATION
   3792 }
   3793 
   3794 /*
   3795  * Process completed xmit descriptors from the specified queue.
   3796  */
   3797 static void
   3798 ath_tx_processq(struct ath_softc *sc, struct ath_txq *txq)
   3799 {
   3800 	struct ath_hal *ah = sc->sc_ah;
   3801 	struct ieee80211com *ic = &sc->sc_ic;
   3802 	struct ath_buf *bf;
   3803 	struct ath_desc *ds, *ds0;
   3804 	struct ieee80211_node *ni;
   3805 	struct ath_node *an;
   3806 	int sr, lr, pri;
   3807 	HAL_STATUS status;
   3808 
   3809 	DPRINTF(sc, ATH_DEBUG_TX_PROC, "%s: tx queue %u head %p link %p\n",
   3810 		__func__, txq->axq_qnum,
   3811 		(caddr_t)(uintptr_t) ath_hal_gettxbuf(sc->sc_ah, txq->axq_qnum),
   3812 		txq->axq_link);
   3813 	for (;;) {
   3814 		ATH_TXQ_LOCK(txq);
   3815 		txq->axq_intrcnt = 0;	/* reset periodic desc intr count */
   3816 		bf = STAILQ_FIRST(&txq->axq_q);
   3817 		if (bf == NULL) {
   3818 			txq->axq_link = NULL;
   3819 			ATH_TXQ_UNLOCK(txq);
   3820 			break;
   3821 		}
   3822 		ds0 = &bf->bf_desc[0];
   3823 		ds = &bf->bf_desc[bf->bf_nseg - 1];
   3824 		status = ath_hal_txprocdesc(ah, ds);
   3825 #ifdef AR_DEBUG
   3826 		if (sc->sc_debug & ATH_DEBUG_XMIT_DESC)
   3827 			ath_printtxbuf(bf, status == HAL_OK);
   3828 #endif
   3829 		if (status == HAL_EINPROGRESS) {
   3830 			ATH_TXQ_UNLOCK(txq);
   3831 			break;
   3832 		}
   3833 		if (ds0 == txq->axq_lastdsWithCTS)
   3834 			txq->axq_lastdsWithCTS = NULL;
   3835 		if (ds == txq->axq_gatingds)
   3836 			txq->axq_gatingds = NULL;
   3837 		ATH_TXQ_REMOVE_HEAD(txq, bf_list);
   3838 		ATH_TXQ_UNLOCK(txq);
   3839 
   3840 		ni = bf->bf_node;
   3841 		if (ni != NULL) {
   3842 			an = ATH_NODE(ni);
   3843 			if (ds->ds_txstat.ts_status == 0) {
   3844 				u_int8_t txant = ds->ds_txstat.ts_antenna;
   3845 				sc->sc_stats.ast_ant_tx[txant]++;
   3846 				sc->sc_ant_tx[txant]++;
   3847 				if (ds->ds_txstat.ts_rate & HAL_TXSTAT_ALTRATE)
   3848 					sc->sc_stats.ast_tx_altrate++;
   3849 				sc->sc_stats.ast_tx_rssi =
   3850 					ds->ds_txstat.ts_rssi;
   3851 				ATH_RSSI_LPF(an->an_halstats.ns_avgtxrssi,
   3852 					ds->ds_txstat.ts_rssi);
   3853 				pri = M_WME_GETAC(bf->bf_m);
   3854 				if (pri >= WME_AC_VO)
   3855 					ic->ic_wme.wme_hipri_traffic++;
   3856 				ni->ni_inact = ni->ni_inact_reload;
   3857 			} else {
   3858 				if (ds->ds_txstat.ts_status & HAL_TXERR_XRETRY)
   3859 					sc->sc_stats.ast_tx_xretries++;
   3860 				if (ds->ds_txstat.ts_status & HAL_TXERR_FIFO)
   3861 					sc->sc_stats.ast_tx_fifoerr++;
   3862 				if (ds->ds_txstat.ts_status & HAL_TXERR_FILT)
   3863 					sc->sc_stats.ast_tx_filtered++;
   3864 			}
   3865 			sr = ds->ds_txstat.ts_shortretry;
   3866 			lr = ds->ds_txstat.ts_longretry;
   3867 			sc->sc_stats.ast_tx_shortretry += sr;
   3868 			sc->sc_stats.ast_tx_longretry += lr;
   3869 			/*
   3870 			 * Hand the descriptor to the rate control algorithm.
   3871 			 */
   3872 			if ((ds->ds_txstat.ts_status & HAL_TXERR_FILT) == 0 &&
   3873 			    (bf->bf_flags & HAL_TXDESC_NOACK) == 0)
   3874 				ath_rate_tx_complete(sc, an, ds, ds0);
   3875 			/*
   3876 			 * Reclaim reference to node.
   3877 			 *
   3878 			 * NB: the node may be reclaimed here if, for example
   3879 			 *     this is a DEAUTH message that was sent and the
   3880 			 *     node was timed out due to inactivity.
   3881 			 */
   3882 			ieee80211_free_node(ni);
   3883 		}
   3884 		bus_dmamap_sync(sc->sc_dmat, bf->bf_dmamap, 0,
   3885 		    bf->bf_dmamap->dm_mapsize, BUS_DMASYNC_POSTWRITE);
   3886 		bus_dmamap_unload(sc->sc_dmat, bf->bf_dmamap);
   3887 		m_freem(bf->bf_m);
   3888 		bf->bf_m = NULL;
   3889 		bf->bf_node = NULL;
   3890 
   3891 		ATH_TXBUF_LOCK(sc);
   3892 		STAILQ_INSERT_TAIL(&sc->sc_txbuf, bf, bf_list);
   3893 		ATH_TXBUF_UNLOCK(sc);
   3894 	}
   3895 }
   3896 
   3897 /*
   3898  * Deferred processing of transmit interrupt; special-cased
   3899  * for a single hardware transmit queue (e.g. 5210 and 5211).
   3900  */
   3901 static void
   3902 ath_tx_proc_q0(void *arg, int npending)
   3903 {
   3904 	struct ath_softc *sc = arg;
   3905 	struct ifnet *ifp = &sc->sc_if;
   3906 
   3907 	ath_tx_processq(sc, &sc->sc_txq[0]);
   3908 	ath_tx_processq(sc, sc->sc_cabq);
   3909 	ifp->if_flags &= ~IFF_OACTIVE;
   3910 	sc->sc_tx_timer = 0;
   3911 
   3912 	if (sc->sc_softled)
   3913 		ath_led_event(sc, ATH_LED_TX);
   3914 
   3915 	ath_start(ifp);
   3916 }
   3917 
   3918 /*
   3919  * Deferred processing of transmit interrupt; special-cased
   3920  * for four hardware queues, 0-3 (e.g. 5212 w/ WME support).
   3921  */
   3922 static void
   3923 ath_tx_proc_q0123(void *arg, int npending)
   3924 {
   3925 	struct ath_softc *sc = arg;
   3926 	struct ifnet *ifp = &sc->sc_if;
   3927 
   3928 	/*
   3929 	 * Process each active queue.
   3930 	 */
   3931 	ath_tx_processq(sc, &sc->sc_txq[0]);
   3932 	ath_tx_processq(sc, &sc->sc_txq[1]);
   3933 	ath_tx_processq(sc, &sc->sc_txq[2]);
   3934 	ath_tx_processq(sc, &sc->sc_txq[3]);
   3935 	ath_tx_processq(sc, sc->sc_cabq);
   3936 
   3937 	ifp->if_flags &= ~IFF_OACTIVE;
   3938 	sc->sc_tx_timer = 0;
   3939 
   3940 	if (sc->sc_softled)
   3941 		ath_led_event(sc, ATH_LED_TX);
   3942 
   3943 	ath_start(ifp);
   3944 }
   3945 
   3946 /*
   3947  * Deferred processing of transmit interrupt.
   3948  */
   3949 static void
   3950 ath_tx_proc(void *arg, int npending)
   3951 {
   3952 	struct ath_softc *sc = arg;
   3953 	struct ifnet *ifp = &sc->sc_if;
   3954 	int i;
   3955 
   3956 	/*
   3957 	 * Process each active queue.
   3958 	 */
   3959 	/* XXX faster to read ISR_S0_S and ISR_S1_S to determine q's? */
   3960 	for (i = 0; i < HAL_NUM_TX_QUEUES; i++)
   3961 		if (ATH_TXQ_SETUP(sc, i))
   3962 			ath_tx_processq(sc, &sc->sc_txq[i]);
   3963 
   3964 	ifp->if_flags &= ~IFF_OACTIVE;
   3965 	sc->sc_tx_timer = 0;
   3966 
   3967 	if (sc->sc_softled)
   3968 		ath_led_event(sc, ATH_LED_TX);
   3969 
   3970 	ath_start(ifp);
   3971 }
   3972 
   3973 static void
   3974 ath_tx_draintxq(struct ath_softc *sc, struct ath_txq *txq)
   3975 {
   3976 	struct ath_hal *ah = sc->sc_ah;
   3977 	struct ieee80211_node *ni;
   3978 	struct ath_buf *bf;
   3979 
   3980 	/*
   3981 	 * NB: this assumes output has been stopped and
   3982 	 *     we do not need to block ath_tx_tasklet
   3983 	 */
   3984 	for (;;) {
   3985 		ATH_TXQ_LOCK(txq);
   3986 		bf = STAILQ_FIRST(&txq->axq_q);
   3987 		if (bf == NULL) {
   3988 			txq->axq_link = NULL;
   3989 			ATH_TXQ_UNLOCK(txq);
   3990 			break;
   3991 		}
   3992 		ATH_TXQ_REMOVE_HEAD(txq, bf_list);
   3993 		ATH_TXQ_UNLOCK(txq);
   3994 #ifdef AR_DEBUG
   3995 		if (sc->sc_debug & ATH_DEBUG_RESET)
   3996 			ath_printtxbuf(bf,
   3997 				ath_hal_txprocdesc(ah, bf->bf_desc) == HAL_OK);
   3998 #endif /* AR_DEBUG */
   3999 		bus_dmamap_unload(sc->sc_dmat, bf->bf_dmamap);
   4000 		m_freem(bf->bf_m);
   4001 		bf->bf_m = NULL;
   4002 		ni = bf->bf_node;
   4003 		bf->bf_node = NULL;
   4004 		if (ni != NULL) {
   4005 			/*
   4006 			 * Reclaim node reference.
   4007 			 */
   4008 			ieee80211_free_node(ni);
   4009 		}
   4010 		ATH_TXBUF_LOCK(sc);
   4011 		STAILQ_INSERT_TAIL(&sc->sc_txbuf, bf, bf_list);
   4012 		ATH_TXBUF_UNLOCK(sc);
   4013 	}
   4014 }
   4015 
   4016 static void
   4017 ath_tx_stopdma(struct ath_softc *sc, struct ath_txq *txq)
   4018 {
   4019 	struct ath_hal *ah = sc->sc_ah;
   4020 
   4021 	(void) ath_hal_stoptxdma(ah, txq->axq_qnum);
   4022 	DPRINTF(sc, ATH_DEBUG_RESET, "%s: tx queue [%u] %p, link %p\n",
   4023 	    __func__, txq->axq_qnum,
   4024 	    (caddr_t)(uintptr_t) ath_hal_gettxbuf(ah, txq->axq_qnum),
   4025 	    txq->axq_link);
   4026 }
   4027 
   4028 /*
   4029  * Drain the transmit queues and reclaim resources.
   4030  */
   4031 static void
   4032 ath_draintxq(struct ath_softc *sc)
   4033 {
   4034 	struct ath_hal *ah = sc->sc_ah;
   4035 	struct ifnet *ifp = &sc->sc_if;
   4036 	int i;
   4037 
   4038 	/* XXX return value */
   4039 	if (!sc->sc_invalid) {
   4040 		/* don't touch the hardware if marked invalid */
   4041 		(void) ath_hal_stoptxdma(ah, sc->sc_bhalq);
   4042 		DPRINTF(sc, ATH_DEBUG_RESET,
   4043 		    "%s: beacon queue %p\n", __func__,
   4044 		    (caddr_t)(uintptr_t) ath_hal_gettxbuf(ah, sc->sc_bhalq));
   4045 		for (i = 0; i < HAL_NUM_TX_QUEUES; i++)
   4046 			if (ATH_TXQ_SETUP(sc, i))
   4047 				ath_tx_stopdma(sc, &sc->sc_txq[i]);
   4048 	}
   4049 	for (i = 0; i < HAL_NUM_TX_QUEUES; i++)
   4050 		if (ATH_TXQ_SETUP(sc, i))
   4051 			ath_tx_draintxq(sc, &sc->sc_txq[i]);
   4052 	ifp->if_flags &= ~IFF_OACTIVE;
   4053 	sc->sc_tx_timer = 0;
   4054 }
   4055 
   4056 /*
   4057  * Disable the receive h/w in preparation for a reset.
   4058  */
   4059 static void
   4060 ath_stoprecv(struct ath_softc *sc)
   4061 {
   4062 #define	PA2DESC(_sc, _pa) \
   4063 	((struct ath_desc *)((caddr_t)(_sc)->sc_rxdma.dd_desc + \
   4064 		((_pa) - (_sc)->sc_rxdma.dd_desc_paddr)))
   4065 	struct ath_hal *ah = sc->sc_ah;
   4066 
   4067 	ath_hal_stoppcurecv(ah);	/* disable PCU */
   4068 	ath_hal_setrxfilter(ah, 0);	/* clear recv filter */
   4069 	ath_hal_stopdmarecv(ah);	/* disable DMA engine */
   4070 	DELAY(3000);			/* 3ms is long enough for 1 frame */
   4071 #ifdef AR_DEBUG
   4072 	if (sc->sc_debug & (ATH_DEBUG_RESET | ATH_DEBUG_FATAL)) {
   4073 		struct ath_buf *bf;
   4074 
   4075 		printf("%s: rx queue %p, link %p\n", __func__,
   4076 			(caddr_t)(uintptr_t) ath_hal_getrxbuf(ah), sc->sc_rxlink);
   4077 		STAILQ_FOREACH(bf, &sc->sc_rxbuf, bf_list) {
   4078 			struct ath_desc *ds = bf->bf_desc;
   4079 			HAL_STATUS status = ath_hal_rxprocdesc(ah, ds,
   4080 				bf->bf_daddr, PA2DESC(sc, ds->ds_link));
   4081 			if (status == HAL_OK || (sc->sc_debug & ATH_DEBUG_FATAL))
   4082 				ath_printrxbuf(bf, status == HAL_OK);
   4083 		}
   4084 	}
   4085 #endif
   4086 	sc->sc_rxlink = NULL;		/* just in case */
   4087 #undef PA2DESC
   4088 }
   4089 
   4090 /*
   4091  * Enable the receive h/w following a reset.
   4092  */
   4093 static int
   4094 ath_startrecv(struct ath_softc *sc)
   4095 {
   4096 	struct ath_hal *ah = sc->sc_ah;
   4097 	struct ath_buf *bf;
   4098 
   4099 	sc->sc_rxlink = NULL;
   4100 	STAILQ_FOREACH(bf, &sc->sc_rxbuf, bf_list) {
   4101 		int error = ath_rxbuf_init(sc, bf);
   4102 		if (error != 0) {
   4103 			DPRINTF(sc, ATH_DEBUG_RECV,
   4104 				"%s: ath_rxbuf_init failed %d\n",
   4105 				__func__, error);
   4106 			return error;
   4107 		}
   4108 	}
   4109 
   4110 	bf = STAILQ_FIRST(&sc->sc_rxbuf);
   4111 	ath_hal_putrxbuf(ah, bf->bf_daddr);
   4112 	ath_hal_rxena(ah);		/* enable recv descriptors */
   4113 	ath_mode_init(sc);		/* set filters, etc. */
   4114 	ath_hal_startpcurecv(ah);	/* re-enable PCU/DMA engine */
   4115 	return 0;
   4116 }
   4117 
   4118 /*
   4119  * Update internal state after a channel change.
   4120  */
   4121 static void
   4122 ath_chan_change(struct ath_softc *sc, struct ieee80211_channel *chan)
   4123 {
   4124 	struct ieee80211com *ic = &sc->sc_ic;
   4125 	enum ieee80211_phymode mode;
   4126 	u_int16_t flags;
   4127 
   4128 	/*
   4129 	 * Change channels and update the h/w rate map
   4130 	 * if we're switching; e.g. 11a to 11b/g.
   4131 	 */
   4132 	mode = ieee80211_chan2mode(ic, chan);
   4133 	if (mode != sc->sc_curmode)
   4134 		ath_setcurmode(sc, mode);
   4135 	/*
   4136 	 * Update BPF state.  NB: ethereal et. al. don't handle
   4137 	 * merged flags well so pick a unique mode for their use.
   4138 	 */
   4139 	if (IEEE80211_IS_CHAN_A(chan))
   4140 		flags = IEEE80211_CHAN_A;
   4141 	/* XXX 11g schizophrenia */
   4142 	else if (IEEE80211_IS_CHAN_G(chan) ||
   4143 	    IEEE80211_IS_CHAN_PUREG(chan))
   4144 		flags = IEEE80211_CHAN_G;
   4145 	else
   4146 		flags = IEEE80211_CHAN_B;
   4147 	if (IEEE80211_IS_CHAN_T(chan))
   4148 		flags |= IEEE80211_CHAN_TURBO;
   4149 	sc->sc_tx_th.wt_chan_freq = sc->sc_rx_th.wr_chan_freq =
   4150 		htole16(chan->ic_freq);
   4151 	sc->sc_tx_th.wt_chan_flags = sc->sc_rx_th.wr_chan_flags =
   4152 		htole16(flags);
   4153 }
   4154 
   4155 /*
   4156  * Set/change channels.  If the channel is really being changed,
   4157  * it's done by reseting the chip.  To accomplish this we must
   4158  * first cleanup any pending DMA, then restart stuff after a la
   4159  * ath_init.
   4160  */
   4161 static int
   4162 ath_chan_set(struct ath_softc *sc, struct ieee80211_channel *chan)
   4163 {
   4164 	struct ath_hal *ah = sc->sc_ah;
   4165 	struct ieee80211com *ic = &sc->sc_ic;
   4166 	HAL_CHANNEL hchan;
   4167 
   4168 	/*
   4169 	 * Convert to a HAL channel description with
   4170 	 * the flags constrained to reflect the current
   4171 	 * operating mode.
   4172 	 */
   4173 	hchan.channel = chan->ic_freq;
   4174 	hchan.channelFlags = ath_chan2flags(ic, chan);
   4175 
   4176 	DPRINTF(sc, ATH_DEBUG_RESET, "%s: %u (%u MHz) -> %u (%u MHz)\n",
   4177 	    __func__,
   4178 	    ath_hal_mhz2ieee(sc->sc_curchan.channel,
   4179 		sc->sc_curchan.channelFlags),
   4180 	    	sc->sc_curchan.channel,
   4181 	    ath_hal_mhz2ieee(hchan.channel, hchan.channelFlags), hchan.channel);
   4182 	if (hchan.channel != sc->sc_curchan.channel ||
   4183 	    hchan.channelFlags != sc->sc_curchan.channelFlags) {
   4184 		HAL_STATUS status;
   4185 
   4186 		/*
   4187 		 * To switch channels clear any pending DMA operations;
   4188 		 * wait long enough for the RX fifo to drain, reset the
   4189 		 * hardware at the new frequency, and then re-enable
   4190 		 * the relevant bits of the h/w.
   4191 		 */
   4192 		ath_hal_intrset(ah, 0);		/* disable interrupts */
   4193 		ath_draintxq(sc);		/* clear pending tx frames */
   4194 		ath_stoprecv(sc);		/* turn off frame recv */
   4195 		if (!ath_hal_reset(ah, ic->ic_opmode, &hchan, AH_TRUE, &status)) {
   4196 			if_printf(&sc->sc_if, "ath_chan_set: unable to reset "
   4197 				"channel %u (%u Mhz)\n",
   4198 				ieee80211_chan2ieee(ic, chan), chan->ic_freq);
   4199 			return EIO;
   4200 		}
   4201 		sc->sc_curchan = hchan;
   4202 		ath_update_txpow(sc);		/* update tx power state */
   4203 
   4204 		/*
   4205 		 * Re-enable rx framework.
   4206 		 */
   4207 		if (ath_startrecv(sc) != 0) {
   4208 			if_printf(&sc->sc_if,
   4209 				"ath_chan_set: unable to restart recv logic\n");
   4210 			return EIO;
   4211 		}
   4212 
   4213 		/*
   4214 		 * Change channels and update the h/w rate map
   4215 		 * if we're switching; e.g. 11a to 11b/g.
   4216 		 */
   4217 		ic->ic_ibss_chan = chan;
   4218 		ath_chan_change(sc, chan);
   4219 
   4220 		/*
   4221 		 * Re-enable interrupts.
   4222 		 */
   4223 		ath_hal_intrset(ah, sc->sc_imask);
   4224 	}
   4225 	return 0;
   4226 }
   4227 
   4228 static void
   4229 ath_next_scan(void *arg)
   4230 {
   4231 	struct ath_softc *sc = arg;
   4232 	struct ieee80211com *ic = &sc->sc_ic;
   4233 	int s;
   4234 
   4235 	/* don't call ath_start w/o network interrupts blocked */
   4236 	s = splnet();
   4237 
   4238 	if (ic->ic_state == IEEE80211_S_SCAN)
   4239 		ieee80211_next_scan(ic);
   4240 	splx(s);
   4241 }
   4242 
   4243 /*
   4244  * Periodically recalibrate the PHY to account
   4245  * for temperature/environment changes.
   4246  */
   4247 static void
   4248 ath_calibrate(void *arg)
   4249 {
   4250 	struct ath_softc *sc = arg;
   4251 	struct ath_hal *ah = sc->sc_ah;
   4252 
   4253 	sc->sc_stats.ast_per_cal++;
   4254 
   4255 	ATH_LOCK(sc);
   4256 	DPRINTF(sc, ATH_DEBUG_CALIBRATE, "%s: channel %u/%x\n",
   4257 		__func__, sc->sc_curchan.channel, sc->sc_curchan.channelFlags);
   4258 
   4259 	if (ath_hal_getrfgain(ah) == HAL_RFGAIN_NEED_CHANGE) {
   4260 		/*
   4261 		 * Rfgain is out of bounds, reset the chip
   4262 		 * to load new gain values.
   4263 		 */
   4264 		sc->sc_stats.ast_per_rfgain++;
   4265 		ath_reset(&sc->sc_if);
   4266 	}
   4267 	if (!ath_hal_calibrate(ah, &sc->sc_curchan)) {
   4268 		DPRINTF(sc, ATH_DEBUG_ANY,
   4269 			"%s: calibration of channel %u failed\n",
   4270 			__func__, sc->sc_curchan.channel);
   4271 		sc->sc_stats.ast_per_calfail++;
   4272 	}
   4273 	callout_reset(&sc->sc_cal_ch, ath_calinterval * hz, ath_calibrate, sc);
   4274 	ATH_UNLOCK(sc);
   4275 }
   4276 
   4277 static int
   4278 ath_newstate(struct ieee80211com *ic, enum ieee80211_state nstate, int arg)
   4279 {
   4280 	struct ifnet *ifp = ic->ic_ifp;
   4281 	struct ath_softc *sc = ifp->if_softc;
   4282 	struct ath_hal *ah = sc->sc_ah;
   4283 	struct ieee80211_node *ni;
   4284 	int i, error;
   4285 	const u_int8_t *bssid;
   4286 	u_int32_t rfilt;
   4287 	static const HAL_LED_STATE leds[] = {
   4288 	    HAL_LED_INIT,	/* IEEE80211_S_INIT */
   4289 	    HAL_LED_SCAN,	/* IEEE80211_S_SCAN */
   4290 	    HAL_LED_AUTH,	/* IEEE80211_S_AUTH */
   4291 	    HAL_LED_ASSOC, 	/* IEEE80211_S_ASSOC */
   4292 	    HAL_LED_RUN, 	/* IEEE80211_S_RUN */
   4293 	};
   4294 
   4295 	DPRINTF(sc, ATH_DEBUG_STATE, "%s: %s -> %s\n", __func__,
   4296 		ieee80211_state_name[ic->ic_state],
   4297 		ieee80211_state_name[nstate]);
   4298 
   4299 	callout_stop(&sc->sc_scan_ch);
   4300 	callout_stop(&sc->sc_cal_ch);
   4301 	ath_hal_setledstate(ah, leds[nstate]);	/* set LED */
   4302 
   4303 	if (nstate == IEEE80211_S_INIT) {
   4304 		sc->sc_imask &= ~(HAL_INT_SWBA | HAL_INT_BMISS);
   4305 		/*
   4306 		 * NB: disable interrupts so we don't rx frames.
   4307 		 */
   4308 		ath_hal_intrset(ah, sc->sc_imask &~ HAL_INT_GLOBAL);
   4309 		/*
   4310 		 * Notify the rate control algorithm.
   4311 		 */
   4312 		ath_rate_newstate(sc, nstate);
   4313 		goto done;
   4314 	}
   4315 	ni = ic->ic_bss;
   4316 	error = ath_chan_set(sc, ni->ni_chan);
   4317 	if (error != 0)
   4318 		goto bad;
   4319 	rfilt = ath_calcrxfilter(sc, nstate);
   4320 	if (nstate == IEEE80211_S_SCAN)
   4321 		bssid = ifp->if_broadcastaddr;
   4322 	else
   4323 		bssid = ni->ni_bssid;
   4324 	ath_hal_setrxfilter(ah, rfilt);
   4325 	DPRINTF(sc, ATH_DEBUG_STATE, "%s: RX filter 0x%x bssid %s\n",
   4326 		 __func__, rfilt, ether_sprintf(bssid));
   4327 
   4328 	if (nstate == IEEE80211_S_RUN && ic->ic_opmode == IEEE80211_M_STA)
   4329 		ath_hal_setassocid(ah, bssid, ni->ni_associd);
   4330 	else
   4331 		ath_hal_setassocid(ah, bssid, 0);
   4332 	if (ic->ic_flags & IEEE80211_F_PRIVACY) {
   4333 		for (i = 0; i < IEEE80211_WEP_NKID; i++)
   4334 			if (ath_hal_keyisvalid(ah, i))
   4335 				ath_hal_keysetmac(ah, i, bssid);
   4336 	}
   4337 
   4338 	/*
   4339 	 * Notify the rate control algorithm so rates
   4340 	 * are setup should ath_beacon_alloc be called.
   4341 	 */
   4342 	ath_rate_newstate(sc, nstate);
   4343 
   4344 	if (ic->ic_opmode == IEEE80211_M_MONITOR) {
   4345 		/* nothing to do */;
   4346 	} else if (nstate == IEEE80211_S_RUN) {
   4347 		DPRINTF(sc, ATH_DEBUG_STATE,
   4348 			"%s(RUN): ic_flags=0x%08x iv=%d bssid=%s "
   4349 			"capinfo=0x%04x chan=%d\n"
   4350 			 , __func__
   4351 			 , ic->ic_flags
   4352 			 , ni->ni_intval
   4353 			 , ether_sprintf(ni->ni_bssid)
   4354 			 , ni->ni_capinfo
   4355 			 , ieee80211_chan2ieee(ic, ni->ni_chan));
   4356 
   4357 		switch (ic->ic_opmode) {
   4358 		case IEEE80211_M_HOSTAP:
   4359 		case IEEE80211_M_IBSS:
   4360 			/*
   4361 			 * Allocate and setup the beacon frame.
   4362 			 *
   4363 			 * Stop any previous beacon DMA.  This may be
   4364 			 * necessary, for example, when an ibss merge
   4365 			 * causes reconfiguration; there will be a state
   4366 			 * transition from RUN->RUN that means we may
   4367 			 * be called with beacon transmission active.
   4368 			 */
   4369 			ath_hal_stoptxdma(ah, sc->sc_bhalq);
   4370 			ath_beacon_free(sc);
   4371 			error = ath_beacon_alloc(sc, ni);
   4372 			if (error != 0)
   4373 				goto bad;
   4374 			break;
   4375 		case IEEE80211_M_STA:
   4376 			/*
   4377 			 * Allocate a key cache slot to the station.
   4378 			 */
   4379 			if ((ic->ic_flags & IEEE80211_F_PRIVACY) == 0 &&
   4380 			    sc->sc_hasclrkey &&
   4381 			    ni->ni_ucastkey.wk_keyix == IEEE80211_KEYIX_NONE)
   4382 				ath_setup_stationkey(ni);
   4383 			break;
   4384 		default:
   4385 			break;
   4386 		}
   4387 
   4388 		/*
   4389 		 * Configure the beacon and sleep timers.
   4390 		 */
   4391 		ath_beacon_config(sc);
   4392 	} else {
   4393 		ath_hal_intrset(ah,
   4394 			sc->sc_imask &~ (HAL_INT_SWBA | HAL_INT_BMISS));
   4395 		sc->sc_imask &= ~(HAL_INT_SWBA | HAL_INT_BMISS);
   4396 	}
   4397 done:
   4398 	/*
   4399 	 * Invoke the parent method to complete the work.
   4400 	 */
   4401 	error = sc->sc_newstate(ic, nstate, arg);
   4402 	/*
   4403 	 * Finally, start any timers.
   4404 	 */
   4405 	if (nstate == IEEE80211_S_RUN) {
   4406 		/* start periodic recalibration timer */
   4407 		callout_reset(&sc->sc_cal_ch, ath_calinterval * hz,
   4408 			ath_calibrate, sc);
   4409 	} else if (nstate == IEEE80211_S_SCAN) {
   4410 		/* start ap/neighbor scan timer */
   4411 		callout_reset(&sc->sc_scan_ch, (ath_dwelltime * hz) / 1000,
   4412 			ath_next_scan, sc);
   4413 	}
   4414 bad:
   4415 	return error;
   4416 }
   4417 
   4418 /*
   4419  * Allocate a key cache slot to the station so we can
   4420  * setup a mapping from key index to node. The key cache
   4421  * slot is needed for managing antenna state and for
   4422  * compression when stations do not use crypto.  We do
   4423  * it uniliaterally here; if crypto is employed this slot
   4424  * will be reassigned.
   4425  */
   4426 static void
   4427 ath_setup_stationkey(struct ieee80211_node *ni)
   4428 {
   4429 	struct ieee80211com *ic = ni->ni_ic;
   4430 	struct ath_softc *sc = ic->ic_ifp->if_softc;
   4431 	u_int16_t keyix;
   4432 
   4433 	keyix = ath_key_alloc(ic, &ni->ni_ucastkey);
   4434 	if (keyix == IEEE80211_KEYIX_NONE) {
   4435 		/*
   4436 		 * Key cache is full; we'll fall back to doing
   4437 		 * the more expensive lookup in software.  Note
   4438 		 * this also means no h/w compression.
   4439 		 */
   4440 		/* XXX msg+statistic */
   4441 	} else {
   4442 		ni->ni_ucastkey.wk_keyix = keyix;
   4443 		/* NB: this will create a pass-thru key entry */
   4444 		ath_keyset(sc, &ni->ni_ucastkey, ni->ni_macaddr, ic->ic_bss);
   4445 	}
   4446 }
   4447 
   4448 /*
   4449  * Setup driver-specific state for a newly associated node.
   4450  * Note that we're called also on a re-associate, the isnew
   4451  * param tells us if this is the first time or not.
   4452  */
   4453 static void
   4454 ath_newassoc(struct ieee80211com *ic, struct ieee80211_node *ni, int isnew)
   4455 {
   4456 	struct ath_softc *sc = ic->ic_ifp->if_softc;
   4457 
   4458 	ath_rate_newassoc(sc, ATH_NODE(ni), isnew);
   4459 	if (isnew &&
   4460 	    (ic->ic_flags & IEEE80211_F_PRIVACY) == 0 && sc->sc_hasclrkey) {
   4461 		KASSERT(ni->ni_ucastkey.wk_keyix == IEEE80211_KEYIX_NONE,
   4462 		    ("new assoc with a unicast key already setup (keyix %u)",
   4463 		    ni->ni_ucastkey.wk_keyix));
   4464 		ath_setup_stationkey(ni);
   4465 	}
   4466 }
   4467 
   4468 static int
   4469 ath_getchannels(struct ath_softc *sc, u_int cc,
   4470 	HAL_BOOL outdoor, HAL_BOOL xchanmode)
   4471 {
   4472 	struct ieee80211com *ic = &sc->sc_ic;
   4473 	struct ifnet *ifp = &sc->sc_if;
   4474 	struct ath_hal *ah = sc->sc_ah;
   4475 	HAL_CHANNEL *chans;
   4476 	int i, ix, nchan;
   4477 
   4478 	chans = malloc(IEEE80211_CHAN_MAX * sizeof(HAL_CHANNEL),
   4479 			M_TEMP, M_NOWAIT);
   4480 	if (chans == NULL) {
   4481 		if_printf(ifp, "unable to allocate channel table\n");
   4482 		return ENOMEM;
   4483 	}
   4484 	if (!ath_hal_init_channels(ah, chans, IEEE80211_CHAN_MAX, &nchan,
   4485 	    cc, HAL_MODE_ALL, outdoor, xchanmode)) {
   4486 		u_int32_t rd;
   4487 
   4488 		ath_hal_getregdomain(ah, &rd);
   4489 		if_printf(ifp, "unable to collect channel list from hal; "
   4490 			"regdomain likely %u country code %u\n", rd, cc);
   4491 		free(chans, M_TEMP);
   4492 		return EINVAL;
   4493 	}
   4494 
   4495 	/*
   4496 	 * Convert HAL channels to ieee80211 ones and insert
   4497 	 * them in the table according to their channel number.
   4498 	 */
   4499 	for (i = 0; i < nchan; i++) {
   4500 		HAL_CHANNEL *c = &chans[i];
   4501 		ix = ath_hal_mhz2ieee(c->channel, c->channelFlags);
   4502 		if (ix > IEEE80211_CHAN_MAX) {
   4503 			if_printf(ifp, "bad hal channel %u (%u/%x) ignored\n",
   4504 				ix, c->channel, c->channelFlags);
   4505 			continue;
   4506 		}
   4507 		DPRINTF(sc, ATH_DEBUG_ANY,
   4508 		    "%s: HAL channel %d/%d freq %d flags %#04x idx %d\n",
   4509 		    sc->sc_dev.dv_xname, i, nchan, c->channel, c->channelFlags,
   4510 		    ix);
   4511 		/* NB: flags are known to be compatible */
   4512 		if (ic->ic_channels[ix].ic_freq == 0) {
   4513 			ic->ic_channels[ix].ic_freq = c->channel;
   4514 			ic->ic_channels[ix].ic_flags = c->channelFlags;
   4515 		} else {
   4516 			/* channels overlap; e.g. 11g and 11b */
   4517 			ic->ic_channels[ix].ic_flags |= c->channelFlags;
   4518 		}
   4519 	}
   4520 	free(chans, M_TEMP);
   4521 	return 0;
   4522 }
   4523 
   4524 static void
   4525 ath_led_done(void *arg)
   4526 {
   4527 	struct ath_softc *sc = arg;
   4528 
   4529 	sc->sc_blinking = 0;
   4530 }
   4531 
   4532 /*
   4533  * Turn the LED off: flip the pin and then set a timer so no
   4534  * update will happen for the specified duration.
   4535  */
   4536 static void
   4537 ath_led_off(void *arg)
   4538 {
   4539 	struct ath_softc *sc = arg;
   4540 
   4541 	ath_hal_gpioset(sc->sc_ah, sc->sc_ledpin, !sc->sc_ledon);
   4542 	callout_reset(&sc->sc_ledtimer, sc->sc_ledoff, ath_led_done, sc);
   4543 }
   4544 
   4545 /*
   4546  * Blink the LED according to the specified on/off times.
   4547  */
   4548 static void
   4549 ath_led_blink(struct ath_softc *sc, int on, int off)
   4550 {
   4551 	DPRINTF(sc, ATH_DEBUG_LED, "%s: on %u off %u\n", __func__, on, off);
   4552 	ath_hal_gpioset(sc->sc_ah, sc->sc_ledpin, sc->sc_ledon);
   4553 	sc->sc_blinking = 1;
   4554 	sc->sc_ledoff = off;
   4555 	callout_reset(&sc->sc_ledtimer, on, ath_led_off, sc);
   4556 }
   4557 
   4558 static void
   4559 ath_led_event(struct ath_softc *sc, int event)
   4560 {
   4561 
   4562 	sc->sc_ledevent = ticks;	/* time of last event */
   4563 	if (sc->sc_blinking)		/* don't interrupt active blink */
   4564 		return;
   4565 	switch (event) {
   4566 	case ATH_LED_POLL:
   4567 		ath_led_blink(sc, sc->sc_hwmap[0].ledon,
   4568 			sc->sc_hwmap[0].ledoff);
   4569 		break;
   4570 	case ATH_LED_TX:
   4571 		ath_led_blink(sc, sc->sc_hwmap[sc->sc_txrate].ledon,
   4572 			sc->sc_hwmap[sc->sc_txrate].ledoff);
   4573 		break;
   4574 	case ATH_LED_RX:
   4575 		ath_led_blink(sc, sc->sc_hwmap[sc->sc_rxrate].ledon,
   4576 			sc->sc_hwmap[sc->sc_rxrate].ledoff);
   4577 		break;
   4578 	}
   4579 }
   4580 
   4581 static void
   4582 ath_update_txpow(struct ath_softc *sc)
   4583 {
   4584 	struct ieee80211com *ic = &sc->sc_ic;
   4585 	struct ath_hal *ah = sc->sc_ah;
   4586 	u_int32_t txpow;
   4587 
   4588 	if (sc->sc_curtxpow != ic->ic_txpowlimit) {
   4589 		ath_hal_settxpowlimit(ah, ic->ic_txpowlimit);
   4590 		/* read back in case value is clamped */
   4591 		ath_hal_gettxpowlimit(ah, &txpow);
   4592 		ic->ic_txpowlimit = sc->sc_curtxpow = txpow;
   4593 	}
   4594 	/*
   4595 	 * Fetch max tx power level for status requests.
   4596 	 */
   4597 	ath_hal_getmaxtxpow(sc->sc_ah, &txpow);
   4598 	ic->ic_bss->ni_txpower = txpow;
   4599 }
   4600 
   4601 static int
   4602 ath_rate_setup(struct ath_softc *sc, u_int mode)
   4603 {
   4604 	struct ath_hal *ah = sc->sc_ah;
   4605 	struct ieee80211com *ic = &sc->sc_ic;
   4606 	const HAL_RATE_TABLE *rt;
   4607 	struct ieee80211_rateset *rs;
   4608 	int i, maxrates;
   4609 
   4610 	switch (mode) {
   4611 	case IEEE80211_MODE_11A:
   4612 		sc->sc_rates[mode] = ath_hal_getratetable(ah, HAL_MODE_11A);
   4613 		break;
   4614 	case IEEE80211_MODE_11B:
   4615 		sc->sc_rates[mode] = ath_hal_getratetable(ah, HAL_MODE_11B);
   4616 		break;
   4617 	case IEEE80211_MODE_11G:
   4618 		sc->sc_rates[mode] = ath_hal_getratetable(ah, HAL_MODE_11G);
   4619 		break;
   4620 	case IEEE80211_MODE_TURBO_A:
   4621 		sc->sc_rates[mode] = ath_hal_getratetable(ah, HAL_MODE_TURBO);
   4622 		break;
   4623 	case IEEE80211_MODE_TURBO_G:
   4624 		sc->sc_rates[mode] = ath_hal_getratetable(ah, HAL_MODE_108G);
   4625 		break;
   4626 	default:
   4627 		DPRINTF(sc, ATH_DEBUG_ANY, "%s: invalid mode %u\n",
   4628 			__func__, mode);
   4629 		return 0;
   4630 	}
   4631 	rt = sc->sc_rates[mode];
   4632 	if (rt == NULL)
   4633 		return 0;
   4634 	if (rt->rateCount > IEEE80211_RATE_MAXSIZE) {
   4635 		DPRINTF(sc, ATH_DEBUG_ANY,
   4636 			"%s: rate table too small (%u > %u)\n",
   4637 			__func__, rt->rateCount, IEEE80211_RATE_MAXSIZE);
   4638 		maxrates = IEEE80211_RATE_MAXSIZE;
   4639 	} else
   4640 		maxrates = rt->rateCount;
   4641 	rs = &ic->ic_sup_rates[mode];
   4642 	for (i = 0; i < maxrates; i++)
   4643 		rs->rs_rates[i] = rt->info[i].dot11Rate;
   4644 	rs->rs_nrates = maxrates;
   4645 	return 1;
   4646 }
   4647 
   4648 static void
   4649 ath_setcurmode(struct ath_softc *sc, enum ieee80211_phymode mode)
   4650 {
   4651 #define	N(a)	(sizeof(a)/sizeof(a[0]))
   4652 	/* NB: on/off times from the Atheros NDIS driver, w/ permission */
   4653 	static const struct {
   4654 		u_int		rate;		/* tx/rx 802.11 rate */
   4655 		u_int16_t	timeOn;		/* LED on time (ms) */
   4656 		u_int16_t	timeOff;	/* LED off time (ms) */
   4657 	} blinkrates[] = {
   4658 		{ 108,  40,  10 },
   4659 		{  96,  44,  11 },
   4660 		{  72,  50,  13 },
   4661 		{  48,  57,  14 },
   4662 		{  36,  67,  16 },
   4663 		{  24,  80,  20 },
   4664 		{  22, 100,  25 },
   4665 		{  18, 133,  34 },
   4666 		{  12, 160,  40 },
   4667 		{  10, 200,  50 },
   4668 		{   6, 240,  58 },
   4669 		{   4, 267,  66 },
   4670 		{   2, 400, 100 },
   4671 		{   0, 500, 130 },
   4672 	};
   4673 	const HAL_RATE_TABLE *rt;
   4674 	int i, j;
   4675 
   4676 	memset(sc->sc_rixmap, 0xff, sizeof(sc->sc_rixmap));
   4677 	rt = sc->sc_rates[mode];
   4678 	KASSERT(rt != NULL, ("no h/w rate set for phy mode %u", mode));
   4679 	for (i = 0; i < rt->rateCount; i++)
   4680 		sc->sc_rixmap[rt->info[i].dot11Rate & IEEE80211_RATE_VAL] = i;
   4681 	memset(sc->sc_hwmap, 0, sizeof(sc->sc_hwmap));
   4682 	for (i = 0; i < 32; i++) {
   4683 		u_int8_t ix = rt->rateCodeToIndex[i];
   4684 		if (ix == 0xff) {
   4685 			sc->sc_hwmap[i].ledon = (500 * hz) / 1000;
   4686 			sc->sc_hwmap[i].ledoff = (130 * hz) / 1000;
   4687 			continue;
   4688 		}
   4689 		sc->sc_hwmap[i].ieeerate =
   4690 			rt->info[ix].dot11Rate & IEEE80211_RATE_VAL;
   4691 		sc->sc_hwmap[i].txflags = IEEE80211_RADIOTAP_F_DATAPAD;
   4692 		if (rt->info[ix].shortPreamble ||
   4693 		    rt->info[ix].phy == IEEE80211_T_OFDM)
   4694 			sc->sc_hwmap[i].txflags |= IEEE80211_RADIOTAP_F_SHORTPRE;
   4695 		/* NB: receive frames include FCS */
   4696 		sc->sc_hwmap[i].rxflags = sc->sc_hwmap[i].txflags |
   4697 			IEEE80211_RADIOTAP_F_FCS;
   4698 		/* setup blink rate table to avoid per-packet lookup */
   4699 		for (j = 0; j < N(blinkrates)-1; j++)
   4700 			if (blinkrates[j].rate == sc->sc_hwmap[i].ieeerate)
   4701 				break;
   4702 		/* NB: this uses the last entry if the rate isn't found */
   4703 		/* XXX beware of overlow */
   4704 		sc->sc_hwmap[i].ledon = (blinkrates[j].timeOn * hz) / 1000;
   4705 		sc->sc_hwmap[i].ledoff = (blinkrates[j].timeOff * hz) / 1000;
   4706 	}
   4707 	sc->sc_currates = rt;
   4708 	sc->sc_curmode = mode;
   4709 	/*
   4710 	 * All protection frames are transmited at 2Mb/s for
   4711 	 * 11g, otherwise at 1Mb/s.
   4712 	 * XXX select protection rate index from rate table.
   4713 	 */
   4714 	sc->sc_protrix = (mode == IEEE80211_MODE_11G ? 1 : 0);
   4715 	/* NB: caller is responsible for reseting rate control state */
   4716 #undef N
   4717 }
   4718 
   4719 #ifdef AR_DEBUG
   4720 static void
   4721 ath_printrxbuf(struct ath_buf *bf, int done)
   4722 {
   4723 	struct ath_desc *ds;
   4724 	int i;
   4725 
   4726 	for (i = 0, ds = bf->bf_desc; i < bf->bf_nseg; i++, ds++) {
   4727 		printf("R%d (%p %p) %08x %08x %08x %08x %08x %08x %c\n",
   4728 		    i, ds, (struct ath_desc *)bf->bf_daddr + i,
   4729 		    ds->ds_link, ds->ds_data,
   4730 		    ds->ds_ctl0, ds->ds_ctl1,
   4731 		    ds->ds_hw[0], ds->ds_hw[1],
   4732 		    !done ? ' ' : (ds->ds_rxstat.rs_status == 0) ? '*' : '!');
   4733 	}
   4734 }
   4735 
   4736 static void
   4737 ath_printtxbuf(struct ath_buf *bf, int done)
   4738 {
   4739 	struct ath_desc *ds;
   4740 	int i;
   4741 
   4742 	for (i = 0, ds = bf->bf_desc; i < bf->bf_nseg; i++, ds++) {
   4743 		printf("T%d (%p %p) %08x %08x %08x %08x %08x %08x %08x %08x %c\n",
   4744 		    i, ds, (struct ath_desc *)bf->bf_daddr + i,
   4745 		    ds->ds_link, ds->ds_data,
   4746 		    ds->ds_ctl0, ds->ds_ctl1,
   4747 		    ds->ds_hw[0], ds->ds_hw[1], ds->ds_hw[2], ds->ds_hw[3],
   4748 		    !done ? ' ' : (ds->ds_txstat.ts_status == 0) ? '*' : '!');
   4749 	}
   4750 }
   4751 #endif /* AR_DEBUG */
   4752 
   4753 static void
   4754 ath_watchdog(struct ifnet *ifp)
   4755 {
   4756 	struct ath_softc *sc = ifp->if_softc;
   4757 	struct ieee80211com *ic = &sc->sc_ic;
   4758 
   4759 	ifp->if_timer = 0;
   4760 	if ((ifp->if_flags & IFF_RUNNING) == 0 || sc->sc_invalid)
   4761 		return;
   4762 	if (sc->sc_tx_timer) {
   4763 		if (--sc->sc_tx_timer == 0) {
   4764 			if_printf(ifp, "device timeout\n");
   4765 			ath_reset(ifp);
   4766 			ifp->if_oerrors++;
   4767 			sc->sc_stats.ast_watchdog++;
   4768 		} else
   4769 			ifp->if_timer = 1;
   4770 	}
   4771 	ieee80211_watchdog(ic);
   4772 }
   4773 
   4774 /*
   4775  * Diagnostic interface to the HAL.  This is used by various
   4776  * tools to do things like retrieve register contents for
   4777  * debugging.  The mechanism is intentionally opaque so that
   4778  * it can change frequently w/o concern for compatiblity.
   4779  */
   4780 static int
   4781 ath_ioctl_diag(struct ath_softc *sc, struct ath_diag *ad)
   4782 {
   4783 	struct ath_hal *ah = sc->sc_ah;
   4784 	u_int id = ad->ad_id & ATH_DIAG_ID;
   4785 	void *indata = NULL;
   4786 	void *outdata = NULL;
   4787 	u_int32_t insize = ad->ad_in_size;
   4788 	u_int32_t outsize = ad->ad_out_size;
   4789 	int error = 0;
   4790 
   4791 	if (ad->ad_id & ATH_DIAG_IN) {
   4792 		/*
   4793 		 * Copy in data.
   4794 		 */
   4795 		indata = malloc(insize, M_TEMP, M_NOWAIT);
   4796 		if (indata == NULL) {
   4797 			error = ENOMEM;
   4798 			goto bad;
   4799 		}
   4800 		error = copyin(ad->ad_in_data, indata, insize);
   4801 		if (error)
   4802 			goto bad;
   4803 	}
   4804 	if (ad->ad_id & ATH_DIAG_DYN) {
   4805 		/*
   4806 		 * Allocate a buffer for the results (otherwise the HAL
   4807 		 * returns a pointer to a buffer where we can read the
   4808 		 * results).  Note that we depend on the HAL leaving this
   4809 		 * pointer for us to use below in reclaiming the buffer;
   4810 		 * may want to be more defensive.
   4811 		 */
   4812 		outdata = malloc(outsize, M_TEMP, M_NOWAIT);
   4813 		if (outdata == NULL) {
   4814 			error = ENOMEM;
   4815 			goto bad;
   4816 		}
   4817 	}
   4818 	if (ath_hal_getdiagstate(ah, id, indata, insize, &outdata, &outsize)) {
   4819 		if (outsize < ad->ad_out_size)
   4820 			ad->ad_out_size = outsize;
   4821 		if (outdata != NULL)
   4822 			error = copyout(outdata, ad->ad_out_data,
   4823 					ad->ad_out_size);
   4824 	} else {
   4825 		error = EINVAL;
   4826 	}
   4827 bad:
   4828 	if ((ad->ad_id & ATH_DIAG_IN) && indata != NULL)
   4829 		free(indata, M_TEMP);
   4830 	if ((ad->ad_id & ATH_DIAG_DYN) && outdata != NULL)
   4831 		free(outdata, M_TEMP);
   4832 	return error;
   4833 }
   4834 
   4835 static int
   4836 ath_ioctl(struct ifnet *ifp, u_long cmd, caddr_t data)
   4837 {
   4838 #define	IS_RUNNING(ifp) \
   4839 	((ifp->if_flags & (IFF_RUNNING|IFF_UP)) == (IFF_RUNNING|IFF_UP))
   4840 	struct ath_softc *sc = ifp->if_softc;
   4841 	struct ieee80211com *ic = &sc->sc_ic;
   4842 	struct ifreq *ifr = (struct ifreq *)data;
   4843 	int error = 0;
   4844 
   4845 	ATH_LOCK(sc);
   4846 	switch (cmd) {
   4847 	case SIOCSIFFLAGS:
   4848 		if (IS_RUNNING(ifp)) {
   4849 			/*
   4850 			 * To avoid rescanning another access point,
   4851 			 * do not call ath_init() here.  Instead,
   4852 			 * only reflect promisc mode settings.
   4853 			 */
   4854 			ath_mode_init(sc);
   4855 		} else if (ifp->if_flags & IFF_UP) {
   4856 			/*
   4857 			 * Beware of being called during attach/detach
   4858 			 * to reset promiscuous mode.  In that case we
   4859 			 * will still be marked UP but not RUNNING.
   4860 			 * However trying to re-init the interface
   4861 			 * is the wrong thing to do as we've already
   4862 			 * torn down much of our state.  There's
   4863 			 * probably a better way to deal with this.
   4864 			 */
   4865 			if (!sc->sc_invalid && ic->ic_bss != NULL)
   4866 				ath_init(sc);	/* XXX lose error */
   4867 		} else
   4868 			ath_stop_locked(ifp, 1);
   4869 		break;
   4870 	case SIOCADDMULTI:
   4871 	case SIOCDELMULTI:
   4872 		error = (cmd == SIOCADDMULTI) ?
   4873 		    ether_addmulti(ifr, &sc->sc_ec) :
   4874 		    ether_delmulti(ifr, &sc->sc_ec);
   4875 		if (error == ENETRESET) {
   4876 			if (ifp->if_flags & IFF_RUNNING)
   4877 				ath_mode_init(sc);
   4878 			error = 0;
   4879 		}
   4880 		break;
   4881 	case SIOCGATHSTATS:
   4882 		/* NB: embed these numbers to get a consistent view */
   4883 		sc->sc_stats.ast_tx_packets = ifp->if_opackets;
   4884 		sc->sc_stats.ast_rx_packets = ifp->if_ipackets;
   4885 		sc->sc_stats.ast_rx_rssi = ieee80211_getrssi(ic);
   4886 		ATH_UNLOCK(sc);
   4887 		/*
   4888 		 * NB: Drop the softc lock in case of a page fault;
   4889 		 * we'll accept any potential inconsisentcy in the
   4890 		 * statistics.  The alternative is to copy the data
   4891 		 * to a local structure.
   4892 		 */
   4893 		return copyout(&sc->sc_stats,
   4894 				ifr->ifr_data, sizeof (sc->sc_stats));
   4895 	case SIOCGATHDIAG:
   4896 		error = ath_ioctl_diag(sc, (struct ath_diag *) ifr);
   4897 		break;
   4898 	default:
   4899 		error = ieee80211_ioctl(ic, cmd, data);
   4900 		if (error == ENETRESET) {
   4901 			if (IS_RUNNING(ifp) &&
   4902 			    ic->ic_roaming != IEEE80211_ROAMING_MANUAL)
   4903 				ath_init(sc);	/* XXX lose error */
   4904 			error = 0;
   4905 		}
   4906 		if (error == ERESTART)
   4907 			error = IS_RUNNING(ifp) ? ath_reset(ifp) : 0;
   4908 		break;
   4909 	}
   4910 	ATH_UNLOCK(sc);
   4911 	return error;
   4912 #undef IS_RUNNING
   4913 }
   4914 
   4915 static void
   4916 ath_bpfattach(struct ath_softc *sc)
   4917 {
   4918 	struct ifnet *ifp = &sc->sc_if;
   4919 
   4920 	bpfattach2(ifp, DLT_IEEE802_11_RADIO,
   4921 		sizeof(struct ieee80211_frame) + sizeof(sc->sc_tx_th),
   4922 		&sc->sc_drvbpf);
   4923 	/*
   4924 	 * Initialize constant fields.
   4925 	 * XXX make header lengths a multiple of 32-bits so subsequent
   4926 	 *     headers are properly aligned; this is a kludge to keep
   4927 	 *     certain applications happy.
   4928 	 *
   4929 	 * NB: the channel is setup each time we transition to the
   4930 	 *     RUN state to avoid filling it in for each frame.
   4931 	 */
   4932 	sc->sc_tx_th_len = roundup(sizeof(sc->sc_tx_th), sizeof(u_int32_t));
   4933 	sc->sc_tx_th.wt_ihdr.it_len = htole16(sc->sc_tx_th_len);
   4934 	sc->sc_tx_th.wt_ihdr.it_present = htole32(ATH_TX_RADIOTAP_PRESENT);
   4935 
   4936 	sc->sc_rx_th_len = roundup(sizeof(sc->sc_rx_th), sizeof(u_int32_t));
   4937 	sc->sc_rx_th.wr_ihdr.it_len = htole16(sc->sc_rx_th_len);
   4938 	sc->sc_rx_th.wr_ihdr.it_present = htole32(ATH_RX_RADIOTAP_PRESENT);
   4939 }
   4940 
   4941 /*
   4942  * Announce various information on device/driver attach.
   4943  */
   4944 static void
   4945 ath_announce(struct ath_softc *sc)
   4946 {
   4947 #define	HAL_MODE_DUALBAND	(HAL_MODE_11A|HAL_MODE_11B)
   4948 	struct ifnet *ifp = &sc->sc_if;
   4949 	struct ath_hal *ah = sc->sc_ah;
   4950 	u_int modes, cc;
   4951 
   4952 	if_printf(ifp, "mac %d.%d phy %d.%d",
   4953 		ah->ah_macVersion, ah->ah_macRev,
   4954 		ah->ah_phyRev >> 4, ah->ah_phyRev & 0xf);
   4955 	/*
   4956 	 * Print radio revision(s).  We check the wireless modes
   4957 	 * to avoid falsely printing revs for inoperable parts.
   4958 	 * Dual-band radio revs are returned in the 5Ghz rev number.
   4959 	 */
   4960 	ath_hal_getcountrycode(ah, &cc);
   4961 	modes = ath_hal_getwirelessmodes(ah, cc);
   4962 	if ((modes & HAL_MODE_DUALBAND) == HAL_MODE_DUALBAND) {
   4963 		if (ah->ah_analog5GhzRev && ah->ah_analog2GhzRev)
   4964 			printf(" 5ghz radio %d.%d 2ghz radio %d.%d",
   4965 				ah->ah_analog5GhzRev >> 4,
   4966 				ah->ah_analog5GhzRev & 0xf,
   4967 				ah->ah_analog2GhzRev >> 4,
   4968 				ah->ah_analog2GhzRev & 0xf);
   4969 		else
   4970 			printf(" radio %d.%d", ah->ah_analog5GhzRev >> 4,
   4971 				ah->ah_analog5GhzRev & 0xf);
   4972 	} else
   4973 		printf(" radio %d.%d", ah->ah_analog5GhzRev >> 4,
   4974 			ah->ah_analog5GhzRev & 0xf);
   4975 	printf("\n");
   4976 	if (bootverbose) {
   4977 		int i;
   4978 		for (i = 0; i <= WME_AC_VO; i++) {
   4979 			struct ath_txq *txq = sc->sc_ac2q[i];
   4980 			if_printf(ifp, "Use hw queue %u for %s traffic\n",
   4981 				txq->axq_qnum, ieee80211_wme_acnames[i]);
   4982 		}
   4983 		if_printf(ifp, "Use hw queue %u for CAB traffic\n",
   4984 			sc->sc_cabq->axq_qnum);
   4985 		if_printf(ifp, "Use hw queue %u for beacons\n", sc->sc_bhalq);
   4986 	}
   4987 #undef HAL_MODE_DUALBAND
   4988 }
   4989