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