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