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