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