xref: /freebsd/sys/dev/ath/if_ath.c (revision 4a5216a6dc0c3ce4cf5f2d3ee8af0c3ff3402c4f)
1 /*-
2  * Copyright (c) 2002-2008 Sam Leffler, Errno Consulting
3  * All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer,
10  *    without modification.
11  * 2. Redistributions in binary form must reproduce at minimum a disclaimer
12  *    similar to the "NO WARRANTY" disclaimer below ("Disclaimer") and any
13  *    redistribution must be conditioned upon including a substantially
14  *    similar Disclaimer requirement for further binary redistribution.
15  *
16  * NO WARRANTY
17  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
18  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
19  * LIMITED TO, THE IMPLIED WARRANTIES OF NONINFRINGEMENT, MERCHANTIBILITY
20  * AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
21  * THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR SPECIAL, EXEMPLARY,
22  * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
23  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
24  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER
25  * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
26  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
27  * THE POSSIBILITY OF SUCH DAMAGES.
28  */
29 
30 #include <sys/cdefs.h>
31 __FBSDID("$FreeBSD$");
32 
33 /*
34  * Driver for the Atheros Wireless LAN controller.
35  *
36  * This software is derived from work of Atsushi Onoe; his contribution
37  * is greatly appreciated.
38  */
39 
40 #include "opt_inet.h"
41 #include "opt_ath.h"
42 
43 #include <sys/param.h>
44 #include <sys/systm.h>
45 #include <sys/sysctl.h>
46 #include <sys/mbuf.h>
47 #include <sys/malloc.h>
48 #include <sys/lock.h>
49 #include <sys/mutex.h>
50 #include <sys/kernel.h>
51 #include <sys/socket.h>
52 #include <sys/sockio.h>
53 #include <sys/errno.h>
54 #include <sys/callout.h>
55 #include <sys/bus.h>
56 #include <sys/endian.h>
57 #include <sys/kthread.h>
58 #include <sys/taskqueue.h>
59 
60 #include <machine/bus.h>
61 
62 #include <net/if.h>
63 #include <net/if_dl.h>
64 #include <net/if_media.h>
65 #include <net/if_types.h>
66 #include <net/if_arp.h>
67 #include <net/ethernet.h>
68 #include <net/if_llc.h>
69 
70 #include <net80211/ieee80211_var.h>
71 
72 #include <net/bpf.h>
73 
74 #ifdef INET
75 #include <netinet/in.h>
76 #include <netinet/if_ether.h>
77 #endif
78 
79 #include <dev/ath/if_athvar.h>
80 #include <contrib/dev/ath/ah_desc.h>
81 #include <contrib/dev/ath/ah_devid.h>		/* XXX for softled */
82 
83 #ifdef ATH_TX99_DIAG
84 #include <dev/ath/ath_tx99/ath_tx99.h>
85 #endif
86 
87 /*
88  * We require a HAL w/ the changes for split tx/rx MIC.
89  */
90 CTASSERT(HAL_ABI_VERSION > 0x06052200);
91 
92 /*
93  * ATH_BCBUF determines the number of vap's that can transmit
94  * beacons and also (currently) the number of vap's that can
95  * have unique mac addresses/bssid.  When staggering beacons
96  * 4 is probably a good max as otherwise the beacons become
97  * very closely spaced and there is limited time for cab q traffic
98  * to go out.  You can burst beacons instead but that is not good
99  * for stations in power save and at some point you really want
100  * another radio (and channel).
101  *
102  * The limit on the number of mac addresses is tied to our use of
103  * the U/L bit and tracking addresses in a byte; it would be
104  * worthwhile to allow more for applications like proxy sta.
105  */
106 CTASSERT(ATH_BCBUF <= 8);
107 
108 /* unaligned little endian access */
109 #define LE_READ_2(p)							\
110 	((u_int16_t)							\
111 	 ((((u_int8_t *)(p))[0]      ) | (((u_int8_t *)(p))[1] <<  8)))
112 #define LE_READ_4(p)							\
113 	((u_int32_t)							\
114 	 ((((u_int8_t *)(p))[0]      ) | (((u_int8_t *)(p))[1] <<  8) |	\
115 	  (((u_int8_t *)(p))[2] << 16) | (((u_int8_t *)(p))[3] << 24)))
116 
117 enum {
118 	ATH_LED_TX,
119 	ATH_LED_RX,
120 	ATH_LED_POLL,
121 };
122 
123 static struct ieee80211vap *ath_vap_create(struct ieee80211com *,
124 		    const char name[IFNAMSIZ], int unit, int opmode,
125 		    int flags, const uint8_t bssid[IEEE80211_ADDR_LEN],
126 		    const uint8_t mac[IEEE80211_ADDR_LEN]);
127 static void	ath_vap_delete(struct ieee80211vap *);
128 static void	ath_init(void *);
129 static void	ath_stop_locked(struct ifnet *);
130 static void	ath_stop(struct ifnet *);
131 static void	ath_start(struct ifnet *);
132 static int	ath_reset(struct ifnet *);
133 static int	ath_reset_vap(struct ieee80211vap *, u_long);
134 static int	ath_media_change(struct ifnet *);
135 static void	ath_watchdog(struct ifnet *);
136 static int	ath_ioctl(struct ifnet *, u_long, caddr_t);
137 static void	ath_fatal_proc(void *, int);
138 static void	ath_rxorn_proc(void *, int);
139 static void	ath_bmiss_vap(struct ieee80211vap *);
140 static void	ath_bmiss_proc(void *, int);
141 static int	ath_keyset(struct ath_softc *, const struct ieee80211_key *,
142 			struct ieee80211_node *);
143 static int	ath_key_alloc(struct ieee80211vap *,
144 			struct ieee80211_key *,
145 			ieee80211_keyix *, ieee80211_keyix *);
146 static int	ath_key_delete(struct ieee80211vap *,
147 			const struct ieee80211_key *);
148 static int	ath_key_set(struct ieee80211vap *, const struct ieee80211_key *,
149 			const u_int8_t mac[IEEE80211_ADDR_LEN]);
150 static void	ath_key_update_begin(struct ieee80211vap *);
151 static void	ath_key_update_end(struct ieee80211vap *);
152 static void	ath_update_mcast(struct ifnet *);
153 static void	ath_update_promisc(struct ifnet *);
154 static void	ath_mode_init(struct ath_softc *);
155 static void	ath_setslottime(struct ath_softc *);
156 static void	ath_updateslot(struct ifnet *);
157 static int	ath_beaconq_setup(struct ath_hal *);
158 static int	ath_beacon_alloc(struct ath_softc *, struct ieee80211_node *);
159 static void	ath_beacon_update(struct ieee80211vap *, int item);
160 static void	ath_beacon_setup(struct ath_softc *, struct ath_buf *);
161 static void	ath_beacon_proc(void *, int);
162 static struct ath_buf *ath_beacon_generate(struct ath_softc *,
163 			struct ieee80211vap *);
164 static void	ath_bstuck_proc(void *, int);
165 static void	ath_beacon_return(struct ath_softc *, struct ath_buf *);
166 static void	ath_beacon_free(struct ath_softc *);
167 static void	ath_beacon_config(struct ath_softc *, struct ieee80211vap *);
168 static void	ath_descdma_cleanup(struct ath_softc *sc,
169 			struct ath_descdma *, ath_bufhead *);
170 static int	ath_desc_alloc(struct ath_softc *);
171 static void	ath_desc_free(struct ath_softc *);
172 static struct ieee80211_node *ath_node_alloc(struct ieee80211vap *,
173 			const uint8_t [IEEE80211_ADDR_LEN]);
174 static void	ath_node_free(struct ieee80211_node *);
175 static void	ath_node_getsignal(const struct ieee80211_node *,
176 			int8_t *, int8_t *);
177 static int	ath_rxbuf_init(struct ath_softc *, struct ath_buf *);
178 static void	ath_recv_mgmt(struct ieee80211_node *ni, struct mbuf *m,
179 			int subtype, int rssi, int noise, u_int32_t rstamp);
180 static void	ath_setdefantenna(struct ath_softc *, u_int);
181 static void	ath_rx_proc(void *, int);
182 static void	ath_txq_init(struct ath_softc *sc, struct ath_txq *, int);
183 static struct ath_txq *ath_txq_setup(struct ath_softc*, int qtype, int subtype);
184 static int	ath_tx_setup(struct ath_softc *, int, int);
185 static int	ath_wme_update(struct ieee80211com *);
186 static void	ath_tx_cleanupq(struct ath_softc *, struct ath_txq *);
187 static void	ath_tx_cleanup(struct ath_softc *);
188 static void	ath_freetx(struct mbuf *);
189 static int	ath_tx_start(struct ath_softc *, struct ieee80211_node *,
190 			     struct ath_buf *, struct mbuf *);
191 static void	ath_tx_proc_q0(void *, int);
192 static void	ath_tx_proc_q0123(void *, int);
193 static void	ath_tx_proc(void *, int);
194 static void	ath_tx_draintxq(struct ath_softc *, struct ath_txq *);
195 static int	ath_chan_set(struct ath_softc *, struct ieee80211_channel *);
196 static void	ath_draintxq(struct ath_softc *);
197 static void	ath_stoprecv(struct ath_softc *);
198 static int	ath_startrecv(struct ath_softc *);
199 static void	ath_chan_change(struct ath_softc *, struct ieee80211_channel *);
200 static void	ath_scan_start(struct ieee80211com *);
201 static void	ath_scan_end(struct ieee80211com *);
202 static void	ath_set_channel(struct ieee80211com *);
203 static void	ath_calibrate(void *);
204 static int	ath_newstate(struct ieee80211vap *, enum ieee80211_state, int);
205 static void	ath_setup_stationkey(struct ieee80211_node *);
206 static void	ath_newassoc(struct ieee80211_node *, int);
207 static int	ath_setregdomain(struct ieee80211com *,
208 		    struct ieee80211_regdomain *, int,
209 		    struct ieee80211_channel []);
210 static void	ath_getradiocaps(struct ieee80211com *, int *,
211 		    struct ieee80211_channel []);
212 static int	ath_getchannels(struct ath_softc *);
213 static void	ath_led_event(struct ath_softc *, int);
214 
215 static int	ath_rate_setup(struct ath_softc *, u_int mode);
216 static void	ath_setcurmode(struct ath_softc *, enum ieee80211_phymode);
217 
218 static void	ath_sysctlattach(struct ath_softc *);
219 static int	ath_raw_xmit(struct ieee80211_node *,
220 			struct mbuf *, const struct ieee80211_bpf_params *);
221 static void	ath_bpfattach(struct ath_softc *);
222 static void	ath_announce(struct ath_softc *);
223 
224 SYSCTL_DECL(_hw_ath);
225 
226 /* XXX validate sysctl values */
227 static	int ath_calinterval = 30;		/* calibrate every 30 secs */
228 SYSCTL_INT(_hw_ath, OID_AUTO, calibrate, CTLFLAG_RW, &ath_calinterval,
229 	    0, "chip calibration interval (secs)");
230 
231 static	int ath_rxbuf = ATH_RXBUF;		/* # rx buffers to allocate */
232 SYSCTL_INT(_hw_ath, OID_AUTO, rxbuf, CTLFLAG_RW, &ath_rxbuf,
233 	    0, "rx buffers allocated");
234 TUNABLE_INT("hw.ath.rxbuf", &ath_rxbuf);
235 static	int ath_txbuf = ATH_TXBUF;		/* # tx buffers to allocate */
236 SYSCTL_INT(_hw_ath, OID_AUTO, txbuf, CTLFLAG_RW, &ath_txbuf,
237 	    0, "tx buffers allocated");
238 TUNABLE_INT("hw.ath.txbuf", &ath_txbuf);
239 
240 #ifdef ATH_DEBUG
241 static	int ath_debug = 0;
242 SYSCTL_INT(_hw_ath, OID_AUTO, debug, CTLFLAG_RW, &ath_debug,
243 	    0, "control debugging printfs");
244 TUNABLE_INT("hw.ath.debug", &ath_debug);
245 enum {
246 	ATH_DEBUG_XMIT		= 0x00000001,	/* basic xmit operation */
247 	ATH_DEBUG_XMIT_DESC	= 0x00000002,	/* xmit descriptors */
248 	ATH_DEBUG_RECV		= 0x00000004,	/* basic recv operation */
249 	ATH_DEBUG_RECV_DESC	= 0x00000008,	/* recv descriptors */
250 	ATH_DEBUG_RATE		= 0x00000010,	/* rate control */
251 	ATH_DEBUG_RESET		= 0x00000020,	/* reset processing */
252 	ATH_DEBUG_MODE		= 0x00000040,	/* mode init/setup */
253 	ATH_DEBUG_BEACON 	= 0x00000080,	/* beacon handling */
254 	ATH_DEBUG_WATCHDOG 	= 0x00000100,	/* watchdog timeout */
255 	ATH_DEBUG_INTR		= 0x00001000,	/* ISR */
256 	ATH_DEBUG_TX_PROC	= 0x00002000,	/* tx ISR proc */
257 	ATH_DEBUG_RX_PROC	= 0x00004000,	/* rx ISR proc */
258 	ATH_DEBUG_BEACON_PROC	= 0x00008000,	/* beacon ISR proc */
259 	ATH_DEBUG_CALIBRATE	= 0x00010000,	/* periodic calibration */
260 	ATH_DEBUG_KEYCACHE	= 0x00020000,	/* key cache management */
261 	ATH_DEBUG_STATE		= 0x00040000,	/* 802.11 state transitions */
262 	ATH_DEBUG_NODE		= 0x00080000,	/* node management */
263 	ATH_DEBUG_LED		= 0x00100000,	/* led management */
264 	ATH_DEBUG_FF		= 0x00200000,	/* fast frames */
265 	ATH_DEBUG_DFS		= 0x00400000,	/* DFS processing */
266 	ATH_DEBUG_FATAL		= 0x80000000,	/* fatal errors */
267 	ATH_DEBUG_ANY		= 0xffffffff
268 };
269 #define	IFF_DUMPPKTS(sc, m) \
270 	((sc->sc_debug & (m)) || \
271 	    (sc->sc_ifp->if_flags & (IFF_DEBUG|IFF_LINK2)) == (IFF_DEBUG|IFF_LINK2))
272 #define	DPRINTF(sc, m, fmt, ...) do {				\
273 	if (sc->sc_debug & (m))					\
274 		printf(fmt, __VA_ARGS__);			\
275 } while (0)
276 #define	KEYPRINTF(sc, ix, hk, mac) do {				\
277 	if (sc->sc_debug & ATH_DEBUG_KEYCACHE)			\
278 		ath_keyprint(sc, __func__, ix, hk, mac);	\
279 } while (0)
280 static	void ath_printrxbuf(const struct ath_buf *bf, u_int ix, int);
281 static	void ath_printtxbuf(const struct ath_buf *bf, u_int qnum, u_int ix, int done);
282 #else
283 #define	IFF_DUMPPKTS(sc, m) \
284 	((sc->sc_ifp->if_flags & (IFF_DEBUG|IFF_LINK2)) == (IFF_DEBUG|IFF_LINK2))
285 #define	DPRINTF(sc, m, fmt, ...) do {				\
286 	(void) sc;						\
287 } while (0)
288 #define	KEYPRINTF(sc, k, ix, mac) do {				\
289 	(void) sc;						\
290 } while (0)
291 #endif
292 
293 MALLOC_DEFINE(M_ATHDEV, "athdev", "ath driver dma buffers");
294 
295 int
296 ath_attach(u_int16_t devid, struct ath_softc *sc)
297 {
298 	struct ifnet *ifp;
299 	struct ieee80211com *ic;
300 	struct ath_hal *ah = NULL;
301 	HAL_STATUS status;
302 	int error = 0, i;
303 
304 	DPRINTF(sc, ATH_DEBUG_ANY, "%s: devid 0x%x\n", __func__, devid);
305 
306 	ifp = sc->sc_ifp = if_alloc(IFT_IEEE80211);
307 	if (ifp == NULL) {
308 		device_printf(sc->sc_dev, "can not if_alloc()\n");
309 		error = ENOSPC;
310 		goto bad;
311 	}
312 	ic = ifp->if_l2com;
313 
314 	/* set these up early for if_printf use */
315 	if_initname(ifp, device_get_name(sc->sc_dev),
316 		device_get_unit(sc->sc_dev));
317 
318 	ah = ath_hal_attach(devid, sc, sc->sc_st, sc->sc_sh, &status);
319 	if (ah == NULL) {
320 		if_printf(ifp, "unable to attach hardware; HAL status %u\n",
321 			status);
322 		error = ENXIO;
323 		goto bad;
324 	}
325 	if (ah->ah_abi != HAL_ABI_VERSION) {
326 		if_printf(ifp, "HAL ABI mismatch detected "
327 			"(HAL:0x%x != driver:0x%x)\n",
328 			ah->ah_abi, HAL_ABI_VERSION);
329 		error = ENXIO;
330 		goto bad;
331 	}
332 	sc->sc_ah = ah;
333 	sc->sc_invalid = 0;	/* ready to go, enable interrupt handling */
334 
335 	/*
336 	 * Check if the MAC has multi-rate retry support.
337 	 * We do this by trying to setup a fake extended
338 	 * descriptor.  MAC's that don't have support will
339 	 * return false w/o doing anything.  MAC's that do
340 	 * support it will return true w/o doing anything.
341 	 */
342 	sc->sc_mrretry = ath_hal_setupxtxdesc(ah, NULL, 0,0, 0,0, 0,0);
343 
344 	/*
345 	 * Check if the device has hardware counters for PHY
346 	 * errors.  If so we need to enable the MIB interrupt
347 	 * so we can act on stat triggers.
348 	 */
349 	if (ath_hal_hwphycounters(ah))
350 		sc->sc_needmib = 1;
351 
352 	/*
353 	 * Get the hardware key cache size.
354 	 */
355 	sc->sc_keymax = ath_hal_keycachesize(ah);
356 	if (sc->sc_keymax > ATH_KEYMAX) {
357 		if_printf(ifp, "Warning, using only %u of %u key cache slots\n",
358 			ATH_KEYMAX, sc->sc_keymax);
359 		sc->sc_keymax = ATH_KEYMAX;
360 	}
361 	/*
362 	 * Reset the key cache since some parts do not
363 	 * reset the contents on initial power up.
364 	 */
365 	for (i = 0; i < sc->sc_keymax; i++)
366 		ath_hal_keyreset(ah, i);
367 
368 	/*
369 	 * Collect the default channel list.
370 	 */
371 	error = ath_getchannels(sc);
372 	if (error != 0)
373 		goto bad;
374 
375 	/*
376 	 * Setup rate tables for all potential media types.
377 	 */
378 	ath_rate_setup(sc, IEEE80211_MODE_11A);
379 	ath_rate_setup(sc, IEEE80211_MODE_11B);
380 	ath_rate_setup(sc, IEEE80211_MODE_11G);
381 	ath_rate_setup(sc, IEEE80211_MODE_TURBO_A);
382 	ath_rate_setup(sc, IEEE80211_MODE_TURBO_G);
383 	ath_rate_setup(sc, IEEE80211_MODE_STURBO_A);
384 	ath_rate_setup(sc, IEEE80211_MODE_11NA);
385 	ath_rate_setup(sc, IEEE80211_MODE_11NG);
386 	ath_rate_setup(sc, IEEE80211_MODE_HALF);
387 	ath_rate_setup(sc, IEEE80211_MODE_QUARTER);
388 
389 	/* NB: setup here so ath_rate_update is happy */
390 	ath_setcurmode(sc, IEEE80211_MODE_11A);
391 
392 	/*
393 	 * Allocate tx+rx descriptors and populate the lists.
394 	 */
395 	error = ath_desc_alloc(sc);
396 	if (error != 0) {
397 		if_printf(ifp, "failed to allocate descriptors: %d\n", error);
398 		goto bad;
399 	}
400 	callout_init(&sc->sc_cal_ch, CALLOUT_MPSAFE);
401 
402 	ATH_TXBUF_LOCK_INIT(sc);
403 
404 	sc->sc_tq = taskqueue_create("ath_taskq", M_NOWAIT,
405 		taskqueue_thread_enqueue, &sc->sc_tq);
406 	taskqueue_start_threads(&sc->sc_tq, 1, PI_NET,
407 		"%s taskq", ifp->if_xname);
408 
409 	TASK_INIT(&sc->sc_rxtask, 0, ath_rx_proc, sc);
410 	TASK_INIT(&sc->sc_rxorntask, 0, ath_rxorn_proc, sc);
411 	TASK_INIT(&sc->sc_bmisstask, 0, ath_bmiss_proc, sc);
412 	TASK_INIT(&sc->sc_bstucktask,0, ath_bstuck_proc, sc);
413 
414 	/*
415 	 * Allocate hardware transmit queues: one queue for
416 	 * beacon frames and one data queue for each QoS
417 	 * priority.  Note that the hal handles reseting
418 	 * these queues at the needed time.
419 	 *
420 	 * XXX PS-Poll
421 	 */
422 	sc->sc_bhalq = ath_beaconq_setup(ah);
423 	if (sc->sc_bhalq == (u_int) -1) {
424 		if_printf(ifp, "unable to setup a beacon xmit queue!\n");
425 		error = EIO;
426 		goto bad2;
427 	}
428 	sc->sc_cabq = ath_txq_setup(sc, HAL_TX_QUEUE_CAB, 0);
429 	if (sc->sc_cabq == NULL) {
430 		if_printf(ifp, "unable to setup CAB xmit queue!\n");
431 		error = EIO;
432 		goto bad2;
433 	}
434 	/* NB: insure BK queue is the lowest priority h/w queue */
435 	if (!ath_tx_setup(sc, WME_AC_BK, HAL_WME_AC_BK)) {
436 		if_printf(ifp, "unable to setup xmit queue for %s traffic!\n",
437 			ieee80211_wme_acnames[WME_AC_BK]);
438 		error = EIO;
439 		goto bad2;
440 	}
441 	if (!ath_tx_setup(sc, WME_AC_BE, HAL_WME_AC_BE) ||
442 	    !ath_tx_setup(sc, WME_AC_VI, HAL_WME_AC_VI) ||
443 	    !ath_tx_setup(sc, WME_AC_VO, HAL_WME_AC_VO)) {
444 		/*
445 		 * Not enough hardware tx queues to properly do WME;
446 		 * just punt and assign them all to the same h/w queue.
447 		 * We could do a better job of this if, for example,
448 		 * we allocate queues when we switch from station to
449 		 * AP mode.
450 		 */
451 		if (sc->sc_ac2q[WME_AC_VI] != NULL)
452 			ath_tx_cleanupq(sc, sc->sc_ac2q[WME_AC_VI]);
453 		if (sc->sc_ac2q[WME_AC_BE] != NULL)
454 			ath_tx_cleanupq(sc, sc->sc_ac2q[WME_AC_BE]);
455 		sc->sc_ac2q[WME_AC_BE] = sc->sc_ac2q[WME_AC_BK];
456 		sc->sc_ac2q[WME_AC_VI] = sc->sc_ac2q[WME_AC_BK];
457 		sc->sc_ac2q[WME_AC_VO] = sc->sc_ac2q[WME_AC_BK];
458 	}
459 
460 	/*
461 	 * Special case certain configurations.  Note the
462 	 * CAB queue is handled by these specially so don't
463 	 * include them when checking the txq setup mask.
464 	 */
465 	switch (sc->sc_txqsetup &~ (1<<sc->sc_cabq->axq_qnum)) {
466 	case 0x01:
467 		TASK_INIT(&sc->sc_txtask, 0, ath_tx_proc_q0, sc);
468 		break;
469 	case 0x0f:
470 		TASK_INIT(&sc->sc_txtask, 0, ath_tx_proc_q0123, sc);
471 		break;
472 	default:
473 		TASK_INIT(&sc->sc_txtask, 0, ath_tx_proc, sc);
474 		break;
475 	}
476 
477 	/*
478 	 * Setup rate control.  Some rate control modules
479 	 * call back to change the anntena state so expose
480 	 * the necessary entry points.
481 	 * XXX maybe belongs in struct ath_ratectrl?
482 	 */
483 	sc->sc_setdefantenna = ath_setdefantenna;
484 	sc->sc_rc = ath_rate_attach(sc);
485 	if (sc->sc_rc == NULL) {
486 		error = EIO;
487 		goto bad2;
488 	}
489 
490 	sc->sc_blinking = 0;
491 	sc->sc_ledstate = 1;
492 	sc->sc_ledon = 0;			/* low true */
493 	sc->sc_ledidle = (2700*hz)/1000;	/* 2.7sec */
494 	callout_init(&sc->sc_ledtimer, CALLOUT_MPSAFE);
495 	/*
496 	 * Auto-enable soft led processing for IBM cards and for
497 	 * 5211 minipci cards.  Users can also manually enable/disable
498 	 * support with a sysctl.
499 	 */
500 	sc->sc_softled = (devid == AR5212_DEVID_IBM || devid == AR5211_DEVID);
501 	if (sc->sc_softled) {
502 		ath_hal_gpioCfgOutput(ah, sc->sc_ledpin);
503 		ath_hal_gpioset(ah, sc->sc_ledpin, !sc->sc_ledon);
504 	}
505 
506 	ifp->if_softc = sc;
507 	ifp->if_flags = IFF_SIMPLEX | IFF_BROADCAST | IFF_MULTICAST;
508 	ifp->if_start = ath_start;
509 	ifp->if_watchdog = ath_watchdog;
510 	ifp->if_ioctl = ath_ioctl;
511 	ifp->if_init = ath_init;
512 	IFQ_SET_MAXLEN(&ifp->if_snd, IFQ_MAXLEN);
513 	ifp->if_snd.ifq_drv_maxlen = IFQ_MAXLEN;
514 	IFQ_SET_READY(&ifp->if_snd);
515 
516 	ic->ic_ifp = ifp;
517 	/* XXX not right but it's not used anywhere important */
518 	ic->ic_phytype = IEEE80211_T_OFDM;
519 	ic->ic_opmode = IEEE80211_M_STA;
520 	ic->ic_caps =
521 		  IEEE80211_C_STA		/* station mode */
522 		| IEEE80211_C_IBSS		/* ibss, nee adhoc, mode */
523 		| IEEE80211_C_HOSTAP		/* hostap mode */
524 		| IEEE80211_C_MONITOR		/* monitor mode */
525 		| IEEE80211_C_AHDEMO		/* adhoc demo mode */
526 		| IEEE80211_C_WDS		/* 4-address traffic works */
527 		| IEEE80211_C_SHPREAMBLE	/* short preamble supported */
528 		| IEEE80211_C_SHSLOT		/* short slot time supported */
529 		| IEEE80211_C_WPA		/* capable of WPA1+WPA2 */
530 		| IEEE80211_C_BGSCAN		/* capable of bg scanning */
531 		| IEEE80211_C_TXFRAG		/* handle tx frags */
532 		;
533 	/*
534 	 * Query the hal to figure out h/w crypto support.
535 	 */
536 	if (ath_hal_ciphersupported(ah, HAL_CIPHER_WEP))
537 		ic->ic_cryptocaps |= IEEE80211_CRYPTO_WEP;
538 	if (ath_hal_ciphersupported(ah, HAL_CIPHER_AES_OCB))
539 		ic->ic_cryptocaps |= IEEE80211_CRYPTO_AES_OCB;
540 	if (ath_hal_ciphersupported(ah, HAL_CIPHER_AES_CCM))
541 		ic->ic_cryptocaps |= IEEE80211_CRYPTO_AES_CCM;
542 	if (ath_hal_ciphersupported(ah, HAL_CIPHER_CKIP))
543 		ic->ic_cryptocaps |= IEEE80211_CRYPTO_CKIP;
544 	if (ath_hal_ciphersupported(ah, HAL_CIPHER_TKIP)) {
545 		ic->ic_cryptocaps |= IEEE80211_CRYPTO_TKIP;
546 		/*
547 		 * Check if h/w does the MIC and/or whether the
548 		 * separate key cache entries are required to
549 		 * handle both tx+rx MIC keys.
550 		 */
551 		if (ath_hal_ciphersupported(ah, HAL_CIPHER_MIC))
552 			ic->ic_cryptocaps |= IEEE80211_CRYPTO_TKIPMIC;
553 		/*
554 		 * If the h/w supports storing tx+rx MIC keys
555 		 * in one cache slot automatically enable use.
556 		 */
557 		if (ath_hal_hastkipsplit(ah) ||
558 		    !ath_hal_settkipsplit(ah, AH_FALSE))
559 			sc->sc_splitmic = 1;
560 		/*
561 		 * If the h/w can do TKIP MIC together with WME then
562 		 * we use it; otherwise we force the MIC to be done
563 		 * in software by the net80211 layer.
564 		 */
565 		if (ath_hal_haswmetkipmic(ah))
566 			sc->sc_wmetkipmic = 1;
567 	}
568 	sc->sc_hasclrkey = ath_hal_ciphersupported(ah, HAL_CIPHER_CLR);
569 	sc->sc_mcastkey = ath_hal_getmcastkeysearch(ah);
570 	/*
571 	 * Mark key cache slots associated with global keys
572 	 * as in use.  If we knew TKIP was not to be used we
573 	 * could leave the +32, +64, and +32+64 slots free.
574 	 */
575 	for (i = 0; i < IEEE80211_WEP_NKID; i++) {
576 		setbit(sc->sc_keymap, i);
577 		setbit(sc->sc_keymap, i+64);
578 		if (sc->sc_splitmic) {
579 			setbit(sc->sc_keymap, i+32);
580 			setbit(sc->sc_keymap, i+32+64);
581 		}
582 	}
583 	/*
584 	 * TPC support can be done either with a global cap or
585 	 * per-packet support.  The latter is not available on
586 	 * all parts.  We're a bit pedantic here as all parts
587 	 * support a global cap.
588 	 */
589 	if (ath_hal_hastpc(ah) || ath_hal_hastxpowlimit(ah))
590 		ic->ic_caps |= IEEE80211_C_TXPMGT;
591 
592 	/*
593 	 * Mark WME capability only if we have sufficient
594 	 * hardware queues to do proper priority scheduling.
595 	 */
596 	if (sc->sc_ac2q[WME_AC_BE] != sc->sc_ac2q[WME_AC_BK])
597 		ic->ic_caps |= IEEE80211_C_WME;
598 	/*
599 	 * Check for misc other capabilities.
600 	 */
601 	if (ath_hal_hasbursting(ah))
602 		ic->ic_caps |= IEEE80211_C_BURST;
603 	sc->sc_hasbmask = ath_hal_hasbssidmask(ah);
604 	sc->sc_hastsfadd = ath_hal_hastsfadjust(ah);
605 	if (ath_hal_hasfastframes(ah))
606 		ic->ic_caps |= IEEE80211_C_FF;
607 	if (ath_hal_getwirelessmodes(ah, ic->ic_regdomain.country) & (HAL_MODE_108G|HAL_MODE_TURBO))
608 		ic->ic_caps |= IEEE80211_C_TURBOP;
609 
610 	/*
611 	 * Indicate we need the 802.11 header padded to a
612 	 * 32-bit boundary for 4-address and QoS frames.
613 	 */
614 	ic->ic_flags |= IEEE80211_F_DATAPAD;
615 
616 	/*
617 	 * Query the hal about antenna support.
618 	 */
619 	sc->sc_defant = ath_hal_getdefantenna(ah);
620 
621 	/*
622 	 * Not all chips have the VEOL support we want to
623 	 * use with IBSS beacons; check here for it.
624 	 */
625 	sc->sc_hasveol = ath_hal_hasveol(ah);
626 
627 	/* get mac address from hardware */
628 	ath_hal_getmac(ah, ic->ic_myaddr);
629 	if (sc->sc_hasbmask)
630 		ath_hal_getbssidmask(ah, sc->sc_hwbssidmask);
631 
632 	/* NB: used to size node table key mapping array */
633 	ic->ic_max_keyix = sc->sc_keymax;
634 	/* call MI attach routine. */
635 	ieee80211_ifattach(ic);
636 	ic->ic_setregdomain = ath_setregdomain;
637 	ic->ic_getradiocaps = ath_getradiocaps;
638 	sc->sc_opmode = HAL_M_STA;
639 
640 	/* override default methods */
641 	ic->ic_newassoc = ath_newassoc;
642 	ic->ic_updateslot = ath_updateslot;
643 	ic->ic_wme.wme_update = ath_wme_update;
644 	ic->ic_vap_create = ath_vap_create;
645 	ic->ic_vap_delete = ath_vap_delete;
646 	ic->ic_raw_xmit = ath_raw_xmit;
647 	ic->ic_update_mcast = ath_update_mcast;
648 	ic->ic_update_promisc = ath_update_promisc;
649 	ic->ic_node_alloc = ath_node_alloc;
650 	sc->sc_node_free = ic->ic_node_free;
651 	ic->ic_node_free = ath_node_free;
652 	ic->ic_node_getsignal = ath_node_getsignal;
653 	ic->ic_scan_start = ath_scan_start;
654 	ic->ic_scan_end = ath_scan_end;
655 	ic->ic_set_channel = ath_set_channel;
656 
657 	ath_bpfattach(sc);
658 	/*
659 	 * Setup dynamic sysctl's now that country code and
660 	 * regdomain are available from the hal.
661 	 */
662 	ath_sysctlattach(sc);
663 
664 	if (bootverbose)
665 		ieee80211_announce(ic);
666 	ath_announce(sc);
667 	return 0;
668 bad2:
669 	ath_tx_cleanup(sc);
670 	ath_desc_free(sc);
671 bad:
672 	if (ah)
673 		ath_hal_detach(ah);
674 	if (ifp != NULL)
675 		if_free(ifp);
676 	sc->sc_invalid = 1;
677 	return error;
678 }
679 
680 int
681 ath_detach(struct ath_softc *sc)
682 {
683 	struct ifnet *ifp = sc->sc_ifp;
684 
685 	DPRINTF(sc, ATH_DEBUG_ANY, "%s: if_flags %x\n",
686 		__func__, ifp->if_flags);
687 
688 	/*
689 	 * NB: the order of these is important:
690 	 * o stop the chip so no more interrupts will fire
691 	 * o call the 802.11 layer before detaching the hal to
692 	 *   insure callbacks into the driver to delete global
693 	 *   key cache entries can be handled
694 	 * o free the taskqueue which drains any pending tasks
695 	 * o reclaim the bpf tap now that we know nothing will use
696 	 *   it (e.g. rx processing from the task q thread)
697 	 * o reclaim the tx queue data structures after calling
698 	 *   the 802.11 layer as we'll get called back to reclaim
699 	 *   node state and potentially want to use them
700 	 * o to cleanup the tx queues the hal is called, so detach
701 	 *   it last
702 	 * Other than that, it's straightforward...
703 	 */
704 	ath_stop(ifp);
705 	ieee80211_ifdetach(ifp->if_l2com);
706 	taskqueue_free(sc->sc_tq);
707 	bpfdetach(ifp);
708 #ifdef ATH_TX99_DIAG
709 	if (sc->sc_tx99 != NULL)
710 		sc->sc_tx99->detach(sc->sc_tx99);
711 #endif
712 	ath_rate_detach(sc->sc_rc);
713 	ath_desc_free(sc);
714 	ath_tx_cleanup(sc);
715 	ath_hal_detach(sc->sc_ah);	/* NB: sets chip in full sleep */
716 	if_free(ifp);
717 
718 	return 0;
719 }
720 
721 /*
722  * MAC address handling for multiple BSS on the same radio.
723  * The first vap uses the MAC address from the EEPROM.  For
724  * subsequent vap's we set the U/L bit (bit 1) in the MAC
725  * address and use the next six bits as an index.
726  */
727 static void
728 assign_address(struct ath_softc *sc, uint8_t mac[IEEE80211_ADDR_LEN], int clone)
729 {
730 	int i;
731 
732 	if (clone && sc->sc_hasbmask) {
733 		/* NB: we only do this if h/w supports multiple bssid */
734 		for (i = 0; i < 8; i++)
735 			if ((sc->sc_bssidmask & (1<<i)) == 0)
736 				break;
737 		if (i != 0)
738 			mac[0] |= (i << 2)|0x2;
739 	} else
740 		i = 0;
741 	sc->sc_bssidmask |= 1<<i;
742 	sc->sc_hwbssidmask[0] &= ~mac[0];
743 	if (i == 0)
744 		sc->sc_nbssid0++;
745 }
746 
747 static void
748 reclaim_address(struct ath_softc *sc, const uint8_t mac[IEEE80211_ADDR_LEN])
749 {
750 	int i = mac[0] >> 2;
751 	uint8_t mask;
752 
753 	if (i != 0 || --sc->sc_nbssid0 == 0) {
754 		sc->sc_bssidmask &= ~(1<<i);
755 		/* recalculate bssid mask from remaining addresses */
756 		mask = 0xff;
757 		for (i = 1; i < 8; i++)
758 			if (sc->sc_bssidmask & (1<<i))
759 				mask &= ~((i<<2)|0x2);
760 		sc->sc_hwbssidmask[0] |= mask;
761 	}
762 }
763 
764 /*
765  * Assign a beacon xmit slot.  We try to space out
766  * assignments so when beacons are staggered the
767  * traffic coming out of the cab q has maximal time
768  * to go out before the next beacon is scheduled.
769  */
770 static int
771 assign_bslot(struct ath_softc *sc)
772 {
773 	u_int slot, free;
774 
775 	free = 0;
776 	for (slot = 0; slot < ATH_BCBUF; slot++)
777 		if (sc->sc_bslot[slot] == NULL) {
778 			if (sc->sc_bslot[(slot+1)%ATH_BCBUF] == NULL &&
779 			    sc->sc_bslot[(slot-1)%ATH_BCBUF] == NULL)
780 				return slot;
781 			free = slot;
782 			/* NB: keep looking for a double slot */
783 		}
784 	return free;
785 }
786 
787 static struct ieee80211vap *
788 ath_vap_create(struct ieee80211com *ic,
789 	const char name[IFNAMSIZ], int unit, int opmode, int flags,
790 	const uint8_t bssid[IEEE80211_ADDR_LEN],
791 	const uint8_t mac0[IEEE80211_ADDR_LEN])
792 {
793 	struct ath_softc *sc = ic->ic_ifp->if_softc;
794 	struct ath_vap *avp;
795 	struct ieee80211vap *vap;
796 	uint8_t mac[IEEE80211_ADDR_LEN];
797 	int ic_opmode, needbeacon, error;
798 
799 	avp = (struct ath_vap *) malloc(sizeof(struct ath_vap),
800 	    M_80211_VAP, M_WAITOK | M_ZERO);
801 	needbeacon = 0;
802 	IEEE80211_ADDR_COPY(mac, mac0);
803 
804 	ATH_LOCK(sc);
805 	switch (opmode) {
806 	case IEEE80211_M_STA:
807 		if (sc->sc_nstavaps != 0) {	/* XXX only 1 sta for now */
808 			device_printf(sc->sc_dev, "only 1 sta vap supported\n");
809 			goto bad;
810 		}
811 		if (sc->sc_nvaps) {
812 			/*
813 			 * When there are multiple vaps we must fall
814 			 * back to s/w beacon miss handling.
815 			 */
816 			flags |= IEEE80211_CLONE_NOBEACONS;
817 		}
818 		if (flags & IEEE80211_CLONE_NOBEACONS) {
819 			sc->sc_swbmiss = 1;
820 			ic_opmode = IEEE80211_M_HOSTAP;
821 		} else
822 			ic_opmode = opmode;
823 		break;
824 	case IEEE80211_M_IBSS:
825 		if (sc->sc_nvaps != 0) {	/* XXX only 1 for now */
826 			device_printf(sc->sc_dev,
827 			    "only 1 ibss vap supported\n");
828 			goto bad;
829 		}
830 		ic_opmode = opmode;
831 		needbeacon = 1;
832 		break;
833 	case IEEE80211_M_AHDEMO:
834 		/* fall thru... */
835 	case IEEE80211_M_MONITOR:
836 		if (sc->sc_nvaps != 0 && ic->ic_opmode != opmode) {
837 			/* XXX not right for monitor mode */
838 			ic_opmode = ic->ic_opmode;
839 		} else
840 			ic_opmode = opmode;
841 		break;
842 	case IEEE80211_M_HOSTAP:
843 		needbeacon = 1;
844 		/* fall thru... */
845 	case IEEE80211_M_WDS:
846 		if (sc->sc_nvaps && ic->ic_opmode == IEEE80211_M_STA) {
847 			device_printf(sc->sc_dev,
848 			    "wds not supported in sta mode\n");
849 			goto bad;
850 		}
851 		if (opmode == IEEE80211_M_WDS) {
852 			/*
853 			 * Silently remove any request for a unique
854 			 * bssid; WDS vap's always share the local
855 			 * mac address.
856 			 */
857 			flags &= ~IEEE80211_CLONE_BSSID;
858 		}
859 		ic_opmode = IEEE80211_M_HOSTAP;
860 		break;
861 	default:
862 		device_printf(sc->sc_dev, "unknown opmode %d\n", opmode);
863 		goto bad;
864 	}
865 	/*
866 	 * Check that a beacon buffer is available; the code below assumes it.
867 	 */
868 	if (needbeacon & STAILQ_EMPTY(&sc->sc_bbuf)) {
869 		device_printf(sc->sc_dev, "no beacon buffer available\n");
870 		goto bad;
871 	}
872 
873 	/* STA, AHDEMO? */
874 	if (opmode == IEEE80211_M_HOSTAP) {
875 		assign_address(sc, mac, flags & IEEE80211_CLONE_BSSID);
876 		ath_hal_setbssidmask(sc->sc_ah, sc->sc_hwbssidmask);
877 	}
878 
879 	vap = &avp->av_vap;
880 	/* XXX can't hold mutex across if_alloc */
881 	ATH_UNLOCK(sc);
882 	error = ieee80211_vap_setup(ic, vap, name, unit, opmode, flags,
883 	    bssid, mac);
884 	ATH_LOCK(sc);
885 	if (error != 0) {
886 		device_printf(sc->sc_dev, "%s: error %d creating vap\n",
887 		    __func__, error);
888 		goto bad2;
889 	}
890 
891 	/* h/w crypto support */
892 	vap->iv_key_alloc = ath_key_alloc;
893 	vap->iv_key_delete = ath_key_delete;
894 	vap->iv_key_set = ath_key_set;
895 	vap->iv_key_update_begin = ath_key_update_begin;
896 	vap->iv_key_update_end = ath_key_update_end;
897 
898 	/* override various methods */
899 	avp->av_recv_mgmt = vap->iv_recv_mgmt;
900 	vap->iv_recv_mgmt = ath_recv_mgmt;
901 	vap->iv_reset = ath_reset_vap;
902 	vap->iv_update_beacon = ath_beacon_update;
903 	avp->av_newstate = vap->iv_newstate;
904 	vap->iv_newstate = ath_newstate;
905 	avp->av_bmiss = vap->iv_bmiss;
906 	vap->iv_bmiss = ath_bmiss_vap;
907 
908 	avp->av_bslot = -1;
909 	if (needbeacon) {
910 		/*
911 		 * Allocate beacon state and setup the q for buffered
912 		 * multicast frames.  We know a beacon buffer is
913 		 * available because we checked above.
914 		 */
915 		avp->av_bcbuf = STAILQ_FIRST(&sc->sc_bbuf);
916 		STAILQ_REMOVE_HEAD(&sc->sc_bbuf, bf_list);
917 		if (opmode != IEEE80211_M_IBSS || !sc->sc_hasveol) {
918 			/*
919 			 * Assign the vap to a beacon xmit slot.  As above
920 			 * this cannot fail to find a free one.
921 			 */
922 			avp->av_bslot = assign_bslot(sc);
923 			KASSERT(sc->sc_bslot[avp->av_bslot] == NULL,
924 			    ("beacon slot %u not empty", avp->av_bslot));
925 			sc->sc_bslot[avp->av_bslot] = vap;
926 			sc->sc_nbcnvaps++;
927 		}
928 		if (sc->sc_hastsfadd && sc->sc_nbcnvaps > 0) {
929 			/*
930 			 * Multple vaps are to transmit beacons and we
931 			 * have h/w support for TSF adjusting; enable
932 			 * use of staggered beacons.
933 			 */
934 			sc->sc_stagbeacons = 1;
935 		}
936 		ath_txq_init(sc, &avp->av_mcastq, ATH_TXQ_SWQ);
937 	}
938 
939 	ic->ic_opmode = ic_opmode;
940 	if (opmode != IEEE80211_M_WDS) {
941 		sc->sc_nvaps++;
942 		if (opmode == IEEE80211_M_STA)
943 			sc->sc_nstavaps++;
944 	}
945 	switch (ic_opmode) {
946 	case IEEE80211_M_IBSS:
947 		sc->sc_opmode = HAL_M_IBSS;
948 		break;
949 	case IEEE80211_M_STA:
950 		sc->sc_opmode = HAL_M_STA;
951 		break;
952 	case IEEE80211_M_AHDEMO:
953 	case IEEE80211_M_HOSTAP:
954 		sc->sc_opmode = HAL_M_HOSTAP;
955 		break;
956 	case IEEE80211_M_MONITOR:
957 		sc->sc_opmode = HAL_M_MONITOR;
958 		break;
959 	default:
960 		/* XXX should not happen */
961 		break;
962 	}
963 	if (sc->sc_hastsfadd) {
964 		/*
965 		 * Configure whether or not TSF adjust should be done.
966 		 */
967 		ath_hal_settsfadjust(sc->sc_ah, sc->sc_stagbeacons);
968 	}
969 	ATH_UNLOCK(sc);
970 
971 	/* complete setup */
972 	ieee80211_vap_attach(vap, ath_media_change, ieee80211_media_status);
973 	return vap;
974 bad2:
975 	reclaim_address(sc, mac);
976 	ath_hal_setbssidmask(sc->sc_ah, sc->sc_hwbssidmask);
977 bad:
978 	free(avp, M_80211_VAP);
979 	ATH_UNLOCK(sc);
980 	return NULL;
981 }
982 
983 static void
984 ath_vap_delete(struct ieee80211vap *vap)
985 {
986 	struct ieee80211com *ic = vap->iv_ic;
987 	struct ifnet *ifp = ic->ic_ifp;
988 	struct ath_softc *sc = ifp->if_softc;
989 	struct ath_hal *ah = sc->sc_ah;
990 	struct ath_vap *avp = ATH_VAP(vap);
991 
992 	if (ifp->if_drv_flags & IFF_DRV_RUNNING) {
993 		/*
994 		 * Quiesce the hardware while we remove the vap.  In
995 		 * particular we need to reclaim all references to
996 		 * the vap state by any frames pending on the tx queues.
997 		 */
998 		ath_hal_intrset(ah, 0);		/* disable interrupts */
999 		ath_draintxq(sc);		/* stop xmit side */
1000 		ath_stoprecv(sc);		/* stop recv side */
1001 	}
1002 
1003 	ieee80211_vap_detach(vap);
1004 	ATH_LOCK(sc);
1005 	/*
1006 	 * Reclaim beacon state.  Note this must be done before
1007 	 * the vap instance is reclaimed as we may have a reference
1008 	 * to it in the buffer for the beacon frame.
1009 	 */
1010 	if (avp->av_bcbuf != NULL) {
1011 		if (avp->av_bslot != -1) {
1012 			sc->sc_bslot[avp->av_bslot] = NULL;
1013 			sc->sc_nbcnvaps--;
1014 		}
1015 		ath_beacon_return(sc, avp->av_bcbuf);
1016 		avp->av_bcbuf = NULL;
1017 		if (sc->sc_nbcnvaps == 0) {
1018 			sc->sc_stagbeacons = 0;
1019 			if (sc->sc_hastsfadd)
1020 				ath_hal_settsfadjust(sc->sc_ah, 0);
1021 		}
1022 		/*
1023 		 * Reclaim any pending mcast frames for the vap.
1024 		 */
1025 		ath_tx_draintxq(sc, &avp->av_mcastq);
1026 		ATH_TXQ_LOCK_DESTROY(&avp->av_mcastq);
1027 	}
1028 	/*
1029 	 * Update bookkeeping.
1030 	 */
1031 	if (vap->iv_opmode == IEEE80211_M_STA) {
1032 		sc->sc_nstavaps--;
1033 		if (sc->sc_nstavaps == 0 && sc->sc_swbmiss)
1034 			sc->sc_swbmiss = 0;
1035 	} else if (vap->iv_opmode == IEEE80211_M_HOSTAP) {
1036 		reclaim_address(sc, vap->iv_myaddr);
1037 		ath_hal_setbssidmask(ah, sc->sc_hwbssidmask);
1038 	}
1039 	if (vap->iv_opmode != IEEE80211_M_WDS)
1040 		sc->sc_nvaps--;
1041 	ATH_UNLOCK(sc);
1042 	free(avp, M_80211_VAP);
1043 
1044 	if (ifp->if_drv_flags & IFF_DRV_RUNNING) {
1045 		/*
1046 		 * Restart rx+tx machines if still running (RUNNING will
1047 		 * be reset if we just destroyed the last vap).
1048 		 */
1049 		if (ath_startrecv(sc) != 0)
1050 			if_printf(ifp, "%s: unable to restart recv logic\n",
1051 			    __func__);
1052 		if (sc->sc_beacons)
1053 			ath_beacon_config(sc, NULL);
1054 		ath_hal_intrset(ah, sc->sc_imask);
1055 	}
1056 }
1057 
1058 void
1059 ath_suspend(struct ath_softc *sc)
1060 {
1061 	struct ifnet *ifp = sc->sc_ifp;
1062 	struct ieee80211com *ic = ifp->if_l2com;
1063 
1064 	DPRINTF(sc, ATH_DEBUG_ANY, "%s: if_flags %x\n",
1065 		__func__, ifp->if_flags);
1066 
1067 	sc->sc_resume_up = (ifp->if_flags & IFF_UP) != 0;
1068 	if (ic->ic_opmode == IEEE80211_M_STA)
1069 		ath_stop(ifp);
1070 	else
1071 		ieee80211_suspend_all(ic);
1072 	/*
1073 	 * NB: don't worry about putting the chip in low power
1074 	 * mode; pci will power off our socket on suspend and
1075 	 * cardbus detaches the device.
1076 	 */
1077 }
1078 
1079 /*
1080  * Reset the key cache since some parts do not reset the
1081  * contents on resume.  First we clear all entries, then
1082  * re-load keys that the 802.11 layer assumes are setup
1083  * in h/w.
1084  */
1085 static void
1086 ath_reset_keycache(struct ath_softc *sc)
1087 {
1088 	struct ifnet *ifp = sc->sc_ifp;
1089 	struct ieee80211com *ic = ifp->if_l2com;
1090 	struct ath_hal *ah = sc->sc_ah;
1091 	int i;
1092 
1093 	for (i = 0; i < sc->sc_keymax; i++)
1094 		ath_hal_keyreset(ah, i);
1095 	ieee80211_crypto_reload_keys(ic);
1096 }
1097 
1098 void
1099 ath_resume(struct ath_softc *sc)
1100 {
1101 	struct ifnet *ifp = sc->sc_ifp;
1102 	struct ieee80211com *ic = ifp->if_l2com;
1103 	struct ath_hal *ah = sc->sc_ah;
1104 	HAL_STATUS status;
1105 
1106 	DPRINTF(sc, ATH_DEBUG_ANY, "%s: if_flags %x\n",
1107 		__func__, ifp->if_flags);
1108 
1109 	/*
1110 	 * Must reset the chip before we reload the
1111 	 * keycache as we were powered down on suspend.
1112 	 */
1113 	ath_hal_reset(ah, sc->sc_opmode, &sc->sc_curchan, AH_FALSE, &status);
1114 	ath_reset_keycache(sc);
1115 	if (sc->sc_resume_up) {
1116 		if (ic->ic_opmode == IEEE80211_M_STA) {
1117 			ath_init(sc);
1118 			ieee80211_beacon_miss(ic);
1119 		} else
1120 			ieee80211_resume_all(ic);
1121 	}
1122 	if (sc->sc_softled) {
1123 		ath_hal_gpioCfgOutput(ah, sc->sc_ledpin);
1124 		ath_hal_gpioset(ah, sc->sc_ledpin, !sc->sc_ledon);
1125 	}
1126 }
1127 
1128 void
1129 ath_shutdown(struct ath_softc *sc)
1130 {
1131 	struct ifnet *ifp = sc->sc_ifp;
1132 
1133 	DPRINTF(sc, ATH_DEBUG_ANY, "%s: if_flags %x\n",
1134 		__func__, ifp->if_flags);
1135 
1136 	ath_stop(ifp);
1137 	/* NB: no point powering down chip as we're about to reboot */
1138 }
1139 
1140 /*
1141  * Interrupt handler.  Most of the actual processing is deferred.
1142  */
1143 void
1144 ath_intr(void *arg)
1145 {
1146 	struct ath_softc *sc = arg;
1147 	struct ifnet *ifp = sc->sc_ifp;
1148 	struct ath_hal *ah = sc->sc_ah;
1149 	HAL_INT status;
1150 
1151 	if (sc->sc_invalid) {
1152 		/*
1153 		 * The hardware is not ready/present, don't touch anything.
1154 		 * Note this can happen early on if the IRQ is shared.
1155 		 */
1156 		DPRINTF(sc, ATH_DEBUG_ANY, "%s: invalid; ignored\n", __func__);
1157 		return;
1158 	}
1159 	if (!ath_hal_intrpend(ah))		/* shared irq, not for us */
1160 		return;
1161 	if ((ifp->if_flags & IFF_UP) == 0 ||
1162 	    (ifp->if_drv_flags & IFF_DRV_RUNNING) == 0) {
1163 		HAL_INT status;
1164 
1165 		DPRINTF(sc, ATH_DEBUG_ANY, "%s: if_flags 0x%x\n",
1166 			__func__, ifp->if_flags);
1167 		ath_hal_getisr(ah, &status);	/* clear ISR */
1168 		ath_hal_intrset(ah, 0);		/* disable further intr's */
1169 		return;
1170 	}
1171 	/*
1172 	 * Figure out the reason(s) for the interrupt.  Note
1173 	 * that the hal returns a pseudo-ISR that may include
1174 	 * bits we haven't explicitly enabled so we mask the
1175 	 * value to insure we only process bits we requested.
1176 	 */
1177 	ath_hal_getisr(ah, &status);		/* NB: clears ISR too */
1178 	DPRINTF(sc, ATH_DEBUG_INTR, "%s: status 0x%x\n", __func__, status);
1179 	status &= sc->sc_imask;			/* discard unasked for bits */
1180 	if (status & HAL_INT_FATAL) {
1181 		sc->sc_stats.ast_hardware++;
1182 		ath_hal_intrset(ah, 0);		/* disable intr's until reset */
1183 		ath_fatal_proc(sc, 0);
1184 	} else if (status & HAL_INT_RXORN) {
1185 		sc->sc_stats.ast_rxorn++;
1186 		ath_hal_intrset(ah, 0);		/* disable intr's until reset */
1187 		taskqueue_enqueue(sc->sc_tq, &sc->sc_rxorntask);
1188 	} else {
1189 		if (status & HAL_INT_SWBA) {
1190 			/*
1191 			 * Software beacon alert--time to send a beacon.
1192 			 * Handle beacon transmission directly; deferring
1193 			 * this is too slow to meet timing constraints
1194 			 * under load.
1195 			 */
1196 			ath_beacon_proc(sc, 0);
1197 		}
1198 		if (status & HAL_INT_RXEOL) {
1199 			/*
1200 			 * NB: the hardware should re-read the link when
1201 			 *     RXE bit is written, but it doesn't work at
1202 			 *     least on older hardware revs.
1203 			 */
1204 			sc->sc_stats.ast_rxeol++;
1205 			sc->sc_rxlink = NULL;
1206 		}
1207 		if (status & HAL_INT_TXURN) {
1208 			sc->sc_stats.ast_txurn++;
1209 			/* bump tx trigger level */
1210 			ath_hal_updatetxtriglevel(ah, AH_TRUE);
1211 		}
1212 		if (status & HAL_INT_RX)
1213 			taskqueue_enqueue(sc->sc_tq, &sc->sc_rxtask);
1214 		if (status & HAL_INT_TX)
1215 			taskqueue_enqueue(sc->sc_tq, &sc->sc_txtask);
1216 		if (status & HAL_INT_BMISS) {
1217 			sc->sc_stats.ast_bmiss++;
1218 			taskqueue_enqueue(sc->sc_tq, &sc->sc_bmisstask);
1219 		}
1220 		if (status & HAL_INT_MIB) {
1221 			sc->sc_stats.ast_mib++;
1222 			/*
1223 			 * Disable interrupts until we service the MIB
1224 			 * interrupt; otherwise it will continue to fire.
1225 			 */
1226 			ath_hal_intrset(ah, 0);
1227 			/*
1228 			 * Let the hal handle the event.  We assume it will
1229 			 * clear whatever condition caused the interrupt.
1230 			 */
1231 			ath_hal_mibevent(ah, &sc->sc_halstats);
1232 			ath_hal_intrset(ah, sc->sc_imask);
1233 		}
1234 	}
1235 }
1236 
1237 static void
1238 ath_fatal_proc(void *arg, int pending)
1239 {
1240 	struct ath_softc *sc = arg;
1241 	struct ifnet *ifp = sc->sc_ifp;
1242 	u_int32_t *state;
1243 	u_int32_t len;
1244 	void *sp;
1245 
1246 	if_printf(ifp, "hardware error; resetting\n");
1247 	/*
1248 	 * Fatal errors are unrecoverable.  Typically these
1249 	 * are caused by DMA errors.  Collect h/w state from
1250 	 * the hal so we can diagnose what's going on.
1251 	 */
1252 	if (ath_hal_getfatalstate(sc->sc_ah, &sp, &len)) {
1253 		KASSERT(len >= 6*sizeof(u_int32_t), ("len %u bytes", len));
1254 		state = sp;
1255 		if_printf(ifp, "0x%08x 0x%08x 0x%08x, 0x%08x 0x%08x 0x%08x\n",
1256 		    state[0], state[1] , state[2], state[3],
1257 		    state[4], state[5]);
1258 	}
1259 	ath_reset(ifp);
1260 }
1261 
1262 static void
1263 ath_rxorn_proc(void *arg, int pending)
1264 {
1265 	struct ath_softc *sc = arg;
1266 	struct ifnet *ifp = sc->sc_ifp;
1267 
1268 	if_printf(ifp, "rx FIFO overrun; resetting\n");
1269 	ath_reset(ifp);
1270 }
1271 
1272 static void
1273 ath_bmiss_vap(struct ieee80211vap *vap)
1274 {
1275 	struct ath_softc *sc = vap->iv_ic->ic_ifp->if_softc;
1276 	u_int64_t lastrx = sc->sc_lastrx;
1277 	u_int64_t tsf = ath_hal_gettsf64(sc->sc_ah);
1278 	u_int bmisstimeout =
1279 		vap->iv_bmissthreshold * vap->iv_bss->ni_intval * 1024;
1280 
1281 	DPRINTF(sc, ATH_DEBUG_BEACON,
1282 	    "%s: tsf %llu lastrx %lld (%llu) bmiss %u\n",
1283 	    __func__, (unsigned long long) tsf,
1284 	    (unsigned long long)(tsf - lastrx),
1285 	    (unsigned long long) lastrx, bmisstimeout);
1286 	/*
1287 	 * Workaround phantom bmiss interrupts by sanity-checking
1288 	 * the time of our last rx'd frame.  If it is within the
1289 	 * beacon miss interval then ignore the interrupt.  If it's
1290 	 * truly a bmiss we'll get another interrupt soon and that'll
1291 	 * be dispatched up for processing.
1292 	 */
1293 	if (tsf - lastrx > bmisstimeout)
1294 		ATH_VAP(vap)->av_bmiss(vap);
1295 	else
1296 		sc->sc_stats.ast_bmiss_phantom++;
1297 }
1298 
1299 static void
1300 ath_bmiss_proc(void *arg, int pending)
1301 {
1302 	struct ath_softc *sc = arg;
1303 	struct ifnet *ifp = sc->sc_ifp;
1304 
1305 	DPRINTF(sc, ATH_DEBUG_ANY, "%s: pending %u\n", __func__, pending);
1306 	ieee80211_beacon_miss(ifp->if_l2com);
1307 }
1308 
1309 /*
1310  * Convert net80211 channel to a HAL channel with the flags
1311  * constrained to reflect the current operating mode and
1312  * the frequency possibly mapped for GSM channels.
1313  */
1314 static void
1315 ath_mapchan(HAL_CHANNEL *hc, const struct ieee80211_channel *chan)
1316 {
1317 #define	N(a)	(sizeof(a) / sizeof(a[0]))
1318 	static const u_int modeflags[IEEE80211_MODE_MAX] = {
1319 		0,			/* IEEE80211_MODE_AUTO */
1320 		CHANNEL_A,		/* IEEE80211_MODE_11A */
1321 		CHANNEL_B,		/* IEEE80211_MODE_11B */
1322 		CHANNEL_PUREG,		/* IEEE80211_MODE_11G */
1323 		0,			/* IEEE80211_MODE_FH */
1324 		CHANNEL_108A,		/* IEEE80211_MODE_TURBO_A */
1325 		CHANNEL_108G,		/* IEEE80211_MODE_TURBO_G */
1326 		CHANNEL_ST,		/* IEEE80211_MODE_STURBO_A */
1327 		CHANNEL_A,		/* IEEE80211_MODE_11NA */
1328 		CHANNEL_PUREG,		/* IEEE80211_MODE_11NG */
1329 	};
1330 	enum ieee80211_phymode mode = ieee80211_chan2mode(chan);
1331 
1332 	KASSERT(mode < N(modeflags), ("unexpected phy mode %u", mode));
1333 	KASSERT(modeflags[mode] != 0, ("mode %u undefined", mode));
1334 	hc->channelFlags = modeflags[mode];
1335 	if (IEEE80211_IS_CHAN_HALF(chan))
1336 		hc->channelFlags |= CHANNEL_HALF;
1337 	if (IEEE80211_IS_CHAN_QUARTER(chan))
1338 		hc->channelFlags |= CHANNEL_QUARTER;
1339 	if (IEEE80211_IS_CHAN_HT20(chan))
1340 		hc->channelFlags |= CHANNEL_HT20;
1341 	if (IEEE80211_IS_CHAN_HT40D(chan))
1342 		hc->channelFlags |= CHANNEL_HT40MINUS;
1343 	if (IEEE80211_IS_CHAN_HT40U(chan))
1344 		hc->channelFlags |= CHANNEL_HT40PLUS;
1345 
1346 	hc->channel = IEEE80211_IS_CHAN_GSM(chan) ?
1347 		2422 + (922 - chan->ic_freq) : chan->ic_freq;
1348 #undef N
1349 }
1350 
1351 /*
1352  * Handle TKIP MIC setup to deal hardware that doesn't do MIC
1353  * calcs together with WME.  If necessary disable the crypto
1354  * hardware and mark the 802.11 state so keys will be setup
1355  * with the MIC work done in software.
1356  */
1357 static void
1358 ath_settkipmic(struct ath_softc *sc)
1359 {
1360 	struct ifnet *ifp = sc->sc_ifp;
1361 	struct ieee80211com *ic = ifp->if_l2com;
1362 
1363 	if ((ic->ic_cryptocaps & IEEE80211_CRYPTO_TKIP) && !sc->sc_wmetkipmic) {
1364 		if (ic->ic_flags & IEEE80211_F_WME) {
1365 			ath_hal_settkipmic(sc->sc_ah, AH_FALSE);
1366 			ic->ic_cryptocaps &= ~IEEE80211_CRYPTO_TKIPMIC;
1367 		} else {
1368 			ath_hal_settkipmic(sc->sc_ah, AH_TRUE);
1369 			ic->ic_cryptocaps |= IEEE80211_CRYPTO_TKIPMIC;
1370 		}
1371 	}
1372 }
1373 
1374 static void
1375 ath_init(void *arg)
1376 {
1377 	struct ath_softc *sc = (struct ath_softc *) arg;
1378 	struct ifnet *ifp = sc->sc_ifp;
1379 	struct ieee80211com *ic = ifp->if_l2com;
1380 	struct ath_hal *ah = sc->sc_ah;
1381 	HAL_STATUS status;
1382 
1383 	DPRINTF(sc, ATH_DEBUG_ANY, "%s: if_flags 0x%x\n",
1384 		__func__, ifp->if_flags);
1385 
1386 	ATH_LOCK(sc);
1387 	/*
1388 	 * Stop anything previously setup.  This is safe
1389 	 * whether this is the first time through or not.
1390 	 */
1391 	ath_stop_locked(ifp);
1392 
1393 	/*
1394 	 * The basic interface to setting the hardware in a good
1395 	 * state is ``reset''.  On return the hardware is known to
1396 	 * be powered up and with interrupts disabled.  This must
1397 	 * be followed by initialization of the appropriate bits
1398 	 * and then setup of the interrupt mask.
1399 	 */
1400 	ath_mapchan(&sc->sc_curchan, ic->ic_curchan);
1401 	ath_settkipmic(sc);
1402 	if (!ath_hal_reset(ah, sc->sc_opmode, &sc->sc_curchan, AH_FALSE, &status)) {
1403 		if_printf(ifp, "unable to reset hardware; hal status %u\n",
1404 			status);
1405 		ATH_UNLOCK(sc);
1406 		return;
1407 	}
1408 	ath_chan_change(sc, ic->ic_curchan);
1409 
1410 	/*
1411 	 * Likewise this is set during reset so update
1412 	 * state cached in the driver.
1413 	 */
1414 	sc->sc_diversity = ath_hal_getdiversity(ah);
1415 	sc->sc_calinterval = 1;
1416 	sc->sc_caltries = 0;
1417 
1418 	/*
1419 	 * Setup the hardware after reset: the key cache
1420 	 * is filled as needed and the receive engine is
1421 	 * set going.  Frame transmit is handled entirely
1422 	 * in the frame output path; there's nothing to do
1423 	 * here except setup the interrupt mask.
1424 	 */
1425 	if (ath_startrecv(sc) != 0) {
1426 		if_printf(ifp, "unable to start recv logic\n");
1427 		ATH_UNLOCK(sc);
1428 		return;
1429 	}
1430 
1431 	/*
1432 	 * Enable interrupts.
1433 	 */
1434 	sc->sc_imask = HAL_INT_RX | HAL_INT_TX
1435 		  | HAL_INT_RXEOL | HAL_INT_RXORN
1436 		  | HAL_INT_FATAL | HAL_INT_GLOBAL;
1437 	/*
1438 	 * Enable MIB interrupts when there are hardware phy counters.
1439 	 * Note we only do this (at the moment) for station mode.
1440 	 */
1441 	if (sc->sc_needmib && ic->ic_opmode == IEEE80211_M_STA)
1442 		sc->sc_imask |= HAL_INT_MIB;
1443 
1444 	ifp->if_drv_flags |= IFF_DRV_RUNNING;
1445 	ath_hal_intrset(ah, sc->sc_imask);
1446 
1447 	ATH_UNLOCK(sc);
1448 
1449 #ifdef ATH_TX99_DIAG
1450 	if (sc->sc_tx99 != NULL)
1451 		sc->sc_tx99->start(sc->sc_tx99);
1452 	else
1453 #endif
1454 	ieee80211_start_all(ic);		/* start all vap's */
1455 }
1456 
1457 static void
1458 ath_stop_locked(struct ifnet *ifp)
1459 {
1460 	struct ath_softc *sc = ifp->if_softc;
1461 	struct ath_hal *ah = sc->sc_ah;
1462 
1463 	DPRINTF(sc, ATH_DEBUG_ANY, "%s: invalid %u if_flags 0x%x\n",
1464 		__func__, sc->sc_invalid, ifp->if_flags);
1465 
1466 	ATH_LOCK_ASSERT(sc);
1467 	if (ifp->if_drv_flags & IFF_DRV_RUNNING) {
1468 		/*
1469 		 * Shutdown the hardware and driver:
1470 		 *    reset 802.11 state machine
1471 		 *    turn off timers
1472 		 *    disable interrupts
1473 		 *    turn off the radio
1474 		 *    clear transmit machinery
1475 		 *    clear receive machinery
1476 		 *    drain and release tx queues
1477 		 *    reclaim beacon resources
1478 		 *    power down hardware
1479 		 *
1480 		 * Note that some of this work is not possible if the
1481 		 * hardware is gone (invalid).
1482 		 */
1483 #ifdef ATH_TX99_DIAG
1484 		if (sc->sc_tx99 != NULL)
1485 			sc->sc_tx99->stop(sc->sc_tx99);
1486 #endif
1487 		ifp->if_drv_flags &= ~IFF_DRV_RUNNING;
1488 		ifp->if_timer = 0;
1489 		if (!sc->sc_invalid) {
1490 			if (sc->sc_softled) {
1491 				callout_stop(&sc->sc_ledtimer);
1492 				ath_hal_gpioset(ah, sc->sc_ledpin,
1493 					!sc->sc_ledon);
1494 				sc->sc_blinking = 0;
1495 			}
1496 			ath_hal_intrset(ah, 0);
1497 		}
1498 		ath_draintxq(sc);
1499 		if (!sc->sc_invalid) {
1500 			ath_stoprecv(sc);
1501 			ath_hal_phydisable(ah);
1502 		} else
1503 			sc->sc_rxlink = NULL;
1504 		ath_beacon_free(sc);	/* XXX not needed */
1505 	}
1506 }
1507 
1508 static void
1509 ath_stop(struct ifnet *ifp)
1510 {
1511 	struct ath_softc *sc = ifp->if_softc;
1512 
1513 	ATH_LOCK(sc);
1514 	ath_stop_locked(ifp);
1515 	ATH_UNLOCK(sc);
1516 }
1517 
1518 /*
1519  * Reset the hardware w/o losing operational state.  This is
1520  * basically a more efficient way of doing ath_stop, ath_init,
1521  * followed by state transitions to the current 802.11
1522  * operational state.  Used to recover from various errors and
1523  * to reset or reload hardware state.
1524  */
1525 static int
1526 ath_reset(struct ifnet *ifp)
1527 {
1528 	struct ath_softc *sc = ifp->if_softc;
1529 	struct ieee80211com *ic = ifp->if_l2com;
1530 	struct ath_hal *ah = sc->sc_ah;
1531 	HAL_STATUS status;
1532 
1533 	/*
1534 	 * Convert to a HAL channel description with the flags
1535 	 * constrained to reflect the current operating mode.
1536 	 */
1537 	ath_mapchan(&sc->sc_curchan, ic->ic_curchan);
1538 
1539 	ath_hal_intrset(ah, 0);		/* disable interrupts */
1540 	ath_draintxq(sc);		/* stop xmit side */
1541 	ath_stoprecv(sc);		/* stop recv side */
1542 	ath_settkipmic(sc);		/* configure TKIP MIC handling */
1543 	/* NB: indicate channel change so we do a full reset */
1544 	if (!ath_hal_reset(ah, sc->sc_opmode, &sc->sc_curchan, AH_TRUE, &status))
1545 		if_printf(ifp, "%s: unable to reset hardware; hal status %u\n",
1546 			__func__, status);
1547 	sc->sc_diversity = ath_hal_getdiversity(ah);
1548 	sc->sc_calinterval = 1;
1549 	sc->sc_caltries = 0;
1550 	if (ath_startrecv(sc) != 0)	/* restart recv */
1551 		if_printf(ifp, "%s: unable to start recv logic\n", __func__);
1552 	/*
1553 	 * We may be doing a reset in response to an ioctl
1554 	 * that changes the channel so update any state that
1555 	 * might change as a result.
1556 	 */
1557 	ath_chan_change(sc, ic->ic_curchan);
1558 	if (sc->sc_beacons)
1559 		ath_beacon_config(sc, NULL);	/* restart beacons */
1560 	ath_hal_intrset(ah, sc->sc_imask);
1561 
1562 	ath_start(ifp);			/* restart xmit */
1563 	return 0;
1564 }
1565 
1566 static int
1567 ath_reset_vap(struct ieee80211vap *vap, u_long cmd)
1568 {
1569 	return ath_reset(vap->iv_ic->ic_ifp);
1570 }
1571 
1572 static int
1573 ath_ff_always(struct ath_txq *txq, struct ath_buf *bf)
1574 {
1575 	return 0;
1576 }
1577 
1578 #if 0
1579 static int
1580 ath_ff_ageflushtestdone(struct ath_txq *txq, struct ath_buf *bf)
1581 {
1582 	return (txq->axq_curage - bf->bf_age) < ATH_FF_STAGEMAX;
1583 }
1584 #endif
1585 
1586 /*
1587  * Flush FF staging queue.
1588  */
1589 static void
1590 ath_ff_stageq_flush(struct ath_softc *sc, struct ath_txq *txq,
1591 	int (*ath_ff_flushdonetest)(struct ath_txq *txq, struct ath_buf *bf))
1592 {
1593 	struct ath_buf *bf;
1594 	struct ieee80211_node *ni;
1595 	int pktlen, pri;
1596 
1597 	for (;;) {
1598 		ATH_TXQ_LOCK(txq);
1599 		/*
1600 		 * Go from the back (oldest) to front so we can
1601 		 * stop early based on the age of the entry.
1602 		 */
1603 		bf = TAILQ_LAST(&txq->axq_stageq, axq_headtype);
1604 		if (bf == NULL || ath_ff_flushdonetest(txq, bf)) {
1605 			ATH_TXQ_UNLOCK(txq);
1606 			break;
1607 		}
1608 
1609 		ni = bf->bf_node;
1610 		pri = M_WME_GETAC(bf->bf_m);
1611 		KASSERT(ATH_NODE(ni)->an_ff_buf[pri],
1612 			("no bf on staging queue %p", bf));
1613 		ATH_NODE(ni)->an_ff_buf[pri] = NULL;
1614 		TAILQ_REMOVE(&txq->axq_stageq, bf, bf_stagelist);
1615 
1616 		ATH_TXQ_UNLOCK(txq);
1617 
1618 		DPRINTF(sc, ATH_DEBUG_FF, "%s: flush frame, age %u\n",
1619 			__func__, bf->bf_age);
1620 
1621 		sc->sc_stats.ast_ff_flush++;
1622 
1623 		/* encap and xmit */
1624 		bf->bf_m = ieee80211_encap(ni, bf->bf_m);
1625 		if (bf->bf_m == NULL) {
1626 			DPRINTF(sc, ATH_DEBUG_XMIT | ATH_DEBUG_FF,
1627 				"%s: discard, encapsulation failure\n",
1628 				__func__);
1629 			sc->sc_stats.ast_tx_encap++;
1630 			goto bad;
1631 		}
1632 		pktlen = bf->bf_m->m_pkthdr.len; /* NB: don't reference below */
1633 		if (ath_tx_start(sc, ni, bf, bf->bf_m) == 0) {
1634 #if 0 /*XXX*/
1635 			ifp->if_opackets++;
1636 #endif
1637 			continue;
1638 		}
1639 	bad:
1640 		if (ni != NULL)
1641 			ieee80211_free_node(ni);
1642 		bf->bf_node = NULL;
1643 		if (bf->bf_m != NULL) {
1644 			m_freem(bf->bf_m);
1645 			bf->bf_m = NULL;
1646 		}
1647 
1648 		ATH_TXBUF_LOCK(sc);
1649 		STAILQ_INSERT_TAIL(&sc->sc_txbuf, bf, bf_list);
1650 		ATH_TXBUF_UNLOCK(sc);
1651 	}
1652 }
1653 
1654 static __inline u_int32_t
1655 ath_ff_approx_txtime(struct ath_softc *sc, struct ath_node *an, struct mbuf *m)
1656 {
1657 	struct ieee80211com *ic = sc->sc_ifp->if_l2com;
1658 	u_int32_t framelen;
1659 	struct ath_buf *bf;
1660 
1661 	/*
1662 	 * Approximate the frame length to be transmitted. A swag to add
1663 	 * the following maximal values to the skb payload:
1664 	 *   - 32: 802.11 encap + CRC
1665 	 *   - 24: encryption overhead (if wep bit)
1666 	 *   - 4 + 6: fast-frame header and padding
1667 	 *   - 16: 2 LLC FF tunnel headers
1668 	 *   - 14: 1 802.3 FF tunnel header (skb already accounts for 2nd)
1669 	 */
1670 	framelen = m->m_pkthdr.len + 32 + 4 + 6 + 16 + 14;
1671 	if (ic->ic_flags & IEEE80211_F_PRIVACY)
1672 		framelen += 24;
1673 	bf = an->an_ff_buf[M_WME_GETAC(m)];
1674 	if (bf != NULL)
1675 		framelen += bf->bf_m->m_pkthdr.len;
1676 	return ath_hal_computetxtime(sc->sc_ah, sc->sc_currates, framelen,
1677 			sc->sc_lastdatarix, AH_FALSE);
1678 }
1679 
1680 /*
1681  * Determine if a data frame may be aggregated via ff tunnelling.
1682  * Note the caller is responsible for checking if the destination
1683  * supports fast frames.
1684  *
1685  *  NB: allowing EAPOL frames to be aggregated with other unicast traffic.
1686  *      Do 802.1x EAPOL frames proceed in the clear? Then they couldn't
1687  *      be aggregated with other types of frames when encryption is on?
1688  *
1689  *  NB: assumes lock on an_ff_buf effectively held by txq lock mechanism.
1690  */
1691 static __inline int
1692 ath_ff_can_aggregate(struct ath_softc *sc,
1693 	struct ath_node *an, struct mbuf *m, int *flushq)
1694 {
1695 	struct ieee80211com *ic = sc->sc_ifp->if_l2com;
1696 	struct ath_txq *txq;
1697 	u_int32_t txoplimit;
1698 	u_int pri;
1699 
1700 	*flushq = 0;
1701 
1702 	/*
1703 	 * If there is no frame to combine with and the txq has
1704 	 * fewer frames than the minimum required; then do not
1705 	 * attempt to aggregate this frame.
1706 	 */
1707 	pri = M_WME_GETAC(m);
1708 	txq = sc->sc_ac2q[pri];
1709 	if (an->an_ff_buf[pri] == NULL && txq->axq_depth < sc->sc_fftxqmin)
1710 		return 0;
1711 	/*
1712 	 * When not in station mode never aggregate a multicast
1713 	 * frame; this insures, for example, that a combined frame
1714 	 * does not require multiple encryption keys when using
1715 	 * 802.1x/WPA.
1716 	 */
1717 	if (ic->ic_opmode != IEEE80211_M_STA &&
1718 	    ETHER_IS_MULTICAST(mtod(m, struct ether_header *)->ether_dhost))
1719 		return 0;
1720 	/*
1721 	 * Consult the max bursting interval to insure a combined
1722 	 * frame fits within the TxOp window.
1723 	 */
1724 	txoplimit = IEEE80211_TXOP_TO_US(
1725 		ic->ic_wme.wme_chanParams.cap_wmeParams[pri].wmep_txopLimit);
1726 	if (txoplimit != 0 && ath_ff_approx_txtime(sc, an, m) > txoplimit) {
1727 		DPRINTF(sc, ATH_DEBUG_XMIT | ATH_DEBUG_FF,
1728 			"%s: FF TxOp violation\n", __func__);
1729 		if (an->an_ff_buf[pri] != NULL)
1730 			*flushq = 1;
1731 		return 0;
1732 	}
1733 	return 1;		/* try to aggregate */
1734 }
1735 
1736 /*
1737  * Check if the supplied frame can be partnered with an existing
1738  * or pending frame.  Return a reference to any frame that should be
1739  * sent on return; otherwise return NULL.
1740  */
1741 static struct mbuf *
1742 ath_ff_check(struct ath_softc *sc, struct ath_txq *txq,
1743 	struct ath_buf *bf, struct mbuf *m, struct ieee80211_node *ni)
1744 {
1745 	struct ath_node *an = ATH_NODE(ni);
1746 	struct ath_buf *bfstaged;
1747 	int ff_flush, pri;
1748 
1749 	/*
1750 	 * Check if the supplied frame can be aggregated.
1751 	 *
1752 	 * NB: we use the txq lock to protect references to
1753 	 *     an->an_ff_txbuf in ath_ff_can_aggregate().
1754 	 */
1755 	ATH_TXQ_LOCK(txq);
1756 	pri = M_WME_GETAC(m);
1757 	if (ath_ff_can_aggregate(sc, an, m, &ff_flush)) {
1758 		struct ath_buf *bfstaged = an->an_ff_buf[pri];
1759 		if (bfstaged != NULL) {
1760 			/*
1761 			 * A frame is available for partnering; remove
1762 			 * it, chain it to this one, and encapsulate.
1763 			 */
1764 			an->an_ff_buf[pri] = NULL;
1765 			TAILQ_REMOVE(&txq->axq_stageq, bfstaged, bf_stagelist);
1766 			ATH_TXQ_UNLOCK(txq);
1767 
1768 			/*
1769 			 * Chain mbufs and add FF magic.
1770 			 */
1771 			DPRINTF(sc, ATH_DEBUG_FF,
1772 				"[%s] aggregate fast-frame, age %u\n",
1773 				ether_sprintf(ni->ni_macaddr), txq->axq_curage);
1774 			m->m_nextpkt = NULL;
1775 			bfstaged->bf_m->m_nextpkt = m;
1776 			m = bfstaged->bf_m;
1777 			bfstaged->bf_m = NULL;
1778 			m->m_flags |= M_FF;
1779 			/*
1780 			 * Release the node reference held while
1781 			 * the packet sat on an_ff_buf[]
1782 			 */
1783 			bfstaged->bf_node = NULL;
1784 			ieee80211_free_node(ni);
1785 
1786 			/*
1787 			 * Return bfstaged to the free list.
1788 			 */
1789 			ATH_TXBUF_LOCK(sc);
1790 			STAILQ_INSERT_TAIL(&sc->sc_txbuf, bfstaged, bf_list);
1791 			ATH_TXBUF_UNLOCK(sc);
1792 
1793 			return m;		/* ready to go */
1794 		} else {
1795 			/*
1796 			 * No frame available, queue this frame to wait
1797 			 * for a partner.  Note that we hold the buffer
1798 			 * and a reference to the node; we need the
1799 			 * buffer in particular so we're certain we
1800 			 * can flush the frame at a later time.
1801 			 */
1802 			DPRINTF(sc, ATH_DEBUG_FF,
1803 				"[%s] stage fast-frame, age %u\n",
1804 				ether_sprintf(ni->ni_macaddr), txq->axq_curage);
1805 
1806 			bf->bf_m = m;
1807 			bf->bf_node = ni;	/* NB: held reference */
1808 			bf->bf_age = txq->axq_curage;
1809 			an->an_ff_buf[pri] = bf;
1810 			TAILQ_INSERT_HEAD(&txq->axq_stageq, bf, bf_stagelist);
1811 			ATH_TXQ_UNLOCK(txq);
1812 
1813 			return NULL;		/* consumed */
1814 		}
1815 	}
1816 	/*
1817 	 * Frame could not be aggregated, it needs to be returned
1818 	 * to the caller for immediate transmission.  In addition
1819 	 * we check if we should first flush a frame from the
1820 	 * staging queue before sending this one.
1821 	 *
1822 	 * NB: ath_ff_can_aggregate only marks ff_flush if a frame
1823 	 *     is present to flush.
1824 	 */
1825 	if (ff_flush) {
1826 		int pktlen;
1827 
1828 		bfstaged = an->an_ff_buf[pri];
1829 		an->an_ff_buf[pri] = NULL;
1830 		TAILQ_REMOVE(&txq->axq_stageq, bfstaged, bf_stagelist);
1831 		ATH_TXQ_UNLOCK(txq);
1832 
1833 		DPRINTF(sc, ATH_DEBUG_FF, "[%s] flush staged frame\n",
1834 			ether_sprintf(an->an_node.ni_macaddr));
1835 
1836 		/* encap and xmit */
1837 		bfstaged->bf_m = ieee80211_encap(ni, bfstaged->bf_m);
1838 		if (bfstaged->bf_m == NULL) {
1839 			DPRINTF(sc, ATH_DEBUG_XMIT | ATH_DEBUG_FF,
1840 				"%s: discard, encap failure\n", __func__);
1841 			sc->sc_stats.ast_tx_encap++;
1842 			goto ff_flushbad;
1843 		}
1844 		pktlen = bfstaged->bf_m->m_pkthdr.len;
1845 		if (ath_tx_start(sc, ni, bfstaged, bfstaged->bf_m)) {
1846 			DPRINTF(sc, ATH_DEBUG_XMIT,
1847 				"%s: discard, xmit failure\n", __func__);
1848 	ff_flushbad:
1849 			/*
1850 			 * Unable to transmit frame that was on the staging
1851 			 * queue.  Reclaim the node reference and other
1852 			 * resources.
1853 			 */
1854 			if (ni != NULL)
1855 				ieee80211_free_node(ni);
1856 			bfstaged->bf_node = NULL;
1857 			if (bfstaged->bf_m != NULL) {
1858 				m_freem(bfstaged->bf_m);
1859 				bfstaged->bf_m = NULL;
1860 			}
1861 
1862 			ATH_TXBUF_LOCK(sc);
1863 			STAILQ_INSERT_TAIL(&sc->sc_txbuf, bfstaged, bf_list);
1864 			ATH_TXBUF_UNLOCK(sc);
1865 		} else {
1866 #if 0
1867 			ifp->if_opackets++;
1868 #endif
1869 		}
1870 	} else {
1871 		if (an->an_ff_buf[pri] != NULL) {
1872 			/*
1873 			 * XXX: out-of-order condition only occurs for AP
1874 			 * mode and multicast.  There may be no valid way
1875 			 * to get this condition.
1876 			 */
1877 			DPRINTF(sc, ATH_DEBUG_FF, "[%s] out-of-order frame\n",
1878 				ether_sprintf(an->an_node.ni_macaddr));
1879 			/* XXX stat */
1880 		}
1881 		ATH_TXQ_UNLOCK(txq);
1882 	}
1883 	return m;
1884 }
1885 
1886 /*
1887  * Cleanup driver resources when we run out of buffers
1888  * while processing fragments; return the tx buffers
1889  * allocated and drop node references.
1890  */
1891 static void
1892 ath_txfrag_cleanup(struct ath_softc *sc,
1893 	ath_bufhead *frags, struct ieee80211_node *ni)
1894 {
1895 	struct ath_buf *bf, *next;
1896 
1897 	ATH_TXBUF_LOCK_ASSERT(sc);
1898 
1899 	STAILQ_FOREACH_SAFE(bf, frags, bf_list, next) {
1900 		/* NB: bf assumed clean */
1901 		STAILQ_REMOVE_HEAD(frags, bf_list);
1902 		STAILQ_INSERT_TAIL(&sc->sc_txbuf, bf, bf_list);
1903 		ieee80211_node_decref(ni);
1904 	}
1905 }
1906 
1907 /*
1908  * Setup xmit of a fragmented frame.  Allocate a buffer
1909  * for each frag and bump the node reference count to
1910  * reflect the held reference to be setup by ath_tx_start.
1911  */
1912 static int
1913 ath_txfrag_setup(struct ath_softc *sc, ath_bufhead *frags,
1914 	struct mbuf *m0, struct ieee80211_node *ni)
1915 {
1916 	struct mbuf *m;
1917 	struct ath_buf *bf;
1918 
1919 	ATH_TXBUF_LOCK(sc);
1920 	for (m = m0->m_nextpkt; m != NULL; m = m->m_nextpkt) {
1921 		bf = STAILQ_FIRST(&sc->sc_txbuf);
1922 		if (bf == NULL) {	/* out of buffers, cleanup */
1923 			ath_txfrag_cleanup(sc, frags, ni);
1924 			break;
1925 		}
1926 		STAILQ_REMOVE_HEAD(&sc->sc_txbuf, bf_list);
1927 		ieee80211_node_incref(ni);
1928 		STAILQ_INSERT_TAIL(frags, bf, bf_list);
1929 	}
1930 	ATH_TXBUF_UNLOCK(sc);
1931 
1932 	return !STAILQ_EMPTY(frags);
1933 }
1934 
1935 static void
1936 ath_start(struct ifnet *ifp)
1937 {
1938 	struct ath_softc *sc = ifp->if_softc;
1939 	struct ieee80211com *ic = ifp->if_l2com;
1940 	struct ieee80211_node *ni;
1941 	struct ath_buf *bf;
1942 	struct mbuf *m, *next;
1943 	struct ath_txq *txq;
1944 	ath_bufhead frags;
1945 	int pri;
1946 
1947 	if ((ifp->if_drv_flags & IFF_DRV_RUNNING) == 0 || sc->sc_invalid)
1948 		return;
1949 	for (;;) {
1950 		/*
1951 		 * Grab a TX buffer and associated resources.
1952 		 */
1953 		ATH_TXBUF_LOCK(sc);
1954 		bf = STAILQ_FIRST(&sc->sc_txbuf);
1955 		if (bf != NULL)
1956 			STAILQ_REMOVE_HEAD(&sc->sc_txbuf, bf_list);
1957 		ATH_TXBUF_UNLOCK(sc);
1958 		if (bf == NULL) {
1959 			DPRINTF(sc, ATH_DEBUG_XMIT, "%s: out of xmit buffers\n",
1960 				__func__);
1961 			sc->sc_stats.ast_tx_qstop++;
1962 			ifp->if_drv_flags |= IFF_DRV_OACTIVE;
1963 			break;
1964 		}
1965 
1966 		IFQ_DEQUEUE(&ifp->if_snd, m);
1967 		if (m == NULL) {
1968 			ATH_TXBUF_LOCK(sc);
1969 			STAILQ_INSERT_TAIL(&sc->sc_txbuf, bf, bf_list);
1970 			ATH_TXBUF_UNLOCK(sc);
1971 			break;
1972 		}
1973 		STAILQ_INIT(&frags);
1974 		ni = (struct ieee80211_node *) m->m_pkthdr.rcvif;
1975 		pri = M_WME_GETAC(m);
1976 		txq = sc->sc_ac2q[pri];
1977 		if (ni->ni_ath_flags & IEEE80211_NODE_FF) {
1978 			/*
1979 			 * Check queue length; if too deep drop this
1980 			 * frame (tail drop considered good).
1981 			 */
1982 			if (txq->axq_depth >= sc->sc_fftxqmax) {
1983 				DPRINTF(sc, ATH_DEBUG_FF,
1984 				    "[%s] tail drop on q %u depth %u\n",
1985 				    ether_sprintf(ni->ni_macaddr),
1986 				    txq->axq_qnum, txq->axq_depth);
1987 				sc->sc_stats.ast_tx_qfull++;
1988 				m_freem(m);
1989 				goto reclaim;
1990 			}
1991 			m = ath_ff_check(sc, txq, bf, m, ni);
1992 			if (m == NULL) {
1993 				/* NB: ni ref & bf held on stageq */
1994 				continue;
1995 			}
1996 		}
1997 		ifp->if_opackets++;
1998 		/*
1999 		 * Encapsulate the packet in prep for transmission.
2000 		 */
2001 		m = ieee80211_encap(ni, m);
2002 		if (m == NULL) {
2003 			DPRINTF(sc, ATH_DEBUG_XMIT,
2004 			    "%s: encapsulation failure\n", __func__);
2005 			sc->sc_stats.ast_tx_encap++;
2006 			goto bad;
2007 		}
2008 		/*
2009 		 * Check for fragmentation.  If this frame
2010 		 * has been broken up verify we have enough
2011 		 * buffers to send all the fragments so all
2012 		 * go out or none...
2013 		 */
2014 		if ((m->m_flags & M_FRAG) &&
2015 		    !ath_txfrag_setup(sc, &frags, m, ni)) {
2016 			DPRINTF(sc, ATH_DEBUG_XMIT,
2017 			    "%s: out of txfrag buffers\n", __func__);
2018 			ic->ic_stats.is_tx_nobuf++;	/* XXX */
2019 			ath_freetx(m);
2020 			goto bad;
2021 		}
2022 	nextfrag:
2023 		/*
2024 		 * Pass the frame to the h/w for transmission.
2025 		 * Fragmented frames have each frag chained together
2026 		 * with m_nextpkt.  We know there are sufficient ath_buf's
2027 		 * to send all the frags because of work done by
2028 		 * ath_txfrag_setup.  We leave m_nextpkt set while
2029 		 * calling ath_tx_start so it can use it to extend the
2030 		 * the tx duration to cover the subsequent frag and
2031 		 * so it can reclaim all the mbufs in case of an error;
2032 		 * ath_tx_start clears m_nextpkt once it commits to
2033 		 * handing the frame to the hardware.
2034 		 */
2035 		next = m->m_nextpkt;
2036 		if (ath_tx_start(sc, ni, bf, m)) {
2037 	bad:
2038 			ifp->if_oerrors++;
2039 	reclaim:
2040 			bf->bf_m = NULL;
2041 			bf->bf_node = NULL;
2042 			ATH_TXBUF_LOCK(sc);
2043 			STAILQ_INSERT_TAIL(&sc->sc_txbuf, bf, bf_list);
2044 			ath_txfrag_cleanup(sc, &frags, ni);
2045 			ATH_TXBUF_UNLOCK(sc);
2046 			if (ni != NULL)
2047 				ieee80211_free_node(ni);
2048 			continue;
2049 		}
2050 		if (next != NULL) {
2051 			/*
2052 			 * Beware of state changing between frags.
2053 			 * XXX check sta power-save state?
2054 			 */
2055 			if (ni->ni_vap->iv_state != IEEE80211_S_RUN) {
2056 				DPRINTF(sc, ATH_DEBUG_XMIT,
2057 				    "%s: flush fragmented packet, state %s\n",
2058 				    __func__,
2059 				    ieee80211_state_name[ni->ni_vap->iv_state]);
2060 				ath_freetx(next);
2061 				goto reclaim;
2062 			}
2063 			m = next;
2064 			bf = STAILQ_FIRST(&frags);
2065 			KASSERT(bf != NULL, ("no buf for txfrag"));
2066 			STAILQ_REMOVE_HEAD(&frags, bf_list);
2067 			goto nextfrag;
2068 		}
2069 
2070 		ifp->if_timer = 5;
2071 #if 0
2072 		/*
2073 		 * Flush stale frames from the fast-frame staging queue.
2074 		 */
2075 		if (ic->ic_opmode != IEEE80211_M_STA)
2076 			ath_ff_stageq_flush(sc, txq, ath_ff_ageflushtestdone);
2077 #endif
2078 	}
2079 }
2080 
2081 static int
2082 ath_media_change(struct ifnet *ifp)
2083 {
2084 	int error = ieee80211_media_change(ifp);
2085 	/* NB: only the fixed rate can change and that doesn't need a reset */
2086 	return (error == ENETRESET ? 0 : error);
2087 }
2088 
2089 #ifdef ATH_DEBUG
2090 static void
2091 ath_keyprint(struct ath_softc *sc, const char *tag, u_int ix,
2092 	const HAL_KEYVAL *hk, const u_int8_t mac[IEEE80211_ADDR_LEN])
2093 {
2094 	static const char *ciphers[] = {
2095 		"WEP",
2096 		"AES-OCB",
2097 		"AES-CCM",
2098 		"CKIP",
2099 		"TKIP",
2100 		"CLR",
2101 	};
2102 	int i, n;
2103 
2104 	printf("%s: [%02u] %-7s ", tag, ix, ciphers[hk->kv_type]);
2105 	for (i = 0, n = hk->kv_len; i < n; i++)
2106 		printf("%02x", hk->kv_val[i]);
2107 	printf(" mac %s", ether_sprintf(mac));
2108 	if (hk->kv_type == HAL_CIPHER_TKIP) {
2109 		printf(" %s ", sc->sc_splitmic ? "mic" : "rxmic");
2110 		for (i = 0; i < sizeof(hk->kv_mic); i++)
2111 			printf("%02x", hk->kv_mic[i]);
2112 		if (!sc->sc_splitmic) {
2113 			printf(" txmic ");
2114 			for (i = 0; i < sizeof(hk->kv_txmic); i++)
2115 				printf("%02x", hk->kv_txmic[i]);
2116 		}
2117 	}
2118 	printf("\n");
2119 }
2120 #endif
2121 
2122 /*
2123  * Set a TKIP key into the hardware.  This handles the
2124  * potential distribution of key state to multiple key
2125  * cache slots for TKIP.
2126  */
2127 static int
2128 ath_keyset_tkip(struct ath_softc *sc, const struct ieee80211_key *k,
2129 	HAL_KEYVAL *hk, const u_int8_t mac[IEEE80211_ADDR_LEN])
2130 {
2131 #define	IEEE80211_KEY_XR	(IEEE80211_KEY_XMIT | IEEE80211_KEY_RECV)
2132 	static const u_int8_t zerobssid[IEEE80211_ADDR_LEN];
2133 	struct ath_hal *ah = sc->sc_ah;
2134 
2135 	KASSERT(k->wk_cipher->ic_cipher == IEEE80211_CIPHER_TKIP,
2136 		("got a non-TKIP key, cipher %u", k->wk_cipher->ic_cipher));
2137 	if ((k->wk_flags & IEEE80211_KEY_XR) == IEEE80211_KEY_XR) {
2138 		if (sc->sc_splitmic) {
2139 			/*
2140 			 * TX key goes at first index, RX key at the rx index.
2141 			 * The hal handles the MIC keys at index+64.
2142 			 */
2143 			memcpy(hk->kv_mic, k->wk_txmic, sizeof(hk->kv_mic));
2144 			KEYPRINTF(sc, k->wk_keyix, hk, zerobssid);
2145 			if (!ath_hal_keyset(ah, k->wk_keyix, hk, zerobssid))
2146 				return 0;
2147 
2148 			memcpy(hk->kv_mic, k->wk_rxmic, sizeof(hk->kv_mic));
2149 			KEYPRINTF(sc, k->wk_keyix+32, hk, mac);
2150 			/* XXX delete tx key on failure? */
2151 			return ath_hal_keyset(ah, k->wk_keyix+32, hk, mac);
2152 		} else {
2153 			/*
2154 			 * Room for both TX+RX MIC keys in one key cache
2155 			 * slot, just set key at the first index; the hal
2156 			 * will handle the rest.
2157 			 */
2158 			memcpy(hk->kv_mic, k->wk_rxmic, sizeof(hk->kv_mic));
2159 			memcpy(hk->kv_txmic, k->wk_txmic, sizeof(hk->kv_txmic));
2160 			KEYPRINTF(sc, k->wk_keyix, hk, mac);
2161 			return ath_hal_keyset(ah, k->wk_keyix, hk, mac);
2162 		}
2163 	} else if (k->wk_flags & IEEE80211_KEY_XMIT) {
2164 		if (sc->sc_splitmic) {
2165 			/*
2166 			 * NB: must pass MIC key in expected location when
2167 			 * the keycache only holds one MIC key per entry.
2168 			 */
2169 			memcpy(hk->kv_mic, k->wk_txmic, sizeof(hk->kv_txmic));
2170 		} else
2171 			memcpy(hk->kv_txmic, k->wk_txmic, sizeof(hk->kv_txmic));
2172 		KEYPRINTF(sc, k->wk_keyix, hk, mac);
2173 		return ath_hal_keyset(ah, k->wk_keyix, hk, mac);
2174 	} else if (k->wk_flags & IEEE80211_KEY_RECV) {
2175 		memcpy(hk->kv_mic, k->wk_rxmic, sizeof(hk->kv_mic));
2176 		KEYPRINTF(sc, k->wk_keyix, hk, mac);
2177 		return ath_hal_keyset(ah, k->wk_keyix, hk, mac);
2178 	}
2179 	return 0;
2180 #undef IEEE80211_KEY_XR
2181 }
2182 
2183 /*
2184  * Set a net80211 key into the hardware.  This handles the
2185  * potential distribution of key state to multiple key
2186  * cache slots for TKIP with hardware MIC support.
2187  */
2188 static int
2189 ath_keyset(struct ath_softc *sc, const struct ieee80211_key *k,
2190 	struct ieee80211_node *bss)
2191 {
2192 #define	N(a)	(sizeof(a)/sizeof(a[0]))
2193 	static const u_int8_t ciphermap[] = {
2194 		HAL_CIPHER_WEP,		/* IEEE80211_CIPHER_WEP */
2195 		HAL_CIPHER_TKIP,	/* IEEE80211_CIPHER_TKIP */
2196 		HAL_CIPHER_AES_OCB,	/* IEEE80211_CIPHER_AES_OCB */
2197 		HAL_CIPHER_AES_CCM,	/* IEEE80211_CIPHER_AES_CCM */
2198 		(u_int8_t) -1,		/* 4 is not allocated */
2199 		HAL_CIPHER_CKIP,	/* IEEE80211_CIPHER_CKIP */
2200 		HAL_CIPHER_CLR,		/* IEEE80211_CIPHER_NONE */
2201 	};
2202 	struct ath_hal *ah = sc->sc_ah;
2203 	const struct ieee80211_cipher *cip = k->wk_cipher;
2204 	u_int8_t gmac[IEEE80211_ADDR_LEN];
2205 	const u_int8_t *mac;
2206 	HAL_KEYVAL hk;
2207 
2208 	memset(&hk, 0, sizeof(hk));
2209 	/*
2210 	 * Software crypto uses a "clear key" so non-crypto
2211 	 * state kept in the key cache are maintained and
2212 	 * so that rx frames have an entry to match.
2213 	 */
2214 	if ((k->wk_flags & IEEE80211_KEY_SWCRYPT) == 0) {
2215 		KASSERT(cip->ic_cipher < N(ciphermap),
2216 			("invalid cipher type %u", cip->ic_cipher));
2217 		hk.kv_type = ciphermap[cip->ic_cipher];
2218 		hk.kv_len = k->wk_keylen;
2219 		memcpy(hk.kv_val, k->wk_key, k->wk_keylen);
2220 	} else
2221 		hk.kv_type = HAL_CIPHER_CLR;
2222 
2223 	if ((k->wk_flags & IEEE80211_KEY_GROUP) && sc->sc_mcastkey) {
2224 		/*
2225 		 * Group keys on hardware that supports multicast frame
2226 		 * key search use a mac that is the sender's address with
2227 		 * the high bit set instead of the app-specified address.
2228 		 */
2229 		IEEE80211_ADDR_COPY(gmac, bss->ni_macaddr);
2230 		gmac[0] |= 0x80;
2231 		mac = gmac;
2232 	} else
2233 		mac = k->wk_macaddr;
2234 
2235 	if (hk.kv_type == HAL_CIPHER_TKIP &&
2236 	    (k->wk_flags & IEEE80211_KEY_SWMIC) == 0) {
2237 		return ath_keyset_tkip(sc, k, &hk, mac);
2238 	} else {
2239 		KEYPRINTF(sc, k->wk_keyix, &hk, mac);
2240 		return ath_hal_keyset(ah, k->wk_keyix, &hk, mac);
2241 	}
2242 #undef N
2243 }
2244 
2245 /*
2246  * Allocate tx/rx key slots for TKIP.  We allocate two slots for
2247  * each key, one for decrypt/encrypt and the other for the MIC.
2248  */
2249 static u_int16_t
2250 key_alloc_2pair(struct ath_softc *sc,
2251 	ieee80211_keyix *txkeyix, ieee80211_keyix *rxkeyix)
2252 {
2253 #define	N(a)	(sizeof(a)/sizeof(a[0]))
2254 	u_int i, keyix;
2255 
2256 	KASSERT(sc->sc_splitmic, ("key cache !split"));
2257 	/* XXX could optimize */
2258 	for (i = 0; i < N(sc->sc_keymap)/4; i++) {
2259 		u_int8_t b = sc->sc_keymap[i];
2260 		if (b != 0xff) {
2261 			/*
2262 			 * One or more slots in this byte are free.
2263 			 */
2264 			keyix = i*NBBY;
2265 			while (b & 1) {
2266 		again:
2267 				keyix++;
2268 				b >>= 1;
2269 			}
2270 			/* XXX IEEE80211_KEY_XMIT | IEEE80211_KEY_RECV */
2271 			if (isset(sc->sc_keymap, keyix+32) ||
2272 			    isset(sc->sc_keymap, keyix+64) ||
2273 			    isset(sc->sc_keymap, keyix+32+64)) {
2274 				/* full pair unavailable */
2275 				/* XXX statistic */
2276 				if (keyix == (i+1)*NBBY) {
2277 					/* no slots were appropriate, advance */
2278 					continue;
2279 				}
2280 				goto again;
2281 			}
2282 			setbit(sc->sc_keymap, keyix);
2283 			setbit(sc->sc_keymap, keyix+64);
2284 			setbit(sc->sc_keymap, keyix+32);
2285 			setbit(sc->sc_keymap, keyix+32+64);
2286 			DPRINTF(sc, ATH_DEBUG_KEYCACHE,
2287 				"%s: key pair %u,%u %u,%u\n",
2288 				__func__, keyix, keyix+64,
2289 				keyix+32, keyix+32+64);
2290 			*txkeyix = keyix;
2291 			*rxkeyix = keyix+32;
2292 			return 1;
2293 		}
2294 	}
2295 	DPRINTF(sc, ATH_DEBUG_KEYCACHE, "%s: out of pair space\n", __func__);
2296 	return 0;
2297 #undef N
2298 }
2299 
2300 /*
2301  * Allocate tx/rx key slots for TKIP.  We allocate two slots for
2302  * each key, one for decrypt/encrypt and the other for the MIC.
2303  */
2304 static u_int16_t
2305 key_alloc_pair(struct ath_softc *sc,
2306 	ieee80211_keyix *txkeyix, ieee80211_keyix *rxkeyix)
2307 {
2308 #define	N(a)	(sizeof(a)/sizeof(a[0]))
2309 	u_int i, keyix;
2310 
2311 	KASSERT(!sc->sc_splitmic, ("key cache split"));
2312 	/* XXX could optimize */
2313 	for (i = 0; i < N(sc->sc_keymap)/4; i++) {
2314 		u_int8_t b = sc->sc_keymap[i];
2315 		if (b != 0xff) {
2316 			/*
2317 			 * One or more slots in this byte are free.
2318 			 */
2319 			keyix = i*NBBY;
2320 			while (b & 1) {
2321 		again:
2322 				keyix++;
2323 				b >>= 1;
2324 			}
2325 			if (isset(sc->sc_keymap, keyix+64)) {
2326 				/* full pair unavailable */
2327 				/* XXX statistic */
2328 				if (keyix == (i+1)*NBBY) {
2329 					/* no slots were appropriate, advance */
2330 					continue;
2331 				}
2332 				goto again;
2333 			}
2334 			setbit(sc->sc_keymap, keyix);
2335 			setbit(sc->sc_keymap, keyix+64);
2336 			DPRINTF(sc, ATH_DEBUG_KEYCACHE,
2337 				"%s: key pair %u,%u\n",
2338 				__func__, keyix, keyix+64);
2339 			*txkeyix = *rxkeyix = keyix;
2340 			return 1;
2341 		}
2342 	}
2343 	DPRINTF(sc, ATH_DEBUG_KEYCACHE, "%s: out of pair space\n", __func__);
2344 	return 0;
2345 #undef N
2346 }
2347 
2348 /*
2349  * Allocate a single key cache slot.
2350  */
2351 static int
2352 key_alloc_single(struct ath_softc *sc,
2353 	ieee80211_keyix *txkeyix, ieee80211_keyix *rxkeyix)
2354 {
2355 #define	N(a)	(sizeof(a)/sizeof(a[0]))
2356 	u_int i, keyix;
2357 
2358 	/* XXX try i,i+32,i+64,i+32+64 to minimize key pair conflicts */
2359 	for (i = 0; i < N(sc->sc_keymap); i++) {
2360 		u_int8_t b = sc->sc_keymap[i];
2361 		if (b != 0xff) {
2362 			/*
2363 			 * One or more slots are free.
2364 			 */
2365 			keyix = i*NBBY;
2366 			while (b & 1)
2367 				keyix++, b >>= 1;
2368 			setbit(sc->sc_keymap, keyix);
2369 			DPRINTF(sc, ATH_DEBUG_KEYCACHE, "%s: key %u\n",
2370 				__func__, keyix);
2371 			*txkeyix = *rxkeyix = keyix;
2372 			return 1;
2373 		}
2374 	}
2375 	DPRINTF(sc, ATH_DEBUG_KEYCACHE, "%s: out of space\n", __func__);
2376 	return 0;
2377 #undef N
2378 }
2379 
2380 /*
2381  * Allocate one or more key cache slots for a uniacst key.  The
2382  * key itself is needed only to identify the cipher.  For hardware
2383  * TKIP with split cipher+MIC keys we allocate two key cache slot
2384  * pairs so that we can setup separate TX and RX MIC keys.  Note
2385  * that the MIC key for a TKIP key at slot i is assumed by the
2386  * hardware to be at slot i+64.  This limits TKIP keys to the first
2387  * 64 entries.
2388  */
2389 static int
2390 ath_key_alloc(struct ieee80211vap *vap, struct ieee80211_key *k,
2391 	ieee80211_keyix *keyix, ieee80211_keyix *rxkeyix)
2392 {
2393 	struct ath_softc *sc = vap->iv_ic->ic_ifp->if_softc;
2394 
2395 	/*
2396 	 * Group key allocation must be handled specially for
2397 	 * parts that do not support multicast key cache search
2398 	 * functionality.  For those parts the key id must match
2399 	 * the h/w key index so lookups find the right key.  On
2400 	 * parts w/ the key search facility we install the sender's
2401 	 * mac address (with the high bit set) and let the hardware
2402 	 * find the key w/o using the key id.  This is preferred as
2403 	 * it permits us to support multiple users for adhoc and/or
2404 	 * multi-station operation.
2405 	 */
2406 	if ((k->wk_flags & IEEE80211_KEY_GROUP) && !sc->sc_mcastkey) {
2407 		if (!(&vap->iv_nw_keys[0] <= k &&
2408 		      k < &vap->iv_nw_keys[IEEE80211_WEP_NKID])) {
2409 			/* should not happen */
2410 			DPRINTF(sc, ATH_DEBUG_KEYCACHE,
2411 				"%s: bogus group key\n", __func__);
2412 			return 0;
2413 		}
2414 		/*
2415 		 * XXX we pre-allocate the global keys so
2416 		 * have no way to check if they've already been allocated.
2417 		 */
2418 		*keyix = *rxkeyix = k - vap->iv_nw_keys;
2419 		return 1;
2420 	}
2421 
2422 	/*
2423 	 * We allocate two pair for TKIP when using the h/w to do
2424 	 * the MIC.  For everything else, including software crypto,
2425 	 * we allocate a single entry.  Note that s/w crypto requires
2426 	 * a pass-through slot on the 5211 and 5212.  The 5210 does
2427 	 * not support pass-through cache entries and we map all
2428 	 * those requests to slot 0.
2429 	 */
2430 	if (k->wk_flags & IEEE80211_KEY_SWCRYPT) {
2431 		return key_alloc_single(sc, keyix, rxkeyix);
2432 	} else if (k->wk_cipher->ic_cipher == IEEE80211_CIPHER_TKIP &&
2433 	    (k->wk_flags & IEEE80211_KEY_SWMIC) == 0) {
2434 		if (sc->sc_splitmic)
2435 			return key_alloc_2pair(sc, keyix, rxkeyix);
2436 		else
2437 			return key_alloc_pair(sc, keyix, rxkeyix);
2438 	} else {
2439 		return key_alloc_single(sc, keyix, rxkeyix);
2440 	}
2441 }
2442 
2443 /*
2444  * Delete an entry in the key cache allocated by ath_key_alloc.
2445  */
2446 static int
2447 ath_key_delete(struct ieee80211vap *vap, const struct ieee80211_key *k)
2448 {
2449 	struct ath_softc *sc = vap->iv_ic->ic_ifp->if_softc;
2450 	struct ath_hal *ah = sc->sc_ah;
2451 	const struct ieee80211_cipher *cip = k->wk_cipher;
2452 	u_int keyix = k->wk_keyix;
2453 
2454 	DPRINTF(sc, ATH_DEBUG_KEYCACHE, "%s: delete key %u\n", __func__, keyix);
2455 
2456 	ath_hal_keyreset(ah, keyix);
2457 	/*
2458 	 * Handle split tx/rx keying required for TKIP with h/w MIC.
2459 	 */
2460 	if (cip->ic_cipher == IEEE80211_CIPHER_TKIP &&
2461 	    (k->wk_flags & IEEE80211_KEY_SWMIC) == 0 && sc->sc_splitmic)
2462 		ath_hal_keyreset(ah, keyix+32);		/* RX key */
2463 	if (keyix >= IEEE80211_WEP_NKID) {
2464 		/*
2465 		 * Don't touch keymap entries for global keys so
2466 		 * they are never considered for dynamic allocation.
2467 		 */
2468 		clrbit(sc->sc_keymap, keyix);
2469 		if (cip->ic_cipher == IEEE80211_CIPHER_TKIP &&
2470 		    (k->wk_flags & IEEE80211_KEY_SWMIC) == 0) {
2471 			clrbit(sc->sc_keymap, keyix+64);	/* TX key MIC */
2472 			if (sc->sc_splitmic) {
2473 				/* +32 for RX key, +32+64 for RX key MIC */
2474 				clrbit(sc->sc_keymap, keyix+32);
2475 				clrbit(sc->sc_keymap, keyix+32+64);
2476 			}
2477 		}
2478 	}
2479 	return 1;
2480 }
2481 
2482 /*
2483  * Set the key cache contents for the specified key.  Key cache
2484  * slot(s) must already have been allocated by ath_key_alloc.
2485  */
2486 static int
2487 ath_key_set(struct ieee80211vap *vap, const struct ieee80211_key *k,
2488 	const u_int8_t mac[IEEE80211_ADDR_LEN])
2489 {
2490 	struct ath_softc *sc = vap->iv_ic->ic_ifp->if_softc;
2491 
2492 	return ath_keyset(sc, k, vap->iv_bss);
2493 }
2494 
2495 /*
2496  * Block/unblock tx+rx processing while a key change is done.
2497  * We assume the caller serializes key management operations
2498  * so we only need to worry about synchronization with other
2499  * uses that originate in the driver.
2500  */
2501 static void
2502 ath_key_update_begin(struct ieee80211vap *vap)
2503 {
2504 	struct ifnet *ifp = vap->iv_ic->ic_ifp;
2505 	struct ath_softc *sc = ifp->if_softc;
2506 
2507 	DPRINTF(sc, ATH_DEBUG_KEYCACHE, "%s:\n", __func__);
2508 	taskqueue_block(sc->sc_tq);
2509 	IF_LOCK(&ifp->if_snd);		/* NB: doesn't block mgmt frames */
2510 }
2511 
2512 static void
2513 ath_key_update_end(struct ieee80211vap *vap)
2514 {
2515 	struct ifnet *ifp = vap->iv_ic->ic_ifp;
2516 	struct ath_softc *sc = ifp->if_softc;
2517 
2518 	DPRINTF(sc, ATH_DEBUG_KEYCACHE, "%s:\n", __func__);
2519 	IF_UNLOCK(&ifp->if_snd);
2520 	taskqueue_unblock(sc->sc_tq);
2521 }
2522 
2523 /*
2524  * Calculate the receive filter according to the
2525  * operating mode and state:
2526  *
2527  * o always accept unicast, broadcast, and multicast traffic
2528  * o accept PHY error frames when hardware doesn't have MIB support
2529  *   to count and we need them for ANI (sta mode only at the moment)
2530  *   and we are not scanning (ANI is disabled)
2531  *   NB: only with recent hal's; older hal's add rx filter bits out
2532  *       of sight and we need to blindly preserve them
2533  * o probe request frames are accepted only when operating in
2534  *   hostap, adhoc, or monitor modes
2535  * o enable promiscuous mode
2536  *   - when in monitor mode
2537  *   - if interface marked PROMISC (assumes bridge setting is filtered)
2538  * o accept beacons:
2539  *   - when operating in station mode for collecting rssi data when
2540  *     the station is otherwise quiet, or
2541  *   - when operating in adhoc mode so the 802.11 layer creates
2542  *     node table entries for peers,
2543  *   - when scanning
2544  *   - when doing s/w beacon miss (e.g. for ap+sta)
2545  *   - when operating in ap mode in 11g to detect overlapping bss that
2546  *     require protection
2547  * o accept control frames:
2548  *   - when in monitor mode
2549  * XXX BAR frames for 11n
2550  * XXX HT protection for 11n
2551  */
2552 static u_int32_t
2553 ath_calcrxfilter(struct ath_softc *sc)
2554 {
2555 	struct ifnet *ifp = sc->sc_ifp;
2556 	struct ieee80211com *ic = ifp->if_l2com;
2557 	u_int32_t rfilt;
2558 
2559 #if HAL_ABI_VERSION < 0x08011600
2560 	rfilt = (ath_hal_getrxfilter(sc->sc_ah) &
2561 		(HAL_RX_FILTER_PHYRADAR | HAL_RX_FILTER_PHYERR))
2562 	      | HAL_RX_FILTER_UCAST | HAL_RX_FILTER_BCAST | HAL_RX_FILTER_MCAST;
2563 #else
2564 	rfilt = HAL_RX_FILTER_UCAST | HAL_RX_FILTER_BCAST | HAL_RX_FILTER_MCAST;
2565 	if (ic->ic_opmode == IEEE80211_M_STA &&
2566 	    !sc->sc_needmib && !sc->sc_scanning)
2567 		rfilt |= HAL_RX_FILTER_PHYERR;
2568 #endif
2569 	if (ic->ic_opmode != IEEE80211_M_STA)
2570 		rfilt |= HAL_RX_FILTER_PROBEREQ;
2571 	if (ic->ic_opmode == IEEE80211_M_MONITOR || (ifp->if_flags & IFF_PROMISC))
2572 		rfilt |= HAL_RX_FILTER_PROM;
2573 	if (ic->ic_opmode == IEEE80211_M_STA ||
2574 	    sc->sc_opmode == HAL_M_IBSS ||
2575 	    sc->sc_swbmiss || sc->sc_scanning)
2576 		rfilt |= HAL_RX_FILTER_BEACON;
2577 	/*
2578 	 * NB: We don't recalculate the rx filter when
2579 	 * ic_protmode changes; otherwise we could do
2580 	 * this only when ic_protmode != NONE.
2581 	 */
2582 	if (ic->ic_opmode == IEEE80211_M_HOSTAP &&
2583 	    IEEE80211_IS_CHAN_ANYG(ic->ic_curchan))
2584 		rfilt |= HAL_RX_FILTER_BEACON;
2585 	if (ic->ic_opmode == IEEE80211_M_MONITOR)
2586 		rfilt |= HAL_RX_FILTER_CONTROL;
2587 	DPRINTF(sc, ATH_DEBUG_MODE, "%s: RX filter 0x%x, %s if_flags 0x%x\n",
2588 	    __func__, rfilt, ieee80211_opmode_name[ic->ic_opmode], ifp->if_flags);
2589 	return rfilt;
2590 }
2591 
2592 static void
2593 ath_update_promisc(struct ifnet *ifp)
2594 {
2595 	struct ath_softc *sc = ifp->if_softc;
2596 	u_int32_t rfilt;
2597 
2598 	/* configure rx filter */
2599 	rfilt = ath_calcrxfilter(sc);
2600 	ath_hal_setrxfilter(sc->sc_ah, rfilt);
2601 
2602 	DPRINTF(sc, ATH_DEBUG_MODE, "%s: RX filter 0x%x\n", __func__, rfilt);
2603 }
2604 
2605 static void
2606 ath_update_mcast(struct ifnet *ifp)
2607 {
2608 	struct ath_softc *sc = ifp->if_softc;
2609 	u_int32_t mfilt[2];
2610 
2611 	/* calculate and install multicast filter */
2612 	if ((ifp->if_flags & IFF_ALLMULTI) == 0) {
2613 		struct ifmultiaddr *ifma;
2614 		/*
2615 		 * Merge multicast addresses to form the hardware filter.
2616 		 */
2617 		mfilt[0] = mfilt[1] = 0;
2618 		IF_ADDR_LOCK(ifp);	/* XXX need some fiddling to remove? */
2619 		TAILQ_FOREACH(ifma, &ifp->if_multiaddrs, ifma_link) {
2620 			caddr_t dl;
2621 			u_int32_t val;
2622 			u_int8_t pos;
2623 
2624 			/* calculate XOR of eight 6bit values */
2625 			dl = LLADDR((struct sockaddr_dl *) ifma->ifma_addr);
2626 			val = LE_READ_4(dl + 0);
2627 			pos = (val >> 18) ^ (val >> 12) ^ (val >> 6) ^ val;
2628 			val = LE_READ_4(dl + 3);
2629 			pos ^= (val >> 18) ^ (val >> 12) ^ (val >> 6) ^ val;
2630 			pos &= 0x3f;
2631 			mfilt[pos / 32] |= (1 << (pos % 32));
2632 		}
2633 		IF_ADDR_UNLOCK(ifp);
2634 	} else
2635 		mfilt[0] = mfilt[1] = ~0;
2636 	ath_hal_setmcastfilter(sc->sc_ah, mfilt[0], mfilt[1]);
2637 	DPRINTF(sc, ATH_DEBUG_MODE, "%s: MC filter %08x:%08x\n",
2638 		__func__, mfilt[0], mfilt[1]);
2639 }
2640 
2641 static void
2642 ath_mode_init(struct ath_softc *sc)
2643 {
2644 	struct ifnet *ifp = sc->sc_ifp;
2645 	struct ieee80211com *ic = ifp->if_l2com;
2646 	struct ath_hal *ah = sc->sc_ah;
2647 	u_int32_t rfilt;
2648 
2649 	/* configure rx filter */
2650 	rfilt = ath_calcrxfilter(sc);
2651 	ath_hal_setrxfilter(ah, rfilt);
2652 
2653 	/* configure operational mode */
2654 	ath_hal_setopmode(ah);
2655 
2656 	/*
2657 	 * Handle any link-level address change.  Note that we only
2658 	 * need to force ic_myaddr; any other addresses are handled
2659 	 * as a byproduct of the ifnet code marking the interface
2660 	 * down then up.
2661 	 *
2662 	 * XXX should get from lladdr instead of arpcom but that's more work
2663 	 */
2664 	IEEE80211_ADDR_COPY(ic->ic_myaddr, IF_LLADDR(ifp));
2665 	ath_hal_setmac(ah, ic->ic_myaddr);
2666 
2667 	/* calculate and install multicast filter */
2668 	ath_update_mcast(ifp);
2669 }
2670 
2671 /*
2672  * Set the slot time based on the current setting.
2673  */
2674 static void
2675 ath_setslottime(struct ath_softc *sc)
2676 {
2677 	struct ieee80211com *ic = sc->sc_ifp->if_l2com;
2678 	struct ath_hal *ah = sc->sc_ah;
2679 	u_int usec;
2680 
2681 	if (IEEE80211_IS_CHAN_HALF(ic->ic_curchan))
2682 		usec = 13;
2683 	else if (IEEE80211_IS_CHAN_QUARTER(ic->ic_curchan))
2684 		usec = 21;
2685 	else if (IEEE80211_IS_CHAN_ANYG(ic->ic_curchan)) {
2686 		/* honor short/long slot time only in 11g */
2687 		/* XXX shouldn't honor on pure g or turbo g channel */
2688 		if (ic->ic_flags & IEEE80211_F_SHSLOT)
2689 			usec = HAL_SLOT_TIME_9;
2690 		else
2691 			usec = HAL_SLOT_TIME_20;
2692 	} else
2693 		usec = HAL_SLOT_TIME_9;
2694 
2695 	DPRINTF(sc, ATH_DEBUG_RESET,
2696 	    "%s: chan %u MHz flags 0x%x %s slot, %u usec\n",
2697 	    __func__, ic->ic_curchan->ic_freq, ic->ic_curchan->ic_flags,
2698 	    ic->ic_flags & IEEE80211_F_SHSLOT ? "short" : "long", usec);
2699 
2700 	ath_hal_setslottime(ah, usec);
2701 	sc->sc_updateslot = OK;
2702 }
2703 
2704 /*
2705  * Callback from the 802.11 layer to update the
2706  * slot time based on the current setting.
2707  */
2708 static void
2709 ath_updateslot(struct ifnet *ifp)
2710 {
2711 	struct ath_softc *sc = ifp->if_softc;
2712 	struct ieee80211com *ic = ifp->if_l2com;
2713 
2714 	/*
2715 	 * When not coordinating the BSS, change the hardware
2716 	 * immediately.  For other operation we defer the change
2717 	 * until beacon updates have propagated to the stations.
2718 	 */
2719 	if (ic->ic_opmode == IEEE80211_M_HOSTAP)
2720 		sc->sc_updateslot = UPDATE;
2721 	else
2722 		ath_setslottime(sc);
2723 }
2724 
2725 /*
2726  * Setup a h/w transmit queue for beacons.
2727  */
2728 static int
2729 ath_beaconq_setup(struct ath_hal *ah)
2730 {
2731 	HAL_TXQ_INFO qi;
2732 
2733 	memset(&qi, 0, sizeof(qi));
2734 	qi.tqi_aifs = HAL_TXQ_USEDEFAULT;
2735 	qi.tqi_cwmin = HAL_TXQ_USEDEFAULT;
2736 	qi.tqi_cwmax = HAL_TXQ_USEDEFAULT;
2737 	/* NB: for dynamic turbo, don't enable any other interrupts */
2738 	qi.tqi_qflags = HAL_TXQ_TXDESCINT_ENABLE;
2739 	return ath_hal_setuptxqueue(ah, HAL_TX_QUEUE_BEACON, &qi);
2740 }
2741 
2742 /*
2743  * Setup the transmit queue parameters for the beacon queue.
2744  */
2745 static int
2746 ath_beaconq_config(struct ath_softc *sc)
2747 {
2748 #define	ATH_EXPONENT_TO_VALUE(v)	((1<<(v))-1)
2749 	struct ieee80211com *ic = sc->sc_ifp->if_l2com;
2750 	struct ath_hal *ah = sc->sc_ah;
2751 	HAL_TXQ_INFO qi;
2752 
2753 	ath_hal_gettxqueueprops(ah, sc->sc_bhalq, &qi);
2754 	if (ic->ic_opmode == IEEE80211_M_HOSTAP) {
2755 		/*
2756 		 * Always burst out beacon and CAB traffic.
2757 		 */
2758 		qi.tqi_aifs = ATH_BEACON_AIFS_DEFAULT;
2759 		qi.tqi_cwmin = ATH_BEACON_CWMIN_DEFAULT;
2760 		qi.tqi_cwmax = ATH_BEACON_CWMAX_DEFAULT;
2761 	} else {
2762 		struct wmeParams *wmep =
2763 			&ic->ic_wme.wme_chanParams.cap_wmeParams[WME_AC_BE];
2764 		/*
2765 		 * Adhoc mode; important thing is to use 2x cwmin.
2766 		 */
2767 		qi.tqi_aifs = wmep->wmep_aifsn;
2768 		qi.tqi_cwmin = 2*ATH_EXPONENT_TO_VALUE(wmep->wmep_logcwmin);
2769 		qi.tqi_cwmax = ATH_EXPONENT_TO_VALUE(wmep->wmep_logcwmax);
2770 	}
2771 
2772 	if (!ath_hal_settxqueueprops(ah, sc->sc_bhalq, &qi)) {
2773 		device_printf(sc->sc_dev, "unable to update parameters for "
2774 			"beacon hardware queue!\n");
2775 		return 0;
2776 	} else {
2777 		ath_hal_resettxqueue(ah, sc->sc_bhalq); /* push to h/w */
2778 		return 1;
2779 	}
2780 #undef ATH_EXPONENT_TO_VALUE
2781 }
2782 
2783 /*
2784  * Allocate and setup an initial beacon frame.
2785  */
2786 static int
2787 ath_beacon_alloc(struct ath_softc *sc, struct ieee80211_node *ni)
2788 {
2789 	struct ieee80211vap *vap = ni->ni_vap;
2790 	struct ath_vap *avp = ATH_VAP(vap);
2791 	struct ath_buf *bf;
2792 	struct mbuf *m;
2793 	int error;
2794 
2795 	bf = avp->av_bcbuf;
2796 	if (bf->bf_m != NULL) {
2797 		bus_dmamap_unload(sc->sc_dmat, bf->bf_dmamap);
2798 		m_freem(bf->bf_m);
2799 		bf->bf_m = NULL;
2800 	}
2801 	if (bf->bf_node != NULL) {
2802 		ieee80211_free_node(bf->bf_node);
2803 		bf->bf_node = NULL;
2804 	}
2805 
2806 	/*
2807 	 * NB: the beacon data buffer must be 32-bit aligned;
2808 	 * we assume the mbuf routines will return us something
2809 	 * with this alignment (perhaps should assert).
2810 	 */
2811 	m = ieee80211_beacon_alloc(ni, &avp->av_boff);
2812 	if (m == NULL) {
2813 		device_printf(sc->sc_dev, "%s: cannot get mbuf\n", __func__);
2814 		sc->sc_stats.ast_be_nombuf++;
2815 		return ENOMEM;
2816 	}
2817 	error = bus_dmamap_load_mbuf_sg(sc->sc_dmat, bf->bf_dmamap, m,
2818 				     bf->bf_segs, &bf->bf_nseg,
2819 				     BUS_DMA_NOWAIT);
2820 	if (error != 0) {
2821 		device_printf(sc->sc_dev,
2822 		    "%s: cannot map mbuf, bus_dmamap_load_mbuf_sg returns %d\n",
2823 		    __func__, error);
2824 		m_freem(m);
2825 		return error;
2826 	}
2827 
2828 	/*
2829 	 * Calculate a TSF adjustment factor required for staggered
2830 	 * beacons.  Note that we assume the format of the beacon
2831 	 * frame leaves the tstamp field immediately following the
2832 	 * header.
2833 	 */
2834 	if (sc->sc_stagbeacons && avp->av_bslot > 0) {
2835 		uint64_t tsfadjust;
2836 		struct ieee80211_frame *wh;
2837 
2838 		/*
2839 		 * The beacon interval is in TU's; the TSF is in usecs.
2840 		 * We figure out how many TU's to add to align the timestamp
2841 		 * then convert to TSF units and handle byte swapping before
2842 		 * inserting it in the frame.  The hardware will then add this
2843 		 * each time a beacon frame is sent.  Note that we align vap's
2844 		 * 1..N and leave vap 0 untouched.  This means vap 0 has a
2845 		 * timestamp in one beacon interval while the others get a
2846 		 * timstamp aligned to the next interval.
2847 		 */
2848 		tsfadjust = ni->ni_intval *
2849 		    (ATH_BCBUF - avp->av_bslot) / ATH_BCBUF;
2850 		tsfadjust = htole64(tsfadjust << 10);	/* TU -> TSF */
2851 
2852 		DPRINTF(sc, ATH_DEBUG_BEACON,
2853 		    "%s: %s beacons bslot %d intval %u tsfadjust %llu\n",
2854 		    __func__, sc->sc_stagbeacons ? "stagger" : "burst",
2855 		    avp->av_bslot, ni->ni_intval,
2856 		    (long long unsigned) le64toh(tsfadjust));
2857 
2858 		wh = mtod(m, struct ieee80211_frame *);
2859 		memcpy(&wh[1], &tsfadjust, sizeof(tsfadjust));
2860 	}
2861 	bf->bf_m = m;
2862 	bf->bf_node = ieee80211_ref_node(ni);
2863 
2864 	return 0;
2865 }
2866 
2867 /*
2868  * Setup the beacon frame for transmit.
2869  */
2870 static void
2871 ath_beacon_setup(struct ath_softc *sc, struct ath_buf *bf)
2872 {
2873 #define	USE_SHPREAMBLE(_ic) \
2874 	(((_ic)->ic_flags & (IEEE80211_F_SHPREAMBLE | IEEE80211_F_USEBARKER))\
2875 		== IEEE80211_F_SHPREAMBLE)
2876 	struct ieee80211_node *ni = bf->bf_node;
2877 	struct ieee80211com *ic = ni->ni_ic;
2878 	struct mbuf *m = bf->bf_m;
2879 	struct ath_hal *ah = sc->sc_ah;
2880 	struct ath_desc *ds;
2881 	int flags, antenna;
2882 	const HAL_RATE_TABLE *rt;
2883 	u_int8_t rix, rate;
2884 
2885 	DPRINTF(sc, ATH_DEBUG_BEACON_PROC, "%s: m %p len %u\n",
2886 		__func__, m, m->m_len);
2887 
2888 	/* setup descriptors */
2889 	ds = bf->bf_desc;
2890 
2891 	flags = HAL_TXDESC_NOACK;
2892 	if (ic->ic_opmode == IEEE80211_M_IBSS && sc->sc_hasveol) {
2893 		ds->ds_link = bf->bf_daddr;	/* self-linked */
2894 		flags |= HAL_TXDESC_VEOL;
2895 		/*
2896 		 * Let hardware handle antenna switching.
2897 		 */
2898 		antenna = sc->sc_txantenna;
2899 	} else {
2900 		ds->ds_link = 0;
2901 		/*
2902 		 * Switch antenna every 4 beacons.
2903 		 * XXX assumes two antenna
2904 		 */
2905 		if (sc->sc_txantenna != 0)
2906 			antenna = sc->sc_txantenna;
2907 		else if (sc->sc_stagbeacons && sc->sc_nbcnvaps != 0)
2908 			antenna = ((sc->sc_stats.ast_be_xmit / sc->sc_nbcnvaps) & 4 ? 2 : 1);
2909 		else
2910 			antenna = (sc->sc_stats.ast_be_xmit & 4 ? 2 : 1);
2911 	}
2912 
2913 	KASSERT(bf->bf_nseg == 1,
2914 		("multi-segment beacon frame; nseg %u", bf->bf_nseg));
2915 	ds->ds_data = bf->bf_segs[0].ds_addr;
2916 	/*
2917 	 * Calculate rate code.
2918 	 * XXX everything at min xmit rate
2919 	 */
2920 	rix = 0;
2921 	rt = sc->sc_currates;
2922 	rate = rt->info[rix].rateCode;
2923 	if (USE_SHPREAMBLE(ic))
2924 		rate |= rt->info[rix].shortPreamble;
2925 	ath_hal_setuptxdesc(ah, ds
2926 		, m->m_len + IEEE80211_CRC_LEN	/* frame length */
2927 		, sizeof(struct ieee80211_frame)/* header length */
2928 		, HAL_PKT_TYPE_BEACON		/* Atheros packet type */
2929 		, ni->ni_txpower		/* txpower XXX */
2930 		, rate, 1			/* series 0 rate/tries */
2931 		, HAL_TXKEYIX_INVALID		/* no encryption */
2932 		, antenna			/* antenna mode */
2933 		, flags				/* no ack, veol for beacons */
2934 		, 0				/* rts/cts rate */
2935 		, 0				/* rts/cts duration */
2936 	);
2937 	/* NB: beacon's BufLen must be a multiple of 4 bytes */
2938 	ath_hal_filltxdesc(ah, ds
2939 		, roundup(m->m_len, 4)		/* buffer length */
2940 		, AH_TRUE			/* first segment */
2941 		, AH_TRUE			/* last segment */
2942 		, ds				/* first descriptor */
2943 	);
2944 #if 0
2945 	ath_desc_swap(ds);
2946 #endif
2947 #undef USE_SHPREAMBLE
2948 }
2949 
2950 static void
2951 ath_beacon_update(struct ieee80211vap *vap, int item)
2952 {
2953 	struct ieee80211_beacon_offsets *bo = &ATH_VAP(vap)->av_boff;
2954 
2955 	setbit(bo->bo_flags, item);
2956 }
2957 
2958 /*
2959  * Append the contents of src to dst; both queues
2960  * are assumed to be locked.
2961  */
2962 static void
2963 ath_txqmove(struct ath_txq *dst, struct ath_txq *src)
2964 {
2965 	STAILQ_CONCAT(&dst->axq_q, &src->axq_q);
2966 	dst->axq_link = src->axq_link;
2967 	src->axq_link = NULL;
2968 	dst->axq_depth += src->axq_depth;
2969 	src->axq_depth = 0;
2970 }
2971 
2972 /*
2973  * Transmit a beacon frame at SWBA.  Dynamic updates to the
2974  * frame contents are done as needed and the slot time is
2975  * also adjusted based on current state.
2976  */
2977 static void
2978 ath_beacon_proc(void *arg, int pending)
2979 {
2980 	struct ath_softc *sc = arg;
2981 	struct ath_hal *ah = sc->sc_ah;
2982 	struct ieee80211vap *vap;
2983 	struct ath_buf *bf;
2984 	int slot, otherant;
2985 	uint32_t bfaddr;
2986 
2987 	DPRINTF(sc, ATH_DEBUG_BEACON_PROC, "%s: pending %u\n",
2988 		__func__, pending);
2989 	/*
2990 	 * Check if the previous beacon has gone out.  If
2991 	 * not don't try to post another, skip this period
2992 	 * and wait for the next.  Missed beacons indicate
2993 	 * a problem and should not occur.  If we miss too
2994 	 * many consecutive beacons reset the device.
2995 	 */
2996 	if (ath_hal_numtxpending(ah, sc->sc_bhalq) != 0) {
2997 		sc->sc_bmisscount++;
2998 		DPRINTF(sc, ATH_DEBUG_BEACON,
2999 			"%s: missed %u consecutive beacons\n",
3000 			__func__, sc->sc_bmisscount);
3001 		if (sc->sc_bmisscount > 3)		/* NB: 3 is a guess */
3002 			taskqueue_enqueue(sc->sc_tq, &sc->sc_bstucktask);
3003 		return;
3004 	}
3005 	if (sc->sc_bmisscount != 0) {
3006 		DPRINTF(sc, ATH_DEBUG_BEACON,
3007 			"%s: resume beacon xmit after %u misses\n",
3008 			__func__, sc->sc_bmisscount);
3009 		sc->sc_bmisscount = 0;
3010 	}
3011 
3012 	if (sc->sc_stagbeacons) {			/* staggered beacons */
3013 		struct ieee80211com *ic = sc->sc_ifp->if_l2com;
3014 		uint32_t tsftu;
3015 
3016 		tsftu = ath_hal_gettsf32(ah) >> 10;
3017 		/* XXX lintval */
3018 		slot = ((tsftu % ic->ic_lintval) * ATH_BCBUF) / ic->ic_lintval;
3019 		vap = sc->sc_bslot[(slot+1) % ATH_BCBUF];
3020 		bfaddr = 0;
3021 		if (vap != NULL && vap->iv_state == IEEE80211_S_RUN) {
3022 			bf = ath_beacon_generate(sc, vap);
3023 			if (bf != NULL)
3024 				bfaddr = bf->bf_daddr;
3025 		}
3026 	} else {					/* burst'd beacons */
3027 		uint32_t *bflink = &bfaddr;
3028 
3029 		for (slot = 0; slot < ATH_BCBUF; slot++) {
3030 			vap = sc->sc_bslot[slot];
3031 			if (vap != NULL && vap->iv_state == IEEE80211_S_RUN) {
3032 				bf = ath_beacon_generate(sc, vap);
3033 				if (bf != NULL) {
3034 					*bflink = bf->bf_daddr;
3035 					bflink = &bf->bf_desc->ds_link;
3036 				}
3037 			}
3038 		}
3039 		*bflink = 0;				/* terminate list */
3040 	}
3041 
3042 	/*
3043 	 * Handle slot time change when a non-ERP station joins/leaves
3044 	 * an 11g network.  The 802.11 layer notifies us via callback,
3045 	 * we mark updateslot, then wait one beacon before effecting
3046 	 * the change.  This gives associated stations at least one
3047 	 * beacon interval to note the state change.
3048 	 */
3049 	/* XXX locking */
3050 	if (sc->sc_updateslot == UPDATE) {
3051 		sc->sc_updateslot = COMMIT;	/* commit next beacon */
3052 		sc->sc_slotupdate = slot;
3053 	} else if (sc->sc_updateslot == COMMIT && sc->sc_slotupdate == slot)
3054 		ath_setslottime(sc);		/* commit change to h/w */
3055 
3056 	/*
3057 	 * Check recent per-antenna transmit statistics and flip
3058 	 * the default antenna if noticeably more frames went out
3059 	 * on the non-default antenna.
3060 	 * XXX assumes 2 anntenae
3061 	 */
3062 	if (!sc->sc_diversity && (!sc->sc_stagbeacons || slot == 0)) {
3063 		otherant = sc->sc_defant & 1 ? 2 : 1;
3064 		if (sc->sc_ant_tx[otherant] > sc->sc_ant_tx[sc->sc_defant] + 2)
3065 			ath_setdefantenna(sc, otherant);
3066 		sc->sc_ant_tx[1] = sc->sc_ant_tx[2] = 0;
3067 	}
3068 
3069 	if (bfaddr != 0) {
3070 		/*
3071 		 * Stop any current dma and put the new frame on the queue.
3072 		 * This should never fail since we check above that no frames
3073 		 * are still pending on the queue.
3074 		 */
3075 		if (!ath_hal_stoptxdma(ah, sc->sc_bhalq)) {
3076 			DPRINTF(sc, ATH_DEBUG_ANY,
3077 				"%s: beacon queue %u did not stop?\n",
3078 				__func__, sc->sc_bhalq);
3079 		}
3080 		/* NB: cabq traffic should already be queued and primed */
3081 		ath_hal_puttxbuf(ah, sc->sc_bhalq, bfaddr);
3082 		ath_hal_txstart(ah, sc->sc_bhalq);
3083 
3084 		sc->sc_stats.ast_be_xmit++;
3085 	}
3086 }
3087 
3088 static struct ath_buf *
3089 ath_beacon_generate(struct ath_softc *sc, struct ieee80211vap *vap)
3090 {
3091 	struct ath_vap *avp = ATH_VAP(vap);
3092 	struct ath_txq *cabq = sc->sc_cabq;
3093 	struct ath_buf *bf;
3094 	struct mbuf *m;
3095 	int nmcastq, error;
3096 
3097 	KASSERT(vap->iv_state == IEEE80211_S_RUN,
3098 	    ("not running, state %d", vap->iv_state));
3099 	KASSERT(avp->av_bcbuf != NULL, ("no beacon buffer"));
3100 
3101 	/*
3102 	 * Update dynamic beacon contents.  If this returns
3103 	 * non-zero then we need to remap the memory because
3104 	 * the beacon frame changed size (probably because
3105 	 * of the TIM bitmap).
3106 	 */
3107 	bf = avp->av_bcbuf;
3108 	m = bf->bf_m;
3109 	nmcastq = avp->av_mcastq.axq_depth;
3110 	if (ieee80211_beacon_update(bf->bf_node, &avp->av_boff, m, nmcastq)) {
3111 		/* XXX too conservative? */
3112 		bus_dmamap_unload(sc->sc_dmat, bf->bf_dmamap);
3113 		error = bus_dmamap_load_mbuf_sg(sc->sc_dmat, bf->bf_dmamap, m,
3114 					     bf->bf_segs, &bf->bf_nseg,
3115 					     BUS_DMA_NOWAIT);
3116 		if (error != 0) {
3117 			if_printf(vap->iv_ifp,
3118 			    "%s: bus_dmamap_load_mbuf_sg failed, error %u\n",
3119 			    __func__, error);
3120 			return NULL;
3121 		}
3122 	}
3123 	if ((avp->av_boff.bo_tim[4] & 1) && cabq->axq_depth) {
3124 		DPRINTF(sc, ATH_DEBUG_BEACON,
3125 		    "%s: cabq did not drain, mcastq %u cabq %u\n",
3126 		    __func__, nmcastq, cabq->axq_depth);
3127 		sc->sc_stats.ast_cabq_busy++;
3128 		if (sc->sc_nvaps > 1 && sc->sc_stagbeacons) {
3129 			/*
3130 			 * CABQ traffic from a previous vap is still pending.
3131 			 * We must drain the q before this beacon frame goes
3132 			 * out as otherwise this vap's stations will get cab
3133 			 * frames from a different vap.
3134 			 * XXX could be slow causing us to miss DBA
3135 			 */
3136 			ath_tx_draintxq(sc, cabq);
3137 		}
3138 	}
3139 	ath_beacon_setup(sc, bf);
3140 	bus_dmamap_sync(sc->sc_dmat, bf->bf_dmamap, BUS_DMASYNC_PREWRITE);
3141 
3142 	/*
3143 	 * Enable the CAB queue before the beacon queue to
3144 	 * insure cab frames are triggered by this beacon.
3145 	 */
3146 	if (avp->av_boff.bo_tim[4] & 1) {
3147 		struct ath_hal *ah = sc->sc_ah;
3148 
3149 		/* NB: only at DTIM */
3150 		ATH_TXQ_LOCK(cabq);
3151 		ATH_TXQ_LOCK(&avp->av_mcastq);
3152 		if (nmcastq) {
3153 			struct ath_buf *bfm;
3154 
3155 			/*
3156 			 * Move frames from the s/w mcast q to the h/w cab q.
3157 			 * XXX MORE_DATA bit
3158 			 */
3159 			bfm = STAILQ_FIRST(&avp->av_mcastq.axq_q);
3160 			if (cabq->axq_link != NULL) {
3161 				*cabq->axq_link = bfm->bf_daddr;
3162 			} else
3163 				ath_hal_puttxbuf(ah, cabq->axq_qnum,
3164 					bfm->bf_daddr);
3165 			ath_txqmove(cabq, &avp->av_mcastq);
3166 
3167 			sc->sc_stats.ast_cabq_xmit += nmcastq;
3168 		}
3169 		/* NB: gated by beacon so safe to start here */
3170 		ath_hal_txstart(ah, cabq->axq_qnum);
3171 		ATH_TXQ_UNLOCK(cabq);
3172 		ATH_TXQ_UNLOCK(&avp->av_mcastq);
3173 	}
3174 	return bf;
3175 }
3176 
3177 static void
3178 ath_beacon_start_adhoc(struct ath_softc *sc, struct ieee80211vap *vap)
3179 {
3180 	struct ath_vap *avp = ATH_VAP(vap);
3181 	struct ath_hal *ah = sc->sc_ah;
3182 	struct ath_buf *bf;
3183 	struct mbuf *m;
3184 	int error;
3185 
3186 	KASSERT(avp->av_bcbuf != NULL, ("no beacon buffer"));
3187 
3188 	/*
3189 	 * Update dynamic beacon contents.  If this returns
3190 	 * non-zero then we need to remap the memory because
3191 	 * the beacon frame changed size (probably because
3192 	 * of the TIM bitmap).
3193 	 */
3194 	bf = avp->av_bcbuf;
3195 	m = bf->bf_m;
3196 	if (ieee80211_beacon_update(bf->bf_node, &avp->av_boff, m, 0)) {
3197 		/* XXX too conservative? */
3198 		bus_dmamap_unload(sc->sc_dmat, bf->bf_dmamap);
3199 		error = bus_dmamap_load_mbuf_sg(sc->sc_dmat, bf->bf_dmamap, m,
3200 					     bf->bf_segs, &bf->bf_nseg,
3201 					     BUS_DMA_NOWAIT);
3202 		if (error != 0) {
3203 			if_printf(vap->iv_ifp,
3204 			    "%s: bus_dmamap_load_mbuf_sg failed, error %u\n",
3205 			    __func__, error);
3206 			return;
3207 		}
3208 	}
3209 	ath_beacon_setup(sc, bf);
3210 	bus_dmamap_sync(sc->sc_dmat, bf->bf_dmamap, BUS_DMASYNC_PREWRITE);
3211 
3212 	/* NB: caller is known to have already stopped tx dma */
3213 	ath_hal_puttxbuf(ah, sc->sc_bhalq, bf->bf_daddr);
3214 	ath_hal_txstart(ah, sc->sc_bhalq);
3215 }
3216 
3217 /*
3218  * Reset the hardware after detecting beacons have stopped.
3219  */
3220 static void
3221 ath_bstuck_proc(void *arg, int pending)
3222 {
3223 	struct ath_softc *sc = arg;
3224 	struct ifnet *ifp = sc->sc_ifp;
3225 
3226 	if_printf(ifp, "stuck beacon; resetting (bmiss count %u)\n",
3227 		sc->sc_bmisscount);
3228 	ath_reset(ifp);
3229 }
3230 
3231 /*
3232  * Reclaim beacon resources and return buffer to the pool.
3233  */
3234 static void
3235 ath_beacon_return(struct ath_softc *sc, struct ath_buf *bf)
3236 {
3237 
3238 	if (bf->bf_m != NULL) {
3239 		bus_dmamap_unload(sc->sc_dmat, bf->bf_dmamap);
3240 		m_freem(bf->bf_m);
3241 		bf->bf_m = NULL;
3242 	}
3243 	if (bf->bf_node != NULL) {
3244 		ieee80211_free_node(bf->bf_node);
3245 		bf->bf_node = NULL;
3246 	}
3247 	STAILQ_INSERT_TAIL(&sc->sc_bbuf, bf, bf_list);
3248 }
3249 
3250 /*
3251  * Reclaim beacon resources.
3252  */
3253 static void
3254 ath_beacon_free(struct ath_softc *sc)
3255 {
3256 	struct ath_buf *bf;
3257 
3258 	STAILQ_FOREACH(bf, &sc->sc_bbuf, bf_list) {
3259 		if (bf->bf_m != NULL) {
3260 			bus_dmamap_unload(sc->sc_dmat, bf->bf_dmamap);
3261 			m_freem(bf->bf_m);
3262 			bf->bf_m = NULL;
3263 		}
3264 		if (bf->bf_node != NULL) {
3265 			ieee80211_free_node(bf->bf_node);
3266 			bf->bf_node = NULL;
3267 		}
3268 	}
3269 }
3270 
3271 /*
3272  * Configure the beacon and sleep timers.
3273  *
3274  * When operating as an AP this resets the TSF and sets
3275  * up the hardware to notify us when we need to issue beacons.
3276  *
3277  * When operating in station mode this sets up the beacon
3278  * timers according to the timestamp of the last received
3279  * beacon and the current TSF, configures PCF and DTIM
3280  * handling, programs the sleep registers so the hardware
3281  * will wakeup in time to receive beacons, and configures
3282  * the beacon miss handling so we'll receive a BMISS
3283  * interrupt when we stop seeing beacons from the AP
3284  * we've associated with.
3285  */
3286 static void
3287 ath_beacon_config(struct ath_softc *sc, struct ieee80211vap *vap)
3288 {
3289 #define	TSF_TO_TU(_h,_l) \
3290 	((((u_int32_t)(_h)) << 22) | (((u_int32_t)(_l)) >> 10))
3291 #define	FUDGE	2
3292 	struct ath_hal *ah = sc->sc_ah;
3293 	struct ieee80211com *ic = sc->sc_ifp->if_l2com;
3294 	struct ieee80211_node *ni;
3295 	u_int32_t nexttbtt, intval, tsftu;
3296 	u_int64_t tsf;
3297 
3298 	if (vap == NULL)
3299 		vap = TAILQ_FIRST(&ic->ic_vaps);	/* XXX */
3300 	ni = vap->iv_bss;
3301 
3302 	/* extract tstamp from last beacon and convert to TU */
3303 	nexttbtt = TSF_TO_TU(LE_READ_4(ni->ni_tstamp.data + 4),
3304 			     LE_READ_4(ni->ni_tstamp.data));
3305 	if (ic->ic_opmode == IEEE80211_M_HOSTAP) {
3306 		/*
3307 		 * For multi-bss ap support beacons are either staggered
3308 		 * evenly over N slots or burst together.  For the former
3309 		 * arrange for the SWBA to be delivered for each slot.
3310 		 * Slots that are not occupied will generate nothing.
3311 		 */
3312 		/* NB: the beacon interval is kept internally in TU's */
3313 		intval = ni->ni_intval & HAL_BEACON_PERIOD;
3314 		if (sc->sc_stagbeacons)
3315 			intval /= ATH_BCBUF;
3316 	} else {
3317 		/* NB: the beacon interval is kept internally in TU's */
3318 		intval = ni->ni_intval & HAL_BEACON_PERIOD;
3319 	}
3320 	if (nexttbtt == 0)		/* e.g. for ap mode */
3321 		nexttbtt = intval;
3322 	else if (intval)		/* NB: can be 0 for monitor mode */
3323 		nexttbtt = roundup(nexttbtt, intval);
3324 	DPRINTF(sc, ATH_DEBUG_BEACON, "%s: nexttbtt %u intval %u (%u)\n",
3325 		__func__, nexttbtt, intval, ni->ni_intval);
3326 	if (ic->ic_opmode == IEEE80211_M_STA && !sc->sc_swbmiss) {
3327 		HAL_BEACON_STATE bs;
3328 		int dtimperiod, dtimcount;
3329 		int cfpperiod, cfpcount;
3330 
3331 		/*
3332 		 * Setup dtim and cfp parameters according to
3333 		 * last beacon we received (which may be none).
3334 		 */
3335 		dtimperiod = ni->ni_dtim_period;
3336 		if (dtimperiod <= 0)		/* NB: 0 if not known */
3337 			dtimperiod = 1;
3338 		dtimcount = ni->ni_dtim_count;
3339 		if (dtimcount >= dtimperiod)	/* NB: sanity check */
3340 			dtimcount = 0;		/* XXX? */
3341 		cfpperiod = 1;			/* NB: no PCF support yet */
3342 		cfpcount = 0;
3343 		/*
3344 		 * Pull nexttbtt forward to reflect the current
3345 		 * TSF and calculate dtim+cfp state for the result.
3346 		 */
3347 		tsf = ath_hal_gettsf64(ah);
3348 		tsftu = TSF_TO_TU(tsf>>32, tsf) + FUDGE;
3349 		do {
3350 			nexttbtt += intval;
3351 			if (--dtimcount < 0) {
3352 				dtimcount = dtimperiod - 1;
3353 				if (--cfpcount < 0)
3354 					cfpcount = cfpperiod - 1;
3355 			}
3356 		} while (nexttbtt < tsftu);
3357 		memset(&bs, 0, sizeof(bs));
3358 		bs.bs_intval = intval;
3359 		bs.bs_nexttbtt = nexttbtt;
3360 		bs.bs_dtimperiod = dtimperiod*intval;
3361 		bs.bs_nextdtim = bs.bs_nexttbtt + dtimcount*intval;
3362 		bs.bs_cfpperiod = cfpperiod*bs.bs_dtimperiod;
3363 		bs.bs_cfpnext = bs.bs_nextdtim + cfpcount*bs.bs_dtimperiod;
3364 		bs.bs_cfpmaxduration = 0;
3365 #if 0
3366 		/*
3367 		 * The 802.11 layer records the offset to the DTIM
3368 		 * bitmap while receiving beacons; use it here to
3369 		 * enable h/w detection of our AID being marked in
3370 		 * the bitmap vector (to indicate frames for us are
3371 		 * pending at the AP).
3372 		 * XXX do DTIM handling in s/w to WAR old h/w bugs
3373 		 * XXX enable based on h/w rev for newer chips
3374 		 */
3375 		bs.bs_timoffset = ni->ni_timoff;
3376 #endif
3377 		/*
3378 		 * Calculate the number of consecutive beacons to miss
3379 		 * before taking a BMISS interrupt.
3380 		 * Note that we clamp the result to at most 10 beacons.
3381 		 */
3382 		bs.bs_bmissthreshold = vap->iv_bmissthreshold;
3383 		if (bs.bs_bmissthreshold > 10)
3384 			bs.bs_bmissthreshold = 10;
3385 		else if (bs.bs_bmissthreshold <= 0)
3386 			bs.bs_bmissthreshold = 1;
3387 
3388 		/*
3389 		 * Calculate sleep duration.  The configuration is
3390 		 * given in ms.  We insure a multiple of the beacon
3391 		 * period is used.  Also, if the sleep duration is
3392 		 * greater than the DTIM period then it makes senses
3393 		 * to make it a multiple of that.
3394 		 *
3395 		 * XXX fixed at 100ms
3396 		 */
3397 		bs.bs_sleepduration =
3398 			roundup(IEEE80211_MS_TO_TU(100), bs.bs_intval);
3399 		if (bs.bs_sleepduration > bs.bs_dtimperiod)
3400 			bs.bs_sleepduration = roundup(bs.bs_sleepduration, bs.bs_dtimperiod);
3401 
3402 		DPRINTF(sc, ATH_DEBUG_BEACON,
3403 			"%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"
3404 			, __func__
3405 			, tsf, tsftu
3406 			, bs.bs_intval
3407 			, bs.bs_nexttbtt
3408 			, bs.bs_dtimperiod
3409 			, bs.bs_nextdtim
3410 			, bs.bs_bmissthreshold
3411 			, bs.bs_sleepduration
3412 			, bs.bs_cfpperiod
3413 			, bs.bs_cfpmaxduration
3414 			, bs.bs_cfpnext
3415 			, bs.bs_timoffset
3416 		);
3417 		ath_hal_intrset(ah, 0);
3418 		ath_hal_beacontimers(ah, &bs);
3419 		sc->sc_imask |= HAL_INT_BMISS;
3420 		ath_hal_intrset(ah, sc->sc_imask);
3421 	} else {
3422 		ath_hal_intrset(ah, 0);
3423 		if (nexttbtt == intval)
3424 			intval |= HAL_BEACON_RESET_TSF;
3425 		if (ic->ic_opmode == IEEE80211_M_IBSS) {
3426 			/*
3427 			 * In IBSS mode enable the beacon timers but only
3428 			 * enable SWBA interrupts if we need to manually
3429 			 * prepare beacon frames.  Otherwise we use a
3430 			 * self-linked tx descriptor and let the hardware
3431 			 * deal with things.
3432 			 */
3433 			intval |= HAL_BEACON_ENA;
3434 			if (!sc->sc_hasveol)
3435 				sc->sc_imask |= HAL_INT_SWBA;
3436 			if ((intval & HAL_BEACON_RESET_TSF) == 0) {
3437 				/*
3438 				 * Pull nexttbtt forward to reflect
3439 				 * the current TSF.
3440 				 */
3441 				tsf = ath_hal_gettsf64(ah);
3442 				tsftu = TSF_TO_TU(tsf>>32, tsf) + FUDGE;
3443 				do {
3444 					nexttbtt += intval;
3445 				} while (nexttbtt < tsftu);
3446 			}
3447 			ath_beaconq_config(sc);
3448 		} else if (ic->ic_opmode == IEEE80211_M_HOSTAP) {
3449 			/*
3450 			 * In AP mode we enable the beacon timers and
3451 			 * SWBA interrupts to prepare beacon frames.
3452 			 */
3453 			intval |= HAL_BEACON_ENA;
3454 			sc->sc_imask |= HAL_INT_SWBA;	/* beacon prepare */
3455 			ath_beaconq_config(sc);
3456 		}
3457 		ath_hal_beaconinit(ah, nexttbtt, intval);
3458 		sc->sc_bmisscount = 0;
3459 		ath_hal_intrset(ah, sc->sc_imask);
3460 		/*
3461 		 * When using a self-linked beacon descriptor in
3462 		 * ibss mode load it once here.
3463 		 */
3464 		if (ic->ic_opmode == IEEE80211_M_IBSS && sc->sc_hasveol)
3465 			ath_beacon_start_adhoc(sc, vap);
3466 	}
3467 	sc->sc_syncbeacon = 0;
3468 #undef FUDGE
3469 #undef TSF_TO_TU
3470 }
3471 
3472 static void
3473 ath_load_cb(void *arg, bus_dma_segment_t *segs, int nsegs, int error)
3474 {
3475 	bus_addr_t *paddr = (bus_addr_t*) arg;
3476 	KASSERT(error == 0, ("error %u on bus_dma callback", error));
3477 	*paddr = segs->ds_addr;
3478 }
3479 
3480 static int
3481 ath_descdma_setup(struct ath_softc *sc,
3482 	struct ath_descdma *dd, ath_bufhead *head,
3483 	const char *name, int nbuf, int ndesc)
3484 {
3485 #define	DS2PHYS(_dd, _ds) \
3486 	((_dd)->dd_desc_paddr + ((caddr_t)(_ds) - (caddr_t)(_dd)->dd_desc))
3487 	struct ifnet *ifp = sc->sc_ifp;
3488 	struct ath_desc *ds;
3489 	struct ath_buf *bf;
3490 	int i, bsize, error;
3491 
3492 	DPRINTF(sc, ATH_DEBUG_RESET, "%s: %s DMA: %u buffers %u desc/buf\n",
3493 	    __func__, name, nbuf, ndesc);
3494 
3495 	dd->dd_name = name;
3496 	dd->dd_desc_len = sizeof(struct ath_desc) * nbuf * ndesc;
3497 
3498 	/*
3499 	 * Setup DMA descriptor area.
3500 	 */
3501 	error = bus_dma_tag_create(bus_get_dma_tag(sc->sc_dev),	/* parent */
3502 		       PAGE_SIZE, 0,		/* alignment, bounds */
3503 		       BUS_SPACE_MAXADDR_32BIT,	/* lowaddr */
3504 		       BUS_SPACE_MAXADDR,	/* highaddr */
3505 		       NULL, NULL,		/* filter, filterarg */
3506 		       dd->dd_desc_len,		/* maxsize */
3507 		       1,			/* nsegments */
3508 		       dd->dd_desc_len,		/* maxsegsize */
3509 		       BUS_DMA_ALLOCNOW,	/* flags */
3510 		       NULL,			/* lockfunc */
3511 		       NULL,			/* lockarg */
3512 		       &dd->dd_dmat);
3513 	if (error != 0) {
3514 		if_printf(ifp, "cannot allocate %s DMA tag\n", dd->dd_name);
3515 		return error;
3516 	}
3517 
3518 	/* allocate descriptors */
3519 	error = bus_dmamap_create(dd->dd_dmat, BUS_DMA_NOWAIT, &dd->dd_dmamap);
3520 	if (error != 0) {
3521 		if_printf(ifp, "unable to create dmamap for %s descriptors, "
3522 			"error %u\n", dd->dd_name, error);
3523 		goto fail0;
3524 	}
3525 
3526 	error = bus_dmamem_alloc(dd->dd_dmat, (void**) &dd->dd_desc,
3527 				 BUS_DMA_NOWAIT | BUS_DMA_COHERENT,
3528 				 &dd->dd_dmamap);
3529 	if (error != 0) {
3530 		if_printf(ifp, "unable to alloc memory for %u %s descriptors, "
3531 			"error %u\n", nbuf * ndesc, dd->dd_name, error);
3532 		goto fail1;
3533 	}
3534 
3535 	error = bus_dmamap_load(dd->dd_dmat, dd->dd_dmamap,
3536 				dd->dd_desc, dd->dd_desc_len,
3537 				ath_load_cb, &dd->dd_desc_paddr,
3538 				BUS_DMA_NOWAIT);
3539 	if (error != 0) {
3540 		if_printf(ifp, "unable to map %s descriptors, error %u\n",
3541 			dd->dd_name, error);
3542 		goto fail2;
3543 	}
3544 
3545 	ds = dd->dd_desc;
3546 	DPRINTF(sc, ATH_DEBUG_RESET, "%s: %s DMA map: %p (%lu) -> %p (%lu)\n",
3547 	    __func__, dd->dd_name, ds, (u_long) dd->dd_desc_len,
3548 	    (caddr_t) dd->dd_desc_paddr, /*XXX*/ (u_long) dd->dd_desc_len);
3549 
3550 	/* allocate rx buffers */
3551 	bsize = sizeof(struct ath_buf) * nbuf;
3552 	bf = malloc(bsize, M_ATHDEV, M_NOWAIT | M_ZERO);
3553 	if (bf == NULL) {
3554 		if_printf(ifp, "malloc of %s buffers failed, size %u\n",
3555 			dd->dd_name, bsize);
3556 		goto fail3;
3557 	}
3558 	dd->dd_bufptr = bf;
3559 
3560 	STAILQ_INIT(head);
3561 	for (i = 0; i < nbuf; i++, bf++, ds += ndesc) {
3562 		bf->bf_desc = ds;
3563 		bf->bf_daddr = DS2PHYS(dd, ds);
3564 		error = bus_dmamap_create(sc->sc_dmat, BUS_DMA_NOWAIT,
3565 				&bf->bf_dmamap);
3566 		if (error != 0) {
3567 			if_printf(ifp, "unable to create dmamap for %s "
3568 				"buffer %u, error %u\n", dd->dd_name, i, error);
3569 			ath_descdma_cleanup(sc, dd, head);
3570 			return error;
3571 		}
3572 		STAILQ_INSERT_TAIL(head, bf, bf_list);
3573 	}
3574 	return 0;
3575 fail3:
3576 	bus_dmamap_unload(dd->dd_dmat, dd->dd_dmamap);
3577 fail2:
3578 	bus_dmamem_free(dd->dd_dmat, dd->dd_desc, dd->dd_dmamap);
3579 fail1:
3580 	bus_dmamap_destroy(dd->dd_dmat, dd->dd_dmamap);
3581 fail0:
3582 	bus_dma_tag_destroy(dd->dd_dmat);
3583 	memset(dd, 0, sizeof(*dd));
3584 	return error;
3585 #undef DS2PHYS
3586 }
3587 
3588 static void
3589 ath_descdma_cleanup(struct ath_softc *sc,
3590 	struct ath_descdma *dd, ath_bufhead *head)
3591 {
3592 	struct ath_buf *bf;
3593 	struct ieee80211_node *ni;
3594 
3595 	bus_dmamap_unload(dd->dd_dmat, dd->dd_dmamap);
3596 	bus_dmamem_free(dd->dd_dmat, dd->dd_desc, dd->dd_dmamap);
3597 	bus_dmamap_destroy(dd->dd_dmat, dd->dd_dmamap);
3598 	bus_dma_tag_destroy(dd->dd_dmat);
3599 
3600 	STAILQ_FOREACH(bf, head, bf_list) {
3601 		if (bf->bf_m) {
3602 			m_freem(bf->bf_m);
3603 			bf->bf_m = NULL;
3604 		}
3605 		if (bf->bf_dmamap != NULL) {
3606 			bus_dmamap_destroy(sc->sc_dmat, bf->bf_dmamap);
3607 			bf->bf_dmamap = NULL;
3608 		}
3609 		ni = bf->bf_node;
3610 		bf->bf_node = NULL;
3611 		if (ni != NULL) {
3612 			/*
3613 			 * Reclaim node reference.
3614 			 */
3615 			ieee80211_free_node(ni);
3616 		}
3617 	}
3618 
3619 	STAILQ_INIT(head);
3620 	free(dd->dd_bufptr, M_ATHDEV);
3621 	memset(dd, 0, sizeof(*dd));
3622 }
3623 
3624 static int
3625 ath_desc_alloc(struct ath_softc *sc)
3626 {
3627 	int error;
3628 
3629 	error = ath_descdma_setup(sc, &sc->sc_rxdma, &sc->sc_rxbuf,
3630 			"rx", ath_rxbuf, 1);
3631 	if (error != 0)
3632 		return error;
3633 
3634 	error = ath_descdma_setup(sc, &sc->sc_txdma, &sc->sc_txbuf,
3635 			"tx", ath_txbuf, ATH_TXDESC);
3636 	if (error != 0) {
3637 		ath_descdma_cleanup(sc, &sc->sc_rxdma, &sc->sc_rxbuf);
3638 		return error;
3639 	}
3640 
3641 	error = ath_descdma_setup(sc, &sc->sc_bdma, &sc->sc_bbuf,
3642 			"beacon", ATH_BCBUF, 1);
3643 	if (error != 0) {
3644 		ath_descdma_cleanup(sc, &sc->sc_txdma, &sc->sc_txbuf);
3645 		ath_descdma_cleanup(sc, &sc->sc_rxdma, &sc->sc_rxbuf);
3646 		return error;
3647 	}
3648 	return 0;
3649 }
3650 
3651 static void
3652 ath_desc_free(struct ath_softc *sc)
3653 {
3654 
3655 	if (sc->sc_bdma.dd_desc_len != 0)
3656 		ath_descdma_cleanup(sc, &sc->sc_bdma, &sc->sc_bbuf);
3657 	if (sc->sc_txdma.dd_desc_len != 0)
3658 		ath_descdma_cleanup(sc, &sc->sc_txdma, &sc->sc_txbuf);
3659 	if (sc->sc_rxdma.dd_desc_len != 0)
3660 		ath_descdma_cleanup(sc, &sc->sc_rxdma, &sc->sc_rxbuf);
3661 }
3662 
3663 static struct ieee80211_node *
3664 ath_node_alloc(struct ieee80211vap *vap, const uint8_t mac[IEEE80211_ADDR_LEN])
3665 {
3666 	struct ieee80211com *ic = vap->iv_ic;
3667 	struct ath_softc *sc = ic->ic_ifp->if_softc;
3668 	const size_t space = sizeof(struct ath_node) + sc->sc_rc->arc_space;
3669 	struct ath_node *an;
3670 
3671 	an = malloc(space, M_80211_NODE, M_NOWAIT|M_ZERO);
3672 	if (an == NULL) {
3673 		/* XXX stat+msg */
3674 		return NULL;
3675 	}
3676 	ath_rate_node_init(sc, an);
3677 
3678 	DPRINTF(sc, ATH_DEBUG_NODE, "%s: an %p\n", __func__, an);
3679 	return &an->an_node;
3680 }
3681 
3682 static void
3683 ath_node_free(struct ieee80211_node *ni)
3684 {
3685 	struct ieee80211com *ic = ni->ni_ic;
3686         struct ath_softc *sc = ic->ic_ifp->if_softc;
3687 
3688 	DPRINTF(sc, ATH_DEBUG_NODE, "%s: ni %p\n", __func__, ni);
3689 
3690 	ath_rate_node_cleanup(sc, ATH_NODE(ni));
3691 	sc->sc_node_free(ni);
3692 }
3693 
3694 static void
3695 ath_node_getsignal(const struct ieee80211_node *ni, int8_t *rssi, int8_t *noise)
3696 {
3697 	struct ieee80211com *ic = ni->ni_ic;
3698 	struct ath_softc *sc = ic->ic_ifp->if_softc;
3699 	struct ath_hal *ah = sc->sc_ah;
3700 	HAL_CHANNEL hchan;
3701 
3702 	*rssi = ic->ic_node_getrssi(ni);
3703 	if (ni->ni_chan != IEEE80211_CHAN_ANYC) {
3704 		ath_mapchan(&hchan, ni->ni_chan);
3705 		*noise = ath_hal_getchannoise(ah, &hchan);
3706 	} else
3707 		*noise = -95;		/* nominally correct */
3708 }
3709 
3710 static int
3711 ath_rxbuf_init(struct ath_softc *sc, struct ath_buf *bf)
3712 {
3713 	struct ath_hal *ah = sc->sc_ah;
3714 	int error;
3715 	struct mbuf *m;
3716 	struct ath_desc *ds;
3717 
3718 	m = bf->bf_m;
3719 	if (m == NULL) {
3720 		/*
3721 		 * NB: by assigning a page to the rx dma buffer we
3722 		 * implicitly satisfy the Atheros requirement that
3723 		 * this buffer be cache-line-aligned and sized to be
3724 		 * multiple of the cache line size.  Not doing this
3725 		 * causes weird stuff to happen (for the 5210 at least).
3726 		 */
3727 		m = m_getcl(M_DONTWAIT, MT_DATA, M_PKTHDR);
3728 		if (m == NULL) {
3729 			DPRINTF(sc, ATH_DEBUG_ANY,
3730 				"%s: no mbuf/cluster\n", __func__);
3731 			sc->sc_stats.ast_rx_nombuf++;
3732 			return ENOMEM;
3733 		}
3734 		m->m_pkthdr.len = m->m_len = m->m_ext.ext_size;
3735 
3736 		error = bus_dmamap_load_mbuf_sg(sc->sc_dmat,
3737 					     bf->bf_dmamap, m,
3738 					     bf->bf_segs, &bf->bf_nseg,
3739 					     BUS_DMA_NOWAIT);
3740 		if (error != 0) {
3741 			DPRINTF(sc, ATH_DEBUG_ANY,
3742 			    "%s: bus_dmamap_load_mbuf_sg failed; error %d\n",
3743 			    __func__, error);
3744 			sc->sc_stats.ast_rx_busdma++;
3745 			m_freem(m);
3746 			return error;
3747 		}
3748 		KASSERT(bf->bf_nseg == 1,
3749 			("multi-segment packet; nseg %u", bf->bf_nseg));
3750 		bf->bf_m = m;
3751 	}
3752 	bus_dmamap_sync(sc->sc_dmat, bf->bf_dmamap, BUS_DMASYNC_PREREAD);
3753 
3754 	/*
3755 	 * Setup descriptors.  For receive we always terminate
3756 	 * the descriptor list with a self-linked entry so we'll
3757 	 * not get overrun under high load (as can happen with a
3758 	 * 5212 when ANI processing enables PHY error frames).
3759 	 *
3760 	 * To insure the last descriptor is self-linked we create
3761 	 * each descriptor as self-linked and add it to the end.  As
3762 	 * each additional descriptor is added the previous self-linked
3763 	 * entry is ``fixed'' naturally.  This should be safe even
3764 	 * if DMA is happening.  When processing RX interrupts we
3765 	 * never remove/process the last, self-linked, entry on the
3766 	 * descriptor list.  This insures the hardware always has
3767 	 * someplace to write a new frame.
3768 	 */
3769 	ds = bf->bf_desc;
3770 	ds->ds_link = bf->bf_daddr;	/* link to self */
3771 	ds->ds_data = bf->bf_segs[0].ds_addr;
3772 	ath_hal_setuprxdesc(ah, ds
3773 		, m->m_len		/* buffer size */
3774 		, 0
3775 	);
3776 
3777 	if (sc->sc_rxlink != NULL)
3778 		*sc->sc_rxlink = bf->bf_daddr;
3779 	sc->sc_rxlink = &ds->ds_link;
3780 	return 0;
3781 }
3782 
3783 /*
3784  * Extend 15-bit time stamp from rx descriptor to
3785  * a full 64-bit TSF using the specified TSF.
3786  */
3787 static __inline u_int64_t
3788 ath_extend_tsf(u_int32_t rstamp, u_int64_t tsf)
3789 {
3790 	if ((tsf & 0x7fff) < rstamp)
3791 		tsf -= 0x8000;
3792 	return ((tsf &~ 0x7fff) | rstamp);
3793 }
3794 
3795 /*
3796  * Intercept management frames to collect beacon rssi data
3797  * and to do ibss merges.
3798  */
3799 static void
3800 ath_recv_mgmt(struct ieee80211_node *ni, struct mbuf *m,
3801 	int subtype, int rssi, int noise, u_int32_t rstamp)
3802 {
3803 	struct ieee80211vap *vap = ni->ni_vap;
3804 	struct ath_softc *sc = vap->iv_ic->ic_ifp->if_softc;
3805 
3806 	/*
3807 	 * Call up first so subsequent work can use information
3808 	 * potentially stored in the node (e.g. for ibss merge).
3809 	 */
3810 	ATH_VAP(vap)->av_recv_mgmt(ni, m, subtype, rssi, noise, rstamp);
3811 	switch (subtype) {
3812 	case IEEE80211_FC0_SUBTYPE_BEACON:
3813 		/* update rssi statistics for use by the hal */
3814 		ATH_RSSI_LPF(sc->sc_halstats.ns_avgbrssi, rssi);
3815 		if (sc->sc_syncbeacon &&
3816 		    ni == vap->iv_bss && vap->iv_state == IEEE80211_S_RUN) {
3817 			/*
3818 			 * Resync beacon timers using the tsf of the beacon
3819 			 * frame we just received.
3820 			 */
3821 			ath_beacon_config(sc, vap);
3822 		}
3823 		/* fall thru... */
3824 	case IEEE80211_FC0_SUBTYPE_PROBE_RESP:
3825 		if (vap->iv_opmode == IEEE80211_M_IBSS &&
3826 		    vap->iv_state == IEEE80211_S_RUN) {
3827 			u_int64_t tsf = ath_extend_tsf(rstamp,
3828 				ath_hal_gettsf64(sc->sc_ah));
3829 			/*
3830 			 * Handle ibss merge as needed; check the tsf on the
3831 			 * frame before attempting the merge.  The 802.11 spec
3832 			 * says the station should change it's bssid to match
3833 			 * the oldest station with the same ssid, where oldest
3834 			 * is determined by the tsf.  Note that hardware
3835 			 * reconfiguration happens through callback to
3836 			 * ath_newstate as the state machine will go from
3837 			 * RUN -> RUN when this happens.
3838 			 */
3839 			if (le64toh(ni->ni_tstamp.tsf) >= tsf) {
3840 				DPRINTF(sc, ATH_DEBUG_STATE,
3841 				    "ibss merge, rstamp %u tsf %ju "
3842 				    "tstamp %ju\n", rstamp, (uintmax_t)tsf,
3843 				    (uintmax_t)ni->ni_tstamp.tsf);
3844 				(void) ieee80211_ibss_merge(ni);
3845 			}
3846 		}
3847 		break;
3848 	}
3849 }
3850 
3851 /*
3852  * Set the default antenna.
3853  */
3854 static void
3855 ath_setdefantenna(struct ath_softc *sc, u_int antenna)
3856 {
3857 	struct ath_hal *ah = sc->sc_ah;
3858 
3859 	/* XXX block beacon interrupts */
3860 	ath_hal_setdefantenna(ah, antenna);
3861 	if (sc->sc_defant != antenna)
3862 		sc->sc_stats.ast_ant_defswitch++;
3863 	sc->sc_defant = antenna;
3864 	sc->sc_rxotherant = 0;
3865 }
3866 
3867 static int
3868 ath_rx_tap(struct ifnet *ifp, struct mbuf *m,
3869 	const struct ath_rx_status *rs, u_int64_t tsf, int16_t nf)
3870 {
3871 #define	CHAN_HT		htole32(CHANNEL_HT20|CHANNEL_HT40PLUS|CHANNEL_HT40MINUS)
3872 #define	CHAN_HT20	htole32(IEEE80211_CHAN_HT20)
3873 #define	CHAN_HT40U	htole32(IEEE80211_CHAN_HT40U)
3874 #define	CHAN_HT40D	htole32(IEEE80211_CHAN_HT40D)
3875 	struct ath_softc *sc = ifp->if_softc;
3876 	u_int8_t rix;
3877 
3878 	/*
3879 	 * Discard anything shorter than an ack or cts.
3880 	 */
3881 	if (m->m_pkthdr.len < IEEE80211_ACK_LEN) {
3882 		DPRINTF(sc, ATH_DEBUG_RECV, "%s: runt packet %d\n",
3883 			__func__, m->m_pkthdr.len);
3884 		sc->sc_stats.ast_rx_tooshort++;
3885 		return 0;
3886 	}
3887 	rix = rs->rs_rate;
3888 	sc->sc_rx_th.wr_rate = sc->sc_hwmap[rix].ieeerate;
3889 	sc->sc_rx_th.wr_flags = sc->sc_hwmap[rix].rxflags;
3890 #if HAL_ABI_VERSION >= 0x07050400
3891 	sc->sc_rx_th.wr_chan_flags &= ~CHAN_HT;
3892 	if (sc->sc_rx_th.wr_rate & 0x80) {		/* HT rate */
3893 		if ((rs->rs_flags & HAL_RX_2040) == 0)
3894 			sc->sc_rx_th.wr_chan_flags |= CHAN_HT20;
3895 		else if (sc->sc_curchan.channelFlags & CHANNEL_HT40PLUS)
3896 			sc->sc_rx_th.wr_chan_flags |= CHAN_HT40U;
3897 		else
3898 			sc->sc_rx_th.wr_chan_flags |= CHAN_HT40D;
3899 		if ((rs->rs_flags & HAL_RX_GI) == 0)
3900 			sc->sc_rx_th.wr_flags |= IEEE80211_RADIOTAP_F_SHORTGI;
3901 	}
3902 #endif
3903 	sc->sc_rx_th.wr_tsf = htole64(ath_extend_tsf(rs->rs_tstamp, tsf));
3904 	if (rs->rs_status & HAL_RXERR_CRC)
3905 		sc->sc_rx_th.wr_flags |= IEEE80211_RADIOTAP_F_BADFCS;
3906 	/* XXX propagate other error flags from descriptor */
3907 	sc->sc_rx_th.wr_antsignal = rs->rs_rssi + nf;
3908 	sc->sc_rx_th.wr_antnoise = nf;
3909 	sc->sc_rx_th.wr_antenna = rs->rs_antenna;
3910 
3911 	bpf_mtap2(ifp->if_bpf, &sc->sc_rx_th, sc->sc_rx_th_len, m);
3912 
3913 	return 1;
3914 #undef CHAN_HT20
3915 #undef CHAN_HT40U
3916 #undef CHAN_HT40D
3917 #undef CHAN_HT
3918 }
3919 
3920 static void
3921 ath_handle_micerror(struct ieee80211com *ic,
3922 	struct ieee80211_frame *wh, int keyix)
3923 {
3924 	struct ieee80211_node *ni;
3925 
3926 	/* XXX recheck MIC to deal w/ chips that lie */
3927 	/* XXX discard MIC errors on !data frames */
3928 	ni = ieee80211_find_rxnode(ic, (const struct ieee80211_frame_min *) wh);
3929 	if (ni != NULL) {
3930 		ieee80211_notify_michael_failure(ni->ni_vap, wh, keyix);
3931 		ieee80211_free_node(ni);
3932 	}
3933 }
3934 
3935 static void
3936 ath_rx_proc(void *arg, int npending)
3937 {
3938 #define	PA2DESC(_sc, _pa) \
3939 	((struct ath_desc *)((caddr_t)(_sc)->sc_rxdma.dd_desc + \
3940 		((_pa) - (_sc)->sc_rxdma.dd_desc_paddr)))
3941 	struct ath_softc *sc = arg;
3942 	struct ath_buf *bf;
3943 	struct ifnet *ifp = sc->sc_ifp;
3944 	struct ieee80211com *ic = ifp->if_l2com;
3945 	struct ath_hal *ah = sc->sc_ah;
3946 	struct ath_desc *ds;
3947 	struct ath_rx_status *rs;
3948 	struct mbuf *m;
3949 	struct ieee80211_node *ni;
3950 	int len, type, ngood;
3951 	u_int phyerr;
3952 	HAL_STATUS status;
3953 	int16_t nf;
3954 	u_int64_t tsf;
3955 
3956 	DPRINTF(sc, ATH_DEBUG_RX_PROC, "%s: pending %u\n", __func__, npending);
3957 	ngood = 0;
3958 	nf = ath_hal_getchannoise(ah, &sc->sc_curchan);
3959 	tsf = ath_hal_gettsf64(ah);
3960 	do {
3961 		bf = STAILQ_FIRST(&sc->sc_rxbuf);
3962 		if (bf == NULL) {		/* NB: shouldn't happen */
3963 			if_printf(ifp, "%s: no buffer!\n", __func__);
3964 			break;
3965 		}
3966 		m = bf->bf_m;
3967 		if (m == NULL) {		/* NB: shouldn't happen */
3968 			/*
3969 			 * If mbuf allocation failed previously there
3970 			 * will be no mbuf; try again to re-populate it.
3971 			 */
3972 			/* XXX make debug msg */
3973 			if_printf(ifp, "%s: no mbuf!\n", __func__);
3974 			STAILQ_REMOVE_HEAD(&sc->sc_rxbuf, bf_list);
3975 			goto rx_next;
3976 		}
3977 		ds = bf->bf_desc;
3978 		if (ds->ds_link == bf->bf_daddr) {
3979 			/* NB: never process the self-linked entry at the end */
3980 			break;
3981 		}
3982 		/* XXX sync descriptor memory */
3983 		/*
3984 		 * Must provide the virtual address of the current
3985 		 * descriptor, the physical address, and the virtual
3986 		 * address of the next descriptor in the h/w chain.
3987 		 * This allows the HAL to look ahead to see if the
3988 		 * hardware is done with a descriptor by checking the
3989 		 * done bit in the following descriptor and the address
3990 		 * of the current descriptor the DMA engine is working
3991 		 * on.  All this is necessary because of our use of
3992 		 * a self-linked list to avoid rx overruns.
3993 		 */
3994 		rs = &bf->bf_status.ds_rxstat;
3995 		status = ath_hal_rxprocdesc(ah, ds,
3996 				bf->bf_daddr, PA2DESC(sc, ds->ds_link), rs);
3997 #ifdef ATH_DEBUG
3998 		if (sc->sc_debug & ATH_DEBUG_RECV_DESC)
3999 			ath_printrxbuf(bf, 0, status == HAL_OK);
4000 #endif
4001 		if (status == HAL_EINPROGRESS)
4002 			break;
4003 		STAILQ_REMOVE_HEAD(&sc->sc_rxbuf, bf_list);
4004 		if (rs->rs_status != 0) {
4005 			if (rs->rs_status & HAL_RXERR_CRC)
4006 				sc->sc_stats.ast_rx_crcerr++;
4007 			if (rs->rs_status & HAL_RXERR_FIFO)
4008 				sc->sc_stats.ast_rx_fifoerr++;
4009 			if (rs->rs_status & HAL_RXERR_PHY) {
4010 				sc->sc_stats.ast_rx_phyerr++;
4011 				phyerr = rs->rs_phyerr & 0x1f;
4012 				sc->sc_stats.ast_rx_phy[phyerr]++;
4013 				goto rx_error;	/* NB: don't count in ierrors */
4014 			}
4015 			if (rs->rs_status & HAL_RXERR_DECRYPT) {
4016 				/*
4017 				 * Decrypt error.  If the error occurred
4018 				 * because there was no hardware key, then
4019 				 * let the frame through so the upper layers
4020 				 * can process it.  This is necessary for 5210
4021 				 * parts which have no way to setup a ``clear''
4022 				 * key cache entry.
4023 				 *
4024 				 * XXX do key cache faulting
4025 				 */
4026 				if (rs->rs_keyix == HAL_RXKEYIX_INVALID)
4027 					goto rx_accept;
4028 				sc->sc_stats.ast_rx_badcrypt++;
4029 			}
4030 			if (rs->rs_status & HAL_RXERR_MIC) {
4031 				sc->sc_stats.ast_rx_badmic++;
4032 				/*
4033 				 * Do minimal work required to hand off
4034 				 * the 802.11 header for notifcation.
4035 				 */
4036 				/* XXX frag's and qos frames */
4037 				len = rs->rs_datalen;
4038 				if (len >= sizeof (struct ieee80211_frame)) {
4039 					bus_dmamap_sync(sc->sc_dmat,
4040 					    bf->bf_dmamap,
4041 					    BUS_DMASYNC_POSTREAD);
4042 					ath_handle_micerror(ic,
4043 					    mtod(m, struct ieee80211_frame *),
4044 					    sc->sc_splitmic ?
4045 						rs->rs_keyix-32 : rs->rs_keyix);
4046 				}
4047 			}
4048 			ifp->if_ierrors++;
4049 rx_error:
4050 			/*
4051 			 * Cleanup any pending partial frame.
4052 			 */
4053 			if (sc->sc_rxpending != NULL) {
4054 				m_freem(sc->sc_rxpending);
4055 				sc->sc_rxpending = NULL;
4056 			}
4057 			/*
4058 			 * When a tap is present pass error frames
4059 			 * that have been requested.  By default we
4060 			 * pass decrypt+mic errors but others may be
4061 			 * interesting (e.g. crc).
4062 			 */
4063 			if (bpf_peers_present(ifp->if_bpf) &&
4064 			    (rs->rs_status & sc->sc_monpass)) {
4065 				bus_dmamap_sync(sc->sc_dmat, bf->bf_dmamap,
4066 				    BUS_DMASYNC_POSTREAD);
4067 				/* NB: bpf needs the mbuf length setup */
4068 				len = rs->rs_datalen;
4069 				m->m_pkthdr.len = m->m_len = len;
4070 				(void) ath_rx_tap(ifp, m, rs, tsf, nf);
4071 			}
4072 			/* XXX pass MIC errors up for s/w reclaculation */
4073 			goto rx_next;
4074 		}
4075 rx_accept:
4076 		/*
4077 		 * Sync and unmap the frame.  At this point we're
4078 		 * committed to passing the mbuf somewhere so clear
4079 		 * bf_m; this means a new mbuf must be allocated
4080 		 * when the rx descriptor is setup again to receive
4081 		 * another frame.
4082 		 */
4083 		bus_dmamap_sync(sc->sc_dmat, bf->bf_dmamap,
4084 		    BUS_DMASYNC_POSTREAD);
4085 		bus_dmamap_unload(sc->sc_dmat, bf->bf_dmamap);
4086 		bf->bf_m = NULL;
4087 
4088 		len = rs->rs_datalen;
4089 		m->m_len = len;
4090 
4091 		if (rs->rs_more) {
4092 			/*
4093 			 * Frame spans multiple descriptors; save
4094 			 * it for the next completed descriptor, it
4095 			 * will be used to construct a jumbogram.
4096 			 */
4097 			if (sc->sc_rxpending != NULL) {
4098 				/* NB: max frame size is currently 2 clusters */
4099 				sc->sc_stats.ast_rx_toobig++;
4100 				m_freem(sc->sc_rxpending);
4101 			}
4102 			m->m_pkthdr.rcvif = ifp;
4103 			m->m_pkthdr.len = len;
4104 			sc->sc_rxpending = m;
4105 			goto rx_next;
4106 		} else if (sc->sc_rxpending != NULL) {
4107 			/*
4108 			 * This is the second part of a jumbogram,
4109 			 * chain it to the first mbuf, adjust the
4110 			 * frame length, and clear the rxpending state.
4111 			 */
4112 			sc->sc_rxpending->m_next = m;
4113 			sc->sc_rxpending->m_pkthdr.len += len;
4114 			m = sc->sc_rxpending;
4115 			sc->sc_rxpending = NULL;
4116 		} else {
4117 			/*
4118 			 * Normal single-descriptor receive; setup
4119 			 * the rcvif and packet length.
4120 			 */
4121 			m->m_pkthdr.rcvif = ifp;
4122 			m->m_pkthdr.len = len;
4123 		}
4124 
4125 		ifp->if_ipackets++;
4126 		sc->sc_stats.ast_ant_rx[rs->rs_antenna]++;
4127 
4128 		if (bpf_peers_present(ifp->if_bpf) &&
4129 		    !ath_rx_tap(ifp, m, rs, tsf, nf)) {
4130 			m_freem(m);		/* XXX reclaim */
4131 			goto rx_next;
4132 		}
4133 
4134 		/*
4135 		 * From this point on we assume the frame is at least
4136 		 * as large as ieee80211_frame_min; verify that.
4137 		 */
4138 		if (len < IEEE80211_MIN_LEN) {
4139 			DPRINTF(sc, ATH_DEBUG_RECV, "%s: short packet %d\n",
4140 				__func__, len);
4141 			sc->sc_stats.ast_rx_tooshort++;
4142 			m_freem(m);
4143 			goto rx_next;
4144 		}
4145 
4146 		if (IFF_DUMPPKTS(sc, ATH_DEBUG_RECV)) {
4147 			ieee80211_dump_pkt(ic, mtod(m, caddr_t), len,
4148 				   sc->sc_hwmap[rs->rs_rate].ieeerate,
4149 				   rs->rs_rssi);
4150 		}
4151 
4152 		m_adj(m, -IEEE80211_CRC_LEN);
4153 
4154 		/*
4155 		 * Locate the node for sender, track state, and then
4156 		 * pass the (referenced) node up to the 802.11 layer
4157 		 * for its use.
4158 		 */
4159 		ni = ieee80211_find_rxnode_withkey(ic,
4160 			mtod(m, const struct ieee80211_frame_min *),
4161 			rs->rs_keyix == HAL_RXKEYIX_INVALID ?
4162 				IEEE80211_KEYIX_NONE : rs->rs_keyix);
4163 		if (ni != NULL) {
4164 			/*
4165 			 * Sending station is known, dispatch directly.
4166 			 */
4167 			type = ieee80211_input(ni, m,
4168 			    rs->rs_rssi, nf, rs->rs_tstamp);
4169 			ieee80211_free_node(ni);
4170 			/*
4171 			 * Arrange to update the last rx timestamp only for
4172 			 * frames from our ap when operating in station mode.
4173 			 * This assumes the rx key is always setup when
4174 			 * associated.
4175 			 */
4176 			if (ic->ic_opmode == IEEE80211_M_STA &&
4177 			    rs->rs_keyix != HAL_RXKEYIX_INVALID)
4178 				ngood++;
4179 		} else {
4180 			type = ieee80211_input_all(ic, m,
4181 			    rs->rs_rssi, nf, rs->rs_tstamp);
4182 		}
4183 		/*
4184 		 * Track rx rssi and do any rx antenna management.
4185 		 */
4186 		ATH_RSSI_LPF(sc->sc_halstats.ns_avgrssi, rs->rs_rssi);
4187 		if (sc->sc_diversity) {
4188 			/*
4189 			 * When using fast diversity, change the default rx
4190 			 * antenna if diversity chooses the other antenna 3
4191 			 * times in a row.
4192 			 */
4193 			if (sc->sc_defant != rs->rs_antenna) {
4194 				if (++sc->sc_rxotherant >= 3)
4195 					ath_setdefantenna(sc, rs->rs_antenna);
4196 			} else
4197 				sc->sc_rxotherant = 0;
4198 		}
4199 		if (sc->sc_softled) {
4200 			/*
4201 			 * Blink for any data frame.  Otherwise do a
4202 			 * heartbeat-style blink when idle.  The latter
4203 			 * is mainly for station mode where we depend on
4204 			 * periodic beacon frames to trigger the poll event.
4205 			 */
4206 			if (type == IEEE80211_FC0_TYPE_DATA) {
4207 				sc->sc_rxrate = rs->rs_rate;
4208 				ath_led_event(sc, ATH_LED_RX);
4209 			} else if (ticks - sc->sc_ledevent >= sc->sc_ledidle)
4210 				ath_led_event(sc, ATH_LED_POLL);
4211 		}
4212 rx_next:
4213 		STAILQ_INSERT_TAIL(&sc->sc_rxbuf, bf, bf_list);
4214 	} while (ath_rxbuf_init(sc, bf) == 0);
4215 
4216 	/* rx signal state monitoring */
4217 	ath_hal_rxmonitor(ah, &sc->sc_halstats, &sc->sc_curchan);
4218 	if (ngood)
4219 		sc->sc_lastrx = tsf;
4220 
4221 	if ((ifp->if_drv_flags & IFF_DRV_OACTIVE) == 0 &&
4222 	    !IFQ_IS_EMPTY(&ifp->if_snd))
4223 		ath_start(ifp);
4224 
4225 #undef PA2DESC
4226 }
4227 
4228 static void
4229 ath_txq_init(struct ath_softc *sc, struct ath_txq *txq, int qnum)
4230 {
4231 	txq->axq_qnum = qnum;
4232 	txq->axq_depth = 0;
4233 	txq->axq_intrcnt = 0;
4234 	txq->axq_link = NULL;
4235 	STAILQ_INIT(&txq->axq_q);
4236 	ATH_TXQ_LOCK_INIT(sc, txq);
4237 	TAILQ_INIT(&txq->axq_stageq);
4238 	txq->axq_curage = 0;
4239 }
4240 
4241 /*
4242  * Setup a h/w transmit queue.
4243  */
4244 static struct ath_txq *
4245 ath_txq_setup(struct ath_softc *sc, int qtype, int subtype)
4246 {
4247 #define	N(a)	(sizeof(a)/sizeof(a[0]))
4248 	struct ath_hal *ah = sc->sc_ah;
4249 	HAL_TXQ_INFO qi;
4250 	int qnum;
4251 
4252 	memset(&qi, 0, sizeof(qi));
4253 	qi.tqi_subtype = subtype;
4254 	qi.tqi_aifs = HAL_TXQ_USEDEFAULT;
4255 	qi.tqi_cwmin = HAL_TXQ_USEDEFAULT;
4256 	qi.tqi_cwmax = HAL_TXQ_USEDEFAULT;
4257 	/*
4258 	 * Enable interrupts only for EOL and DESC conditions.
4259 	 * We mark tx descriptors to receive a DESC interrupt
4260 	 * when a tx queue gets deep; otherwise waiting for the
4261 	 * EOL to reap descriptors.  Note that this is done to
4262 	 * reduce interrupt load and this only defers reaping
4263 	 * descriptors, never transmitting frames.  Aside from
4264 	 * reducing interrupts this also permits more concurrency.
4265 	 * The only potential downside is if the tx queue backs
4266 	 * up in which case the top half of the kernel may backup
4267 	 * due to a lack of tx descriptors.
4268 	 */
4269 	qi.tqi_qflags = HAL_TXQ_TXEOLINT_ENABLE | HAL_TXQ_TXDESCINT_ENABLE;
4270 	qnum = ath_hal_setuptxqueue(ah, qtype, &qi);
4271 	if (qnum == -1) {
4272 		/*
4273 		 * NB: don't print a message, this happens
4274 		 * normally on parts with too few tx queues
4275 		 */
4276 		return NULL;
4277 	}
4278 	if (qnum >= N(sc->sc_txq)) {
4279 		device_printf(sc->sc_dev,
4280 			"hal qnum %u out of range, max %zu!\n",
4281 			qnum, N(sc->sc_txq));
4282 		ath_hal_releasetxqueue(ah, qnum);
4283 		return NULL;
4284 	}
4285 	if (!ATH_TXQ_SETUP(sc, qnum)) {
4286 		ath_txq_init(sc, &sc->sc_txq[qnum], qnum);
4287 		sc->sc_txqsetup |= 1<<qnum;
4288 	}
4289 	return &sc->sc_txq[qnum];
4290 #undef N
4291 }
4292 
4293 /*
4294  * Setup a hardware data transmit queue for the specified
4295  * access control.  The hal may not support all requested
4296  * queues in which case it will return a reference to a
4297  * previously setup queue.  We record the mapping from ac's
4298  * to h/w queues for use by ath_tx_start and also track
4299  * the set of h/w queues being used to optimize work in the
4300  * transmit interrupt handler and related routines.
4301  */
4302 static int
4303 ath_tx_setup(struct ath_softc *sc, int ac, int haltype)
4304 {
4305 #define	N(a)	(sizeof(a)/sizeof(a[0]))
4306 	struct ath_txq *txq;
4307 
4308 	if (ac >= N(sc->sc_ac2q)) {
4309 		device_printf(sc->sc_dev, "AC %u out of range, max %zu!\n",
4310 			ac, N(sc->sc_ac2q));
4311 		return 0;
4312 	}
4313 	txq = ath_txq_setup(sc, HAL_TX_QUEUE_DATA, haltype);
4314 	if (txq != NULL) {
4315 		sc->sc_ac2q[ac] = txq;
4316 		return 1;
4317 	} else
4318 		return 0;
4319 #undef N
4320 }
4321 
4322 /*
4323  * Update WME parameters for a transmit queue.
4324  */
4325 static int
4326 ath_txq_update(struct ath_softc *sc, int ac)
4327 {
4328 #define	ATH_EXPONENT_TO_VALUE(v)	((1<<v)-1)
4329 #define	ATH_TXOP_TO_US(v)		(v<<5)
4330 	struct ifnet *ifp = sc->sc_ifp;
4331 	struct ieee80211com *ic = ifp->if_l2com;
4332 	struct ath_txq *txq = sc->sc_ac2q[ac];
4333 	struct wmeParams *wmep = &ic->ic_wme.wme_chanParams.cap_wmeParams[ac];
4334 	struct ath_hal *ah = sc->sc_ah;
4335 	HAL_TXQ_INFO qi;
4336 
4337 	ath_hal_gettxqueueprops(ah, txq->axq_qnum, &qi);
4338 	qi.tqi_aifs = wmep->wmep_aifsn;
4339 	qi.tqi_cwmin = ATH_EXPONENT_TO_VALUE(wmep->wmep_logcwmin);
4340 	qi.tqi_cwmax = ATH_EXPONENT_TO_VALUE(wmep->wmep_logcwmax);
4341 	qi.tqi_burstTime = ATH_TXOP_TO_US(wmep->wmep_txopLimit);
4342 
4343 	if (!ath_hal_settxqueueprops(ah, txq->axq_qnum, &qi)) {
4344 		if_printf(ifp, "unable to update hardware queue "
4345 			"parameters for %s traffic!\n",
4346 			ieee80211_wme_acnames[ac]);
4347 		return 0;
4348 	} else {
4349 		ath_hal_resettxqueue(ah, txq->axq_qnum); /* push to h/w */
4350 		return 1;
4351 	}
4352 #undef ATH_TXOP_TO_US
4353 #undef ATH_EXPONENT_TO_VALUE
4354 }
4355 
4356 /*
4357  * Callback from the 802.11 layer to update WME parameters.
4358  */
4359 static int
4360 ath_wme_update(struct ieee80211com *ic)
4361 {
4362 	struct ath_softc *sc = ic->ic_ifp->if_softc;
4363 
4364 	return !ath_txq_update(sc, WME_AC_BE) ||
4365 	    !ath_txq_update(sc, WME_AC_BK) ||
4366 	    !ath_txq_update(sc, WME_AC_VI) ||
4367 	    !ath_txq_update(sc, WME_AC_VO) ? EIO : 0;
4368 }
4369 
4370 /*
4371  * Reclaim resources for a setup queue.
4372  */
4373 static void
4374 ath_tx_cleanupq(struct ath_softc *sc, struct ath_txq *txq)
4375 {
4376 
4377 	ath_hal_releasetxqueue(sc->sc_ah, txq->axq_qnum);
4378 	ATH_TXQ_LOCK_DESTROY(txq);
4379 	sc->sc_txqsetup &= ~(1<<txq->axq_qnum);
4380 }
4381 
4382 /*
4383  * Reclaim all tx queue resources.
4384  */
4385 static void
4386 ath_tx_cleanup(struct ath_softc *sc)
4387 {
4388 	int i;
4389 
4390 	ATH_TXBUF_LOCK_DESTROY(sc);
4391 	for (i = 0; i < HAL_NUM_TX_QUEUES; i++)
4392 		if (ATH_TXQ_SETUP(sc, i))
4393 			ath_tx_cleanupq(sc, &sc->sc_txq[i]);
4394 }
4395 
4396 /*
4397  * Return h/w rate index for an IEEE rate (w/o basic rate bit).
4398  */
4399 static int
4400 ath_tx_findrix(const HAL_RATE_TABLE *rt, int rate)
4401 {
4402 	int i;
4403 
4404 	for (i = 0; i < rt->rateCount; i++)
4405 		if ((rt->info[i].dot11Rate & IEEE80211_RATE_VAL) == rate)
4406 			return i;
4407 	return 0;		/* NB: lowest rate */
4408 }
4409 
4410 /*
4411  * Reclaim mbuf resources.  For fragmented frames we
4412  * need to claim each frag chained with m_nextpkt.
4413  */
4414 static void
4415 ath_freetx(struct mbuf *m)
4416 {
4417 	struct mbuf *next;
4418 
4419 	do {
4420 		next = m->m_nextpkt;
4421 		m->m_nextpkt = NULL;
4422 		m_freem(m);
4423 	} while ((m = next) != NULL);
4424 }
4425 
4426 static int
4427 ath_tx_dmasetup(struct ath_softc *sc, struct ath_buf *bf, struct mbuf *m0)
4428 {
4429 	struct mbuf *m;
4430 	int error;
4431 
4432 	/*
4433 	 * Load the DMA map so any coalescing is done.  This
4434 	 * also calculates the number of descriptors we need.
4435 	 */
4436 	error = bus_dmamap_load_mbuf_sg(sc->sc_dmat, bf->bf_dmamap, m0,
4437 				     bf->bf_segs, &bf->bf_nseg,
4438 				     BUS_DMA_NOWAIT);
4439 	if (error == EFBIG) {
4440 		/* XXX packet requires too many descriptors */
4441 		bf->bf_nseg = ATH_TXDESC+1;
4442 	} else if (error != 0) {
4443 		sc->sc_stats.ast_tx_busdma++;
4444 		ath_freetx(m0);
4445 		return error;
4446 	}
4447 	/*
4448 	 * Discard null packets and check for packets that
4449 	 * require too many TX descriptors.  We try to convert
4450 	 * the latter to a cluster.
4451 	 */
4452 	if (bf->bf_nseg > ATH_TXDESC) {		/* too many desc's, linearize */
4453 		sc->sc_stats.ast_tx_linear++;
4454 		m = m_collapse(m0, M_DONTWAIT, ATH_TXDESC);
4455 		if (m == NULL) {
4456 			ath_freetx(m0);
4457 			sc->sc_stats.ast_tx_nombuf++;
4458 			return ENOMEM;
4459 		}
4460 		m0 = m;
4461 		error = bus_dmamap_load_mbuf_sg(sc->sc_dmat, bf->bf_dmamap, m0,
4462 					     bf->bf_segs, &bf->bf_nseg,
4463 					     BUS_DMA_NOWAIT);
4464 		if (error != 0) {
4465 			sc->sc_stats.ast_tx_busdma++;
4466 			ath_freetx(m0);
4467 			return error;
4468 		}
4469 		KASSERT(bf->bf_nseg <= ATH_TXDESC,
4470 		    ("too many segments after defrag; nseg %u", bf->bf_nseg));
4471 	} else if (bf->bf_nseg == 0) {		/* null packet, discard */
4472 		sc->sc_stats.ast_tx_nodata++;
4473 		ath_freetx(m0);
4474 		return EIO;
4475 	}
4476 	DPRINTF(sc, ATH_DEBUG_XMIT, "%s: m %p len %u\n",
4477 		__func__, m0, m0->m_pkthdr.len);
4478 	bus_dmamap_sync(sc->sc_dmat, bf->bf_dmamap, BUS_DMASYNC_PREWRITE);
4479 	bf->bf_m = m0;
4480 
4481 	return 0;
4482 }
4483 
4484 static void
4485 ath_tx_handoff(struct ath_softc *sc, struct ath_txq *txq, struct ath_buf *bf)
4486 {
4487 	struct ath_hal *ah = sc->sc_ah;
4488 	struct ath_desc *ds, *ds0;
4489 	int i;
4490 
4491 	/*
4492 	 * Fillin the remainder of the descriptor info.
4493 	 */
4494 	ds0 = ds = bf->bf_desc;
4495 	for (i = 0; i < bf->bf_nseg; i++, ds++) {
4496 		ds->ds_data = bf->bf_segs[i].ds_addr;
4497 		if (i == bf->bf_nseg - 1)
4498 			ds->ds_link = 0;
4499 		else
4500 			ds->ds_link = bf->bf_daddr + sizeof(*ds) * (i + 1);
4501 		ath_hal_filltxdesc(ah, ds
4502 			, bf->bf_segs[i].ds_len	/* segment length */
4503 			, i == 0		/* first segment */
4504 			, i == bf->bf_nseg - 1	/* last segment */
4505 			, ds0			/* first descriptor */
4506 		);
4507 		DPRINTF(sc, ATH_DEBUG_XMIT,
4508 			"%s: %d: %08x %08x %08x %08x %08x %08x\n",
4509 			__func__, i, ds->ds_link, ds->ds_data,
4510 			ds->ds_ctl0, ds->ds_ctl1, ds->ds_hw[0], ds->ds_hw[1]);
4511 	}
4512 	/*
4513 	 * Insert the frame on the outbound list and pass it on
4514 	 * to the hardware.  Multicast frames buffered for power
4515 	 * save stations and transmit from the CAB queue are stored
4516 	 * on a s/w only queue and loaded on to the CAB queue in
4517 	 * the SWBA handler since frames only go out on DTIM and
4518 	 * to avoid possible races.
4519 	 */
4520 	ATH_TXQ_LOCK(txq);
4521 	if (txq->axq_qnum != ATH_TXQ_SWQ) {
4522 		ATH_TXQ_INSERT_TAIL(txq, bf, bf_list);
4523 		if (txq->axq_link == NULL) {
4524 			ath_hal_puttxbuf(ah, txq->axq_qnum, bf->bf_daddr);
4525 			DPRINTF(sc, ATH_DEBUG_XMIT,
4526 			    "%s: TXDP[%u] = %p (%p) depth %d\n", __func__,
4527 			    txq->axq_qnum, (caddr_t)bf->bf_daddr, bf->bf_desc,
4528 			    txq->axq_depth);
4529 		} else {
4530 			*txq->axq_link = bf->bf_daddr;
4531 			DPRINTF(sc, ATH_DEBUG_XMIT,
4532 			    "%s: link[%u](%p)=%p (%p) depth %d\n", __func__,
4533 			    txq->axq_qnum, txq->axq_link,
4534 			    (caddr_t)bf->bf_daddr, bf->bf_desc, txq->axq_depth);
4535 		}
4536 		txq->axq_link = &bf->bf_desc[bf->bf_nseg - 1].ds_link;
4537 		ath_hal_txstart(ah, txq->axq_qnum);
4538 	} else {
4539 		if (txq->axq_link != NULL) {
4540 			struct ath_buf *last = ATH_TXQ_LAST(txq);
4541 			struct ieee80211_frame *wh;
4542 
4543 			/* mark previous frame */
4544 			wh = mtod(last->bf_m, struct ieee80211_frame *);
4545 			wh->i_fc[1] |= IEEE80211_FC1_MORE_DATA;
4546 			bus_dmamap_sync(sc->sc_dmat, last->bf_dmamap,
4547 			    BUS_DMASYNC_PREWRITE);
4548 
4549 			/* link descriptor */
4550 			*txq->axq_link = bf->bf_daddr;
4551 		}
4552 		ATH_TXQ_INSERT_TAIL(txq, bf, bf_list);
4553 		txq->axq_link = &bf->bf_desc[bf->bf_nseg - 1].ds_link;
4554 	}
4555 	ATH_TXQ_UNLOCK(txq);
4556 }
4557 
4558 static int
4559 ath_tx_start(struct ath_softc *sc, struct ieee80211_node *ni, struct ath_buf *bf,
4560     struct mbuf *m0)
4561 {
4562 	struct ieee80211vap *vap = ni->ni_vap;
4563 	struct ath_vap *avp = ATH_VAP(vap);
4564 	struct ath_hal *ah = sc->sc_ah;
4565 	struct ifnet *ifp = sc->sc_ifp;
4566 	struct ieee80211com *ic = ifp->if_l2com;
4567 	const struct chanAccParams *cap = &ic->ic_wme.wme_chanParams;
4568 	int error, iswep, ismcast, isfrag, ismrr;
4569 	int keyix, hdrlen, pktlen, try0;
4570 	u_int8_t rix, txrate, ctsrate;
4571 	u_int8_t cix = 0xff;		/* NB: silence compiler */
4572 	struct ath_desc *ds;
4573 	struct ath_txq *txq;
4574 	struct ieee80211_frame *wh;
4575 	u_int subtype, flags, ctsduration;
4576 	HAL_PKT_TYPE atype;
4577 	const HAL_RATE_TABLE *rt;
4578 	HAL_BOOL shortPreamble;
4579 	struct ath_node *an;
4580 	u_int pri;
4581 
4582 	wh = mtod(m0, struct ieee80211_frame *);
4583 	iswep = wh->i_fc[1] & IEEE80211_FC1_WEP;
4584 	ismcast = IEEE80211_IS_MULTICAST(wh->i_addr1);
4585 	isfrag = m0->m_flags & M_FRAG;
4586 	hdrlen = ieee80211_anyhdrsize(wh);
4587 	/*
4588 	 * Packet length must not include any
4589 	 * pad bytes; deduct them here.
4590 	 */
4591 	pktlen = m0->m_pkthdr.len - (hdrlen & 3);
4592 
4593 	if (iswep) {
4594 		const struct ieee80211_cipher *cip;
4595 		struct ieee80211_key *k;
4596 
4597 		/*
4598 		 * Construct the 802.11 header+trailer for an encrypted
4599 		 * frame. The only reason this can fail is because of an
4600 		 * unknown or unsupported cipher/key type.
4601 		 */
4602 		k = ieee80211_crypto_encap(ni, m0);
4603 		if (k == NULL) {
4604 			/*
4605 			 * This can happen when the key is yanked after the
4606 			 * frame was queued.  Just discard the frame; the
4607 			 * 802.11 layer counts failures and provides
4608 			 * debugging/diagnostics.
4609 			 */
4610 			ath_freetx(m0);
4611 			return EIO;
4612 		}
4613 		/*
4614 		 * Adjust the packet + header lengths for the crypto
4615 		 * additions and calculate the h/w key index.  When
4616 		 * a s/w mic is done the frame will have had any mic
4617 		 * added to it prior to entry so m0->m_pkthdr.len will
4618 		 * account for it. Otherwise we need to add it to the
4619 		 * packet length.
4620 		 */
4621 		cip = k->wk_cipher;
4622 		hdrlen += cip->ic_header;
4623 		pktlen += cip->ic_header + cip->ic_trailer;
4624 		/* NB: frags always have any TKIP MIC done in s/w */
4625 		if ((k->wk_flags & IEEE80211_KEY_SWMIC) == 0 && !isfrag)
4626 			pktlen += cip->ic_miclen;
4627 		keyix = k->wk_keyix;
4628 
4629 		/* packet header may have moved, reset our local pointer */
4630 		wh = mtod(m0, struct ieee80211_frame *);
4631 	} else if (ni->ni_ucastkey.wk_cipher == &ieee80211_cipher_none) {
4632 		/*
4633 		 * Use station key cache slot, if assigned.
4634 		 */
4635 		keyix = ni->ni_ucastkey.wk_keyix;
4636 		if (keyix == IEEE80211_KEYIX_NONE)
4637 			keyix = HAL_TXKEYIX_INVALID;
4638 	} else
4639 		keyix = HAL_TXKEYIX_INVALID;
4640 
4641 	pktlen += IEEE80211_CRC_LEN;
4642 
4643 	/*
4644 	 * Load the DMA map so any coalescing is done.  This
4645 	 * also calculates the number of descriptors we need.
4646 	 */
4647 	error = ath_tx_dmasetup(sc, bf, m0);
4648 	if (error != 0)
4649 		return error;
4650 	bf->bf_node = ni;			/* NB: held reference */
4651 	m0 = bf->bf_m;				/* NB: may have changed */
4652 	wh = mtod(m0, struct ieee80211_frame *);
4653 
4654 	/* setup descriptors */
4655 	ds = bf->bf_desc;
4656 	rt = sc->sc_currates;
4657 	KASSERT(rt != NULL, ("no rate table, mode %u", sc->sc_curmode));
4658 
4659 	/*
4660 	 * NB: the 802.11 layer marks whether or not we should
4661 	 * use short preamble based on the current mode and
4662 	 * negotiated parameters.
4663 	 */
4664 	if ((ic->ic_flags & IEEE80211_F_SHPREAMBLE) &&
4665 	    (ni->ni_capinfo & IEEE80211_CAPINFO_SHORT_PREAMBLE)) {
4666 		shortPreamble = AH_TRUE;
4667 		sc->sc_stats.ast_tx_shortpre++;
4668 	} else {
4669 		shortPreamble = AH_FALSE;
4670 	}
4671 
4672 	an = ATH_NODE(ni);
4673 	flags = HAL_TXDESC_CLRDMASK;		/* XXX needed for crypto errs */
4674 	ismrr = 0;				/* default no multi-rate retry*/
4675 	pri = M_WME_GETAC(m0);			/* honor classification */
4676 	/* XXX use txparams instead of fixed values */
4677 	/*
4678 	 * Calculate Atheros packet type from IEEE80211 packet header,
4679 	 * setup for rate calculations, and select h/w transmit queue.
4680 	 */
4681 	switch (wh->i_fc[0] & IEEE80211_FC0_TYPE_MASK) {
4682 	case IEEE80211_FC0_TYPE_MGT:
4683 		subtype = wh->i_fc[0] & IEEE80211_FC0_SUBTYPE_MASK;
4684 		if (subtype == IEEE80211_FC0_SUBTYPE_BEACON)
4685 			atype = HAL_PKT_TYPE_BEACON;
4686 		else if (subtype == IEEE80211_FC0_SUBTYPE_PROBE_RESP)
4687 			atype = HAL_PKT_TYPE_PROBE_RESP;
4688 		else if (subtype == IEEE80211_FC0_SUBTYPE_ATIM)
4689 			atype = HAL_PKT_TYPE_ATIM;
4690 		else
4691 			atype = HAL_PKT_TYPE_NORMAL;	/* XXX */
4692 		rix = an->an_mgmtrix;
4693 		txrate = rt->info[rix].rateCode;
4694 		if (shortPreamble)
4695 			txrate |= rt->info[rix].shortPreamble;
4696 		try0 = ATH_TXMGTTRY;
4697 		flags |= HAL_TXDESC_INTREQ;	/* force interrupt */
4698 		break;
4699 	case IEEE80211_FC0_TYPE_CTL:
4700 		atype = HAL_PKT_TYPE_PSPOLL;	/* stop setting of duration */
4701 		rix = an->an_mgmtrix;
4702 		txrate = rt->info[rix].rateCode;
4703 		if (shortPreamble)
4704 			txrate |= rt->info[rix].shortPreamble;
4705 		try0 = ATH_TXMGTTRY;
4706 		flags |= HAL_TXDESC_INTREQ;	/* force interrupt */
4707 		break;
4708 	case IEEE80211_FC0_TYPE_DATA:
4709 		atype = HAL_PKT_TYPE_NORMAL;		/* default */
4710 		/*
4711 		 * Data frames: multicast frames go out at a fixed rate,
4712 		 * EAPOL frames use the mgmt frame rate; otherwise consult
4713 		 * the rate control module for the rate to use.
4714 		 */
4715 		if (ismcast) {
4716 			rix = an->an_mcastrix;
4717 			txrate = rt->info[rix].rateCode;
4718 			if (shortPreamble)
4719 				txrate |= rt->info[rix].shortPreamble;
4720 			try0 = 1;
4721 		} else if (m0->m_flags & M_EAPOL) {
4722 			/* XXX? maybe always use long preamble? */
4723 			rix = an->an_mgmtrix;
4724 			txrate = rt->info[rix].rateCode;
4725 			if (shortPreamble)
4726 				txrate |= rt->info[rix].shortPreamble;
4727 			try0 = ATH_TXMAXTRY;	/* XXX?too many? */
4728 		} else {
4729 			ath_rate_findrate(sc, an, shortPreamble, pktlen,
4730 				&rix, &try0, &txrate);
4731 			sc->sc_txrate = txrate;		/* for LED blinking */
4732 			sc->sc_lastdatarix = rix;	/* for fast frames */
4733 			if (try0 != ATH_TXMAXTRY)
4734 				ismrr = 1;
4735 		}
4736 		if (cap->cap_wmeParams[pri].wmep_noackPolicy)
4737 			flags |= HAL_TXDESC_NOACK;
4738 		break;
4739 	default:
4740 		if_printf(ifp, "bogus frame type 0x%x (%s)\n",
4741 			wh->i_fc[0] & IEEE80211_FC0_TYPE_MASK, __func__);
4742 		/* XXX statistic */
4743 		ath_freetx(m0);
4744 		return EIO;
4745 	}
4746 	txq = sc->sc_ac2q[pri];
4747 
4748 	/*
4749 	 * When servicing one or more stations in power-save mode
4750 	 * (or) if there is some mcast data waiting on the mcast
4751 	 * queue (to prevent out of order delivery) multicast
4752 	 * frames must be buffered until after the beacon.
4753 	 */
4754 	if (ismcast && (vap->iv_ps_sta || avp->av_mcastq.axq_depth))
4755 		txq = &avp->av_mcastq;
4756 
4757 	/*
4758 	 * Calculate miscellaneous flags.
4759 	 */
4760 	if (ismcast) {
4761 		flags |= HAL_TXDESC_NOACK;	/* no ack on broad/multicast */
4762 	} else if (pktlen > vap->iv_rtsthreshold &&
4763 	    (ni->ni_ath_flags & IEEE80211_NODE_FF) == 0) {
4764 		flags |= HAL_TXDESC_RTSENA;	/* RTS based on frame length */
4765 		cix = rt->info[rix].controlRate;
4766 		sc->sc_stats.ast_tx_rts++;
4767 	}
4768 	if (flags & HAL_TXDESC_NOACK)		/* NB: avoid double counting */
4769 		sc->sc_stats.ast_tx_noack++;
4770 
4771 	/*
4772 	 * If 802.11g protection is enabled, determine whether
4773 	 * to use RTS/CTS or just CTS.  Note that this is only
4774 	 * done for OFDM unicast frames.
4775 	 */
4776 	if ((ic->ic_flags & IEEE80211_F_USEPROT) &&
4777 	    rt->info[rix].phy == IEEE80211_T_OFDM &&
4778 	    (flags & HAL_TXDESC_NOACK) == 0) {
4779 		/* XXX fragments must use CCK rates w/ protection */
4780 		if (ic->ic_protmode == IEEE80211_PROT_RTSCTS)
4781 			flags |= HAL_TXDESC_RTSENA;
4782 		else if (ic->ic_protmode == IEEE80211_PROT_CTSONLY)
4783 			flags |= HAL_TXDESC_CTSENA;
4784 		if (isfrag) {
4785 			/*
4786 			 * For frags it would be desirable to use the
4787 			 * highest CCK rate for RTS/CTS.  But stations
4788 			 * farther away may detect it at a lower CCK rate
4789 			 * so use the configured protection rate instead
4790 			 * (for now).
4791 			 */
4792 			cix = rt->info[sc->sc_protrix].controlRate;
4793 		} else
4794 			cix = rt->info[sc->sc_protrix].controlRate;
4795 		sc->sc_stats.ast_tx_protect++;
4796 	}
4797 
4798 	/*
4799 	 * Calculate duration.  This logically belongs in the 802.11
4800 	 * layer but it lacks sufficient information to calculate it.
4801 	 */
4802 	if ((flags & HAL_TXDESC_NOACK) == 0 &&
4803 	    (wh->i_fc[0] & IEEE80211_FC0_TYPE_MASK) != IEEE80211_FC0_TYPE_CTL) {
4804 		u_int16_t dur;
4805 		if (shortPreamble)
4806 			dur = rt->info[rix].spAckDuration;
4807 		else
4808 			dur = rt->info[rix].lpAckDuration;
4809 		if (wh->i_fc[1] & IEEE80211_FC1_MORE_FRAG) {
4810 			dur += dur;		/* additional SIFS+ACK */
4811 			KASSERT(m0->m_nextpkt != NULL, ("no fragment"));
4812 			/*
4813 			 * Include the size of next fragment so NAV is
4814 			 * updated properly.  The last fragment uses only
4815 			 * the ACK duration
4816 			 */
4817 			dur += ath_hal_computetxtime(ah, rt,
4818 					m0->m_nextpkt->m_pkthdr.len,
4819 					rix, shortPreamble);
4820 		}
4821 		if (isfrag) {
4822 			/*
4823 			 * Force hardware to use computed duration for next
4824 			 * fragment by disabling multi-rate retry which updates
4825 			 * duration based on the multi-rate duration table.
4826 			 */
4827 			ismrr = 0;
4828 			try0 = ATH_TXMGTTRY;	/* XXX? */
4829 		}
4830 		*(u_int16_t *)wh->i_dur = htole16(dur);
4831 	}
4832 
4833 	/*
4834 	 * Calculate RTS/CTS rate and duration if needed.
4835 	 */
4836 	ctsduration = 0;
4837 	if (flags & (HAL_TXDESC_RTSENA|HAL_TXDESC_CTSENA)) {
4838 		/*
4839 		 * CTS transmit rate is derived from the transmit rate
4840 		 * by looking in the h/w rate table.  We must also factor
4841 		 * in whether or not a short preamble is to be used.
4842 		 */
4843 		/* NB: cix is set above where RTS/CTS is enabled */
4844 		KASSERT(cix != 0xff, ("cix not setup"));
4845 		ctsrate = rt->info[cix].rateCode;
4846 		/*
4847 		 * Compute the transmit duration based on the frame
4848 		 * size and the size of an ACK frame.  We call into the
4849 		 * HAL to do the computation since it depends on the
4850 		 * characteristics of the actual PHY being used.
4851 		 *
4852 		 * NB: CTS is assumed the same size as an ACK so we can
4853 		 *     use the precalculated ACK durations.
4854 		 */
4855 		if (shortPreamble) {
4856 			ctsrate |= rt->info[cix].shortPreamble;
4857 			if (flags & HAL_TXDESC_RTSENA)		/* SIFS + CTS */
4858 				ctsduration += rt->info[cix].spAckDuration;
4859 			ctsduration += ath_hal_computetxtime(ah,
4860 				rt, pktlen, rix, AH_TRUE);
4861 			if ((flags & HAL_TXDESC_NOACK) == 0)	/* SIFS + ACK */
4862 				ctsduration += rt->info[rix].spAckDuration;
4863 		} else {
4864 			if (flags & HAL_TXDESC_RTSENA)		/* SIFS + CTS */
4865 				ctsduration += rt->info[cix].lpAckDuration;
4866 			ctsduration += ath_hal_computetxtime(ah,
4867 				rt, pktlen, rix, AH_FALSE);
4868 			if ((flags & HAL_TXDESC_NOACK) == 0)	/* SIFS + ACK */
4869 				ctsduration += rt->info[rix].lpAckDuration;
4870 		}
4871 		/*
4872 		 * Must disable multi-rate retry when using RTS/CTS.
4873 		 */
4874 		ismrr = 0;
4875 		try0 = ATH_TXMGTTRY;		/* XXX */
4876 	} else
4877 		ctsrate = 0;
4878 
4879 	/*
4880 	 * At this point we are committed to sending the frame
4881 	 * and we don't need to look at m_nextpkt; clear it in
4882 	 * case this frame is part of frag chain.
4883 	 */
4884 	m0->m_nextpkt = NULL;
4885 
4886 	if (IFF_DUMPPKTS(sc, ATH_DEBUG_XMIT))
4887 		ieee80211_dump_pkt(ic, mtod(m0, caddr_t), m0->m_len,
4888 			sc->sc_hwmap[txrate].ieeerate, -1);
4889 
4890 	if (bpf_peers_present(ifp->if_bpf)) {
4891 		u_int64_t tsf = ath_hal_gettsf64(ah);
4892 
4893 		sc->sc_tx_th.wt_tsf = htole64(tsf);
4894 		sc->sc_tx_th.wt_flags = sc->sc_hwmap[txrate].txflags;
4895 		if (iswep)
4896 			sc->sc_tx_th.wt_flags |= IEEE80211_RADIOTAP_F_WEP;
4897 		if (isfrag)
4898 			sc->sc_tx_th.wt_flags |= IEEE80211_RADIOTAP_F_FRAG;
4899 		sc->sc_tx_th.wt_rate = sc->sc_hwmap[txrate].ieeerate;
4900 		sc->sc_tx_th.wt_txpower = ni->ni_txpower;
4901 		sc->sc_tx_th.wt_antenna = sc->sc_txantenna;
4902 
4903 		bpf_mtap2(ifp->if_bpf, &sc->sc_tx_th, sc->sc_tx_th_len, m0);
4904 	}
4905 
4906 	/*
4907 	 * Determine if a tx interrupt should be generated for
4908 	 * this descriptor.  We take a tx interrupt to reap
4909 	 * descriptors when the h/w hits an EOL condition or
4910 	 * when the descriptor is specifically marked to generate
4911 	 * an interrupt.  We periodically mark descriptors in this
4912 	 * way to insure timely replenishing of the supply needed
4913 	 * for sending frames.  Defering interrupts reduces system
4914 	 * load and potentially allows more concurrent work to be
4915 	 * done but if done to aggressively can cause senders to
4916 	 * backup.
4917 	 *
4918 	 * NB: use >= to deal with sc_txintrperiod changing
4919 	 *     dynamically through sysctl.
4920 	 */
4921 	if (flags & HAL_TXDESC_INTREQ) {
4922 		txq->axq_intrcnt = 0;
4923 	} else if (++txq->axq_intrcnt >= sc->sc_txintrperiod) {
4924 		flags |= HAL_TXDESC_INTREQ;
4925 		txq->axq_intrcnt = 0;
4926 	}
4927 
4928 	/*
4929 	 * Formulate first tx descriptor with tx controls.
4930 	 */
4931 	/* XXX check return value? */
4932 	ath_hal_setuptxdesc(ah, ds
4933 		, pktlen		/* packet length */
4934 		, hdrlen		/* header length */
4935 		, atype			/* Atheros packet type */
4936 		, ni->ni_txpower	/* txpower */
4937 		, txrate, try0		/* series 0 rate/tries */
4938 		, keyix			/* key cache index */
4939 		, sc->sc_txantenna	/* antenna mode */
4940 		, flags			/* flags */
4941 		, ctsrate		/* rts/cts rate */
4942 		, ctsduration		/* rts/cts duration */
4943 	);
4944 	bf->bf_flags = flags;
4945 	/*
4946 	 * Setup the multi-rate retry state only when we're
4947 	 * going to use it.  This assumes ath_hal_setuptxdesc
4948 	 * initializes the descriptors (so we don't have to)
4949 	 * when the hardware supports multi-rate retry and
4950 	 * we don't use it.
4951 	 */
4952 	if (ismrr)
4953 		ath_rate_setupxtxdesc(sc, an, ds, shortPreamble, rix);
4954 
4955 	ath_tx_handoff(sc, txq, bf);
4956 	return 0;
4957 }
4958 
4959 /*
4960  * Process completed xmit descriptors from the specified queue.
4961  */
4962 static int
4963 ath_tx_processq(struct ath_softc *sc, struct ath_txq *txq)
4964 {
4965 	struct ath_hal *ah = sc->sc_ah;
4966 	struct ifnet *ifp = sc->sc_ifp;
4967 	struct ieee80211com *ic = ifp->if_l2com;
4968 	struct ath_buf *bf;
4969 	struct ath_desc *ds, *ds0;
4970 	struct ath_tx_status *ts;
4971 	struct ieee80211_node *ni;
4972 	struct ath_node *an;
4973 	int sr, lr, pri, nacked;
4974 	HAL_STATUS status;
4975 
4976 	DPRINTF(sc, ATH_DEBUG_TX_PROC, "%s: tx queue %u head %p link %p\n",
4977 		__func__, txq->axq_qnum,
4978 		(caddr_t)(uintptr_t) ath_hal_gettxbuf(sc->sc_ah, txq->axq_qnum),
4979 		txq->axq_link);
4980 	nacked = 0;
4981 	for (;;) {
4982 		ATH_TXQ_LOCK(txq);
4983 		txq->axq_intrcnt = 0;	/* reset periodic desc intr count */
4984 		bf = STAILQ_FIRST(&txq->axq_q);
4985 		if (bf == NULL) {
4986 			ATH_TXQ_UNLOCK(txq);
4987 			break;
4988 		}
4989 		ds0 = &bf->bf_desc[0];
4990 		ds = &bf->bf_desc[bf->bf_nseg - 1];
4991 		ts = &bf->bf_status.ds_txstat;
4992 		status = ath_hal_txprocdesc(ah, ds, ts);
4993 #ifdef ATH_DEBUG
4994 		if (sc->sc_debug & ATH_DEBUG_XMIT_DESC)
4995 			ath_printtxbuf(bf, txq->axq_qnum, 0, status == HAL_OK);
4996 #endif
4997 		if (status == HAL_EINPROGRESS) {
4998 			ATH_TXQ_UNLOCK(txq);
4999 			break;
5000 		}
5001 		ATH_TXQ_REMOVE_HEAD(txq, bf_list);
5002 		if (txq->axq_depth == 0)
5003 			txq->axq_link = NULL;
5004 		ATH_TXQ_UNLOCK(txq);
5005 
5006 		ni = bf->bf_node;
5007 		if (ni != NULL) {
5008 			an = ATH_NODE(ni);
5009 			if (ts->ts_status == 0) {
5010 				u_int8_t txant = ts->ts_antenna;
5011 				sc->sc_stats.ast_ant_tx[txant]++;
5012 				sc->sc_ant_tx[txant]++;
5013 				if (ts->ts_rate & HAL_TXSTAT_ALTRATE)
5014 					sc->sc_stats.ast_tx_altrate++;
5015 				sc->sc_stats.ast_tx_rssi = ts->ts_rssi;
5016 				ATH_RSSI_LPF(sc->sc_halstats.ns_avgtxrssi,
5017 					ts->ts_rssi);
5018 				pri = M_WME_GETAC(bf->bf_m);
5019 				if (pri >= WME_AC_VO)
5020 					ic->ic_wme.wme_hipri_traffic++;
5021 				ni->ni_inact = ni->ni_inact_reload;
5022 			} else {
5023 				if (ts->ts_status & HAL_TXERR_XRETRY)
5024 					sc->sc_stats.ast_tx_xretries++;
5025 				if (ts->ts_status & HAL_TXERR_FIFO)
5026 					sc->sc_stats.ast_tx_fifoerr++;
5027 				if (ts->ts_status & HAL_TXERR_FILT)
5028 					sc->sc_stats.ast_tx_filtered++;
5029 				if (bf->bf_m->m_flags & M_FF)
5030 					sc->sc_stats.ast_ff_txerr++;
5031 			}
5032 			sr = ts->ts_shortretry;
5033 			lr = ts->ts_longretry;
5034 			sc->sc_stats.ast_tx_shortretry += sr;
5035 			sc->sc_stats.ast_tx_longretry += lr;
5036 			/*
5037 			 * Hand the descriptor to the rate control algorithm.
5038 			 */
5039 			if ((ts->ts_status & HAL_TXERR_FILT) == 0 &&
5040 			    (bf->bf_flags & HAL_TXDESC_NOACK) == 0) {
5041 				/*
5042 				 * If frame was ack'd update the last rx time
5043 				 * used to workaround phantom bmiss interrupts.
5044 				 */
5045 				if (ts->ts_status == 0)
5046 					nacked++;
5047 				ath_rate_tx_complete(sc, an, bf);
5048 			}
5049 			/*
5050 			 * Do any tx complete callback.  Note this must
5051 			 * be done before releasing the node reference.
5052 			 */
5053 			if (bf->bf_m->m_flags & M_TXCB)
5054 				ieee80211_process_callback(ni, bf->bf_m,
5055 					ts->ts_status);
5056 			/*
5057 			 * Reclaim reference to node.
5058 			 *
5059 			 * NB: the node may be reclaimed here if, for example
5060 			 *     this is a DEAUTH message that was sent and the
5061 			 *     node was timed out due to inactivity.
5062 			 */
5063 			ieee80211_free_node(ni);
5064 		}
5065 		bus_dmamap_sync(sc->sc_dmat, bf->bf_dmamap,
5066 		    BUS_DMASYNC_POSTWRITE);
5067 		bus_dmamap_unload(sc->sc_dmat, bf->bf_dmamap);
5068 
5069 		m_freem(bf->bf_m);
5070 		bf->bf_m = NULL;
5071 		bf->bf_node = NULL;
5072 
5073 		ATH_TXBUF_LOCK(sc);
5074 		STAILQ_INSERT_TAIL(&sc->sc_txbuf, bf, bf_list);
5075 		ATH_TXBUF_UNLOCK(sc);
5076 	}
5077 	/*
5078 	 * Flush fast-frame staging queue when traffic slows.
5079 	 */
5080 	if (txq->axq_depth <= 1)
5081 		ath_ff_stageq_flush(sc, txq, ath_ff_always);
5082 	return nacked;
5083 }
5084 
5085 static __inline int
5086 txqactive(struct ath_hal *ah, int qnum)
5087 {
5088 	u_int32_t txqs = 1<<qnum;
5089 	ath_hal_gettxintrtxqs(ah, &txqs);
5090 	return (txqs & (1<<qnum));
5091 }
5092 
5093 /*
5094  * Deferred processing of transmit interrupt; special-cased
5095  * for a single hardware transmit queue (e.g. 5210 and 5211).
5096  */
5097 static void
5098 ath_tx_proc_q0(void *arg, int npending)
5099 {
5100 	struct ath_softc *sc = arg;
5101 	struct ifnet *ifp = sc->sc_ifp;
5102 
5103 	if (txqactive(sc->sc_ah, 0) && ath_tx_processq(sc, &sc->sc_txq[0]))
5104 		sc->sc_lastrx = ath_hal_gettsf64(sc->sc_ah);
5105 	if (txqactive(sc->sc_ah, sc->sc_cabq->axq_qnum))
5106 		ath_tx_processq(sc, sc->sc_cabq);
5107 	ifp->if_drv_flags &= ~IFF_DRV_OACTIVE;
5108 	ifp->if_timer = 0;
5109 
5110 	if (sc->sc_softled)
5111 		ath_led_event(sc, ATH_LED_TX);
5112 
5113 	ath_start(ifp);
5114 }
5115 
5116 /*
5117  * Deferred processing of transmit interrupt; special-cased
5118  * for four hardware queues, 0-3 (e.g. 5212 w/ WME support).
5119  */
5120 static void
5121 ath_tx_proc_q0123(void *arg, int npending)
5122 {
5123 	struct ath_softc *sc = arg;
5124 	struct ifnet *ifp = sc->sc_ifp;
5125 	int nacked;
5126 
5127 	/*
5128 	 * Process each active queue.
5129 	 */
5130 	nacked = 0;
5131 	if (txqactive(sc->sc_ah, 0))
5132 		nacked += ath_tx_processq(sc, &sc->sc_txq[0]);
5133 	if (txqactive(sc->sc_ah, 1))
5134 		nacked += ath_tx_processq(sc, &sc->sc_txq[1]);
5135 	if (txqactive(sc->sc_ah, 2))
5136 		nacked += ath_tx_processq(sc, &sc->sc_txq[2]);
5137 	if (txqactive(sc->sc_ah, 3))
5138 		nacked += ath_tx_processq(sc, &sc->sc_txq[3]);
5139 	if (txqactive(sc->sc_ah, sc->sc_cabq->axq_qnum))
5140 		ath_tx_processq(sc, sc->sc_cabq);
5141 	if (nacked)
5142 		sc->sc_lastrx = ath_hal_gettsf64(sc->sc_ah);
5143 
5144 	ifp->if_drv_flags &= ~IFF_DRV_OACTIVE;
5145 	ifp->if_timer = 0;
5146 
5147 	if (sc->sc_softled)
5148 		ath_led_event(sc, ATH_LED_TX);
5149 
5150 	ath_start(ifp);
5151 }
5152 
5153 /*
5154  * Deferred processing of transmit interrupt.
5155  */
5156 static void
5157 ath_tx_proc(void *arg, int npending)
5158 {
5159 	struct ath_softc *sc = arg;
5160 	struct ifnet *ifp = sc->sc_ifp;
5161 	int i, nacked;
5162 
5163 	/*
5164 	 * Process each active queue.
5165 	 */
5166 	nacked = 0;
5167 	for (i = 0; i < HAL_NUM_TX_QUEUES; i++)
5168 		if (ATH_TXQ_SETUP(sc, i) && txqactive(sc->sc_ah, i))
5169 			nacked += ath_tx_processq(sc, &sc->sc_txq[i]);
5170 	if (nacked)
5171 		sc->sc_lastrx = ath_hal_gettsf64(sc->sc_ah);
5172 
5173 	ifp->if_drv_flags &= ~IFF_DRV_OACTIVE;
5174 	ifp->if_timer = 0;
5175 
5176 	if (sc->sc_softled)
5177 		ath_led_event(sc, ATH_LED_TX);
5178 
5179 	ath_start(ifp);
5180 }
5181 
5182 static void
5183 ath_tx_draintxq(struct ath_softc *sc, struct ath_txq *txq)
5184 {
5185 #ifdef ATH_DEBUG
5186 	struct ath_hal *ah = sc->sc_ah;
5187 #endif
5188 	struct ieee80211_node *ni;
5189 	struct ath_buf *bf;
5190 	u_int ix;
5191 
5192 	/*
5193 	 * NB: this assumes output has been stopped and
5194 	 *     we do not need to block ath_tx_tasklet
5195 	 */
5196 	for (ix = 0;; ix++) {
5197 		ATH_TXQ_LOCK(txq);
5198 		bf = STAILQ_FIRST(&txq->axq_q);
5199 		if (bf == NULL) {
5200 			txq->axq_link = NULL;
5201 			ATH_TXQ_UNLOCK(txq);
5202 			break;
5203 		}
5204 		ATH_TXQ_REMOVE_HEAD(txq, bf_list);
5205 		ATH_TXQ_UNLOCK(txq);
5206 #ifdef ATH_DEBUG
5207 		if (sc->sc_debug & ATH_DEBUG_RESET) {
5208 			struct ieee80211com *ic = sc->sc_ifp->if_l2com;
5209 
5210 			ath_printtxbuf(bf, txq->axq_qnum, ix,
5211 				ath_hal_txprocdesc(ah, bf->bf_desc,
5212 				    &bf->bf_status.ds_txstat) == HAL_OK);
5213 			ieee80211_dump_pkt(ic, mtod(bf->bf_m, caddr_t),
5214 				bf->bf_m->m_len, 0, -1);
5215 		}
5216 #endif /* ATH_DEBUG */
5217 		bus_dmamap_unload(sc->sc_dmat, bf->bf_dmamap);
5218 		ni = bf->bf_node;
5219 		bf->bf_node = NULL;
5220 		if (ni != NULL) {
5221 			/*
5222 			 * Do any callback and reclaim the node reference.
5223 			 */
5224 			if (bf->bf_m->m_flags & M_TXCB)
5225 				ieee80211_process_callback(ni, bf->bf_m, -1);
5226 			ieee80211_free_node(ni);
5227 		}
5228 		m_freem(bf->bf_m);
5229 		bf->bf_m = NULL;
5230 
5231 		ATH_TXBUF_LOCK(sc);
5232 		STAILQ_INSERT_TAIL(&sc->sc_txbuf, bf, bf_list);
5233 		ATH_TXBUF_UNLOCK(sc);
5234 	}
5235 }
5236 
5237 static void
5238 ath_tx_stopdma(struct ath_softc *sc, struct ath_txq *txq)
5239 {
5240 	struct ath_hal *ah = sc->sc_ah;
5241 
5242 	DPRINTF(sc, ATH_DEBUG_RESET, "%s: tx queue [%u] %p, link %p\n",
5243 	    __func__, txq->axq_qnum,
5244 	    (caddr_t)(uintptr_t) ath_hal_gettxbuf(ah, txq->axq_qnum),
5245 	    txq->axq_link);
5246 	(void) ath_hal_stoptxdma(ah, txq->axq_qnum);
5247 }
5248 
5249 /*
5250  * Drain the transmit queues and reclaim resources.
5251  */
5252 static void
5253 ath_draintxq(struct ath_softc *sc)
5254 {
5255 	struct ath_hal *ah = sc->sc_ah;
5256 	struct ifnet *ifp = sc->sc_ifp;
5257 	int i;
5258 
5259 	/* XXX return value */
5260 	if (!sc->sc_invalid) {
5261 		/* don't touch the hardware if marked invalid */
5262 		DPRINTF(sc, ATH_DEBUG_RESET, "%s: tx queue [%u] %p, link %p\n",
5263 		    __func__, sc->sc_bhalq,
5264 		    (caddr_t)(uintptr_t) ath_hal_gettxbuf(ah, sc->sc_bhalq),
5265 		    NULL);
5266 		(void) ath_hal_stoptxdma(ah, sc->sc_bhalq);
5267 		for (i = 0; i < HAL_NUM_TX_QUEUES; i++)
5268 			if (ATH_TXQ_SETUP(sc, i))
5269 				ath_tx_stopdma(sc, &sc->sc_txq[i]);
5270 	}
5271 	for (i = 0; i < HAL_NUM_TX_QUEUES; i++)
5272 		if (ATH_TXQ_SETUP(sc, i))
5273 			ath_tx_draintxq(sc, &sc->sc_txq[i]);
5274 #ifdef ATH_DEBUG
5275 	if (sc->sc_debug & ATH_DEBUG_RESET) {
5276 		struct ath_buf *bf = STAILQ_FIRST(&sc->sc_bbuf);
5277 		if (bf != NULL && bf->bf_m != NULL) {
5278 			ath_printtxbuf(bf, sc->sc_bhalq, 0,
5279 				ath_hal_txprocdesc(ah, bf->bf_desc,
5280 				    &bf->bf_status.ds_txstat) == HAL_OK);
5281 			ieee80211_dump_pkt(ifp->if_l2com, mtod(bf->bf_m, caddr_t),
5282 				bf->bf_m->m_len, 0, -1);
5283 		}
5284 	}
5285 #endif /* ATH_DEBUG */
5286 	ifp->if_drv_flags &= ~IFF_DRV_OACTIVE;
5287 	ifp->if_timer = 0;
5288 }
5289 
5290 /*
5291  * Disable the receive h/w in preparation for a reset.
5292  */
5293 static void
5294 ath_stoprecv(struct ath_softc *sc)
5295 {
5296 #define	PA2DESC(_sc, _pa) \
5297 	((struct ath_desc *)((caddr_t)(_sc)->sc_rxdma.dd_desc + \
5298 		((_pa) - (_sc)->sc_rxdma.dd_desc_paddr)))
5299 	struct ath_hal *ah = sc->sc_ah;
5300 
5301 	ath_hal_stoppcurecv(ah);	/* disable PCU */
5302 	ath_hal_setrxfilter(ah, 0);	/* clear recv filter */
5303 	ath_hal_stopdmarecv(ah);	/* disable DMA engine */
5304 	DELAY(3000);			/* 3ms is long enough for 1 frame */
5305 #ifdef ATH_DEBUG
5306 	if (sc->sc_debug & (ATH_DEBUG_RESET | ATH_DEBUG_FATAL)) {
5307 		struct ath_buf *bf;
5308 		u_int ix;
5309 
5310 		printf("%s: rx queue %p, link %p\n", __func__,
5311 			(caddr_t)(uintptr_t) ath_hal_getrxbuf(ah), sc->sc_rxlink);
5312 		ix = 0;
5313 		STAILQ_FOREACH(bf, &sc->sc_rxbuf, bf_list) {
5314 			struct ath_desc *ds = bf->bf_desc;
5315 			struct ath_rx_status *rs = &bf->bf_status.ds_rxstat;
5316 			HAL_STATUS status = ath_hal_rxprocdesc(ah, ds,
5317 				bf->bf_daddr, PA2DESC(sc, ds->ds_link), rs);
5318 			if (status == HAL_OK || (sc->sc_debug & ATH_DEBUG_FATAL))
5319 				ath_printrxbuf(bf, ix, status == HAL_OK);
5320 			ix++;
5321 		}
5322 	}
5323 #endif
5324 	if (sc->sc_rxpending != NULL) {
5325 		m_freem(sc->sc_rxpending);
5326 		sc->sc_rxpending = NULL;
5327 	}
5328 	sc->sc_rxlink = NULL;		/* just in case */
5329 #undef PA2DESC
5330 }
5331 
5332 /*
5333  * Enable the receive h/w following a reset.
5334  */
5335 static int
5336 ath_startrecv(struct ath_softc *sc)
5337 {
5338 	struct ath_hal *ah = sc->sc_ah;
5339 	struct ath_buf *bf;
5340 
5341 	sc->sc_rxlink = NULL;
5342 	sc->sc_rxpending = NULL;
5343 	STAILQ_FOREACH(bf, &sc->sc_rxbuf, bf_list) {
5344 		int error = ath_rxbuf_init(sc, bf);
5345 		if (error != 0) {
5346 			DPRINTF(sc, ATH_DEBUG_RECV,
5347 				"%s: ath_rxbuf_init failed %d\n",
5348 				__func__, error);
5349 			return error;
5350 		}
5351 	}
5352 
5353 	bf = STAILQ_FIRST(&sc->sc_rxbuf);
5354 	ath_hal_putrxbuf(ah, bf->bf_daddr);
5355 	ath_hal_rxena(ah);		/* enable recv descriptors */
5356 	ath_mode_init(sc);		/* set filters, etc. */
5357 	ath_hal_startpcurecv(ah);	/* re-enable PCU/DMA engine */
5358 	return 0;
5359 }
5360 
5361 /*
5362  * Update internal state after a channel change.
5363  */
5364 static void
5365 ath_chan_change(struct ath_softc *sc, struct ieee80211_channel *chan)
5366 {
5367 	enum ieee80211_phymode mode;
5368 
5369 	/*
5370 	 * Change channels and update the h/w rate map
5371 	 * if we're switching; e.g. 11a to 11b/g.
5372 	 */
5373 	if (IEEE80211_IS_CHAN_HALF(chan))
5374 		mode = IEEE80211_MODE_HALF;
5375 	else if (IEEE80211_IS_CHAN_QUARTER(chan))
5376 		mode = IEEE80211_MODE_QUARTER;
5377 	else
5378 		mode = ieee80211_chan2mode(chan);
5379 	if (mode != sc->sc_curmode)
5380 		ath_setcurmode(sc, mode);
5381 
5382 	sc->sc_rx_th.wr_chan_flags = htole32(chan->ic_flags);
5383 	sc->sc_tx_th.wt_chan_flags = sc->sc_rx_th.wr_chan_flags;
5384 	sc->sc_rx_th.wr_chan_freq = htole16(chan->ic_freq);
5385 	sc->sc_tx_th.wt_chan_freq = sc->sc_rx_th.wr_chan_freq;
5386 	sc->sc_rx_th.wr_chan_ieee = chan->ic_ieee;
5387 	sc->sc_tx_th.wt_chan_ieee = sc->sc_rx_th.wr_chan_ieee;
5388 	sc->sc_rx_th.wr_chan_maxpow = chan->ic_maxregpower;
5389 	sc->sc_tx_th.wt_chan_maxpow = sc->sc_rx_th.wr_chan_maxpow;
5390 }
5391 
5392 /*
5393  * Set/change channels.  If the channel is really being changed,
5394  * it's done by reseting the chip.  To accomplish this we must
5395  * first cleanup any pending DMA, then restart stuff after a la
5396  * ath_init.
5397  */
5398 static int
5399 ath_chan_set(struct ath_softc *sc, struct ieee80211_channel *chan)
5400 {
5401 	struct ifnet *ifp = sc->sc_ifp;
5402 	struct ieee80211com *ic = ifp->if_l2com;
5403 	struct ath_hal *ah = sc->sc_ah;
5404 	HAL_CHANNEL hchan;
5405 
5406 	/*
5407 	 * Convert to a HAL channel description with
5408 	 * the flags constrained to reflect the current
5409 	 * operating mode.
5410 	 */
5411 	ath_mapchan(&hchan, chan);
5412 
5413 	DPRINTF(sc, ATH_DEBUG_RESET,
5414 	    "%s: %u (%u MHz, hal flags 0x%x) -> %u (%u MHz, hal flags 0x%x)\n",
5415 	    __func__,
5416 	    ath_hal_mhz2ieee(ah, sc->sc_curchan.channel,
5417 		sc->sc_curchan.channelFlags),
5418 	    	sc->sc_curchan.channel, sc->sc_curchan.channelFlags,
5419 	    ath_hal_mhz2ieee(ah, hchan.channel, hchan.channelFlags),
5420 	        hchan.channel, hchan.channelFlags);
5421 	if (hchan.channel != sc->sc_curchan.channel ||
5422 	    hchan.channelFlags != sc->sc_curchan.channelFlags) {
5423 		HAL_STATUS status;
5424 
5425 		/*
5426 		 * To switch channels clear any pending DMA operations;
5427 		 * wait long enough for the RX fifo to drain, reset the
5428 		 * hardware at the new frequency, and then re-enable
5429 		 * the relevant bits of the h/w.
5430 		 */
5431 		ath_hal_intrset(ah, 0);		/* disable interrupts */
5432 		ath_draintxq(sc);		/* clear pending tx frames */
5433 		ath_stoprecv(sc);		/* turn off frame recv */
5434 		if (!ath_hal_reset(ah, sc->sc_opmode, &hchan, AH_TRUE, &status)) {
5435 			if_printf(ifp, "%s: unable to reset "
5436 			    "channel %u (%u Mhz, flags 0x%x hal flags 0x%x), "
5437 			    "hal status %u\n", __func__,
5438 			    ieee80211_chan2ieee(ic, chan), chan->ic_freq,
5439 			    chan->ic_flags, hchan.channelFlags, status);
5440 			return EIO;
5441 		}
5442 		sc->sc_curchan = hchan;
5443 		sc->sc_diversity = ath_hal_getdiversity(ah);
5444 		sc->sc_calinterval = 1;
5445 		sc->sc_caltries = 0;
5446 
5447 		/*
5448 		 * Re-enable rx framework.
5449 		 */
5450 		if (ath_startrecv(sc) != 0) {
5451 			if_printf(ifp, "%s: unable to restart recv logic\n",
5452 			    __func__);
5453 			return EIO;
5454 		}
5455 
5456 		/*
5457 		 * Change channels and update the h/w rate map
5458 		 * if we're switching; e.g. 11a to 11b/g.
5459 		 */
5460 		ath_chan_change(sc, chan);
5461 
5462 		/*
5463 		 * Re-enable interrupts.
5464 		 */
5465 		ath_hal_intrset(ah, sc->sc_imask);
5466 	}
5467 	return 0;
5468 }
5469 
5470 /*
5471  * Periodically recalibrate the PHY to account
5472  * for temperature/environment changes.
5473  */
5474 static void
5475 ath_calibrate(void *arg)
5476 {
5477 	struct ath_softc *sc = arg;
5478 	struct ath_hal *ah = sc->sc_ah;
5479 	HAL_BOOL iqCalDone;
5480 
5481 	sc->sc_stats.ast_per_cal++;
5482 
5483 	if (ath_hal_getrfgain(ah) == HAL_RFGAIN_NEED_CHANGE) {
5484 		/*
5485 		 * Rfgain is out of bounds, reset the chip
5486 		 * to load new gain values.
5487 		 */
5488 		DPRINTF(sc, ATH_DEBUG_CALIBRATE,
5489 			"%s: rfgain change\n", __func__);
5490 		sc->sc_stats.ast_per_rfgain++;
5491 		ath_reset(sc->sc_ifp);
5492 	}
5493 	if (!ath_hal_calibrate(ah, &sc->sc_curchan, &iqCalDone)) {
5494 		DPRINTF(sc, ATH_DEBUG_ANY,
5495 			"%s: calibration of channel %u failed\n",
5496 			__func__, sc->sc_curchan.channel);
5497 		sc->sc_stats.ast_per_calfail++;
5498 	}
5499 	/*
5500 	 * Calibrate noise floor data again in case of change.
5501 	 */
5502 	ath_hal_process_noisefloor(ah);
5503 	/*
5504 	 * Poll more frequently when the IQ calibration is in
5505 	 * progress to speedup loading the final settings.
5506 	 * We temper this aggressive polling with an exponential
5507 	 * back off after 4 tries up to ath_calinterval.
5508 	 */
5509 	if (iqCalDone || sc->sc_calinterval >= ath_calinterval) {
5510 		sc->sc_caltries = 0;
5511 		sc->sc_calinterval = ath_calinterval;
5512 	} else if (sc->sc_caltries > 4) {
5513 		sc->sc_caltries = 0;
5514 		sc->sc_calinterval <<= 1;
5515 		if (sc->sc_calinterval > ath_calinterval)
5516 			sc->sc_calinterval = ath_calinterval;
5517 	}
5518 	KASSERT(0 < sc->sc_calinterval && sc->sc_calinterval <= ath_calinterval,
5519 		("bad calibration interval %u", sc->sc_calinterval));
5520 
5521 	DPRINTF(sc, ATH_DEBUG_CALIBRATE,
5522 		"%s: next +%u (%siqCalDone tries %u)\n", __func__,
5523 		sc->sc_calinterval, iqCalDone ? "" : "!", sc->sc_caltries);
5524 	sc->sc_caltries++;
5525 	callout_reset(&sc->sc_cal_ch, sc->sc_calinterval * hz,
5526 		ath_calibrate, sc);
5527 }
5528 
5529 static void
5530 ath_scan_start(struct ieee80211com *ic)
5531 {
5532 	struct ifnet *ifp = ic->ic_ifp;
5533 	struct ath_softc *sc = ifp->if_softc;
5534 	struct ath_hal *ah = sc->sc_ah;
5535 	u_int32_t rfilt;
5536 
5537 	/* XXX calibration timer? */
5538 
5539 	sc->sc_scanning = 1;
5540 	sc->sc_syncbeacon = 0;
5541 	rfilt = ath_calcrxfilter(sc);
5542 	ath_hal_setrxfilter(ah, rfilt);
5543 	ath_hal_setassocid(ah, ifp->if_broadcastaddr, 0);
5544 
5545 	DPRINTF(sc, ATH_DEBUG_STATE, "%s: RX filter 0x%x bssid %s aid 0\n",
5546 		 __func__, rfilt, ether_sprintf(ifp->if_broadcastaddr));
5547 }
5548 
5549 static void
5550 ath_scan_end(struct ieee80211com *ic)
5551 {
5552 	struct ifnet *ifp = ic->ic_ifp;
5553 	struct ath_softc *sc = ifp->if_softc;
5554 	struct ath_hal *ah = sc->sc_ah;
5555 	u_int32_t rfilt;
5556 
5557 	sc->sc_scanning = 0;
5558 	rfilt = ath_calcrxfilter(sc);
5559 	ath_hal_setrxfilter(ah, rfilt);
5560 	ath_hal_setassocid(ah, sc->sc_curbssid, sc->sc_curaid);
5561 
5562 	ath_hal_process_noisefloor(ah);
5563 
5564 	DPRINTF(sc, ATH_DEBUG_STATE, "%s: RX filter 0x%x bssid %s aid 0x%x\n",
5565 		 __func__, rfilt, ether_sprintf(sc->sc_curbssid),
5566 		 sc->sc_curaid);
5567 }
5568 
5569 static void
5570 ath_set_channel(struct ieee80211com *ic)
5571 {
5572 	struct ifnet *ifp = ic->ic_ifp;
5573 	struct ath_softc *sc = ifp->if_softc;
5574 
5575 	(void) ath_chan_set(sc, ic->ic_curchan);
5576 	/*
5577 	 * If we are returning to our bss channel then mark state
5578 	 * so the next recv'd beacon's tsf will be used to sync the
5579 	 * beacon timers.  Note that since we only hear beacons in
5580 	 * sta/ibss mode this has no effect in other operating modes.
5581 	 */
5582 	if (!sc->sc_scanning && ic->ic_curchan == ic->ic_bsschan)
5583 		sc->sc_syncbeacon = 1;
5584 }
5585 
5586 /*
5587  * Walk the vap list and check if there any vap's in RUN state.
5588  */
5589 static int
5590 ath_isanyrunningvaps(struct ieee80211vap *this)
5591 {
5592 	struct ieee80211com *ic = this->iv_ic;
5593 	struct ieee80211vap *vap;
5594 
5595 	IEEE80211_LOCK_ASSERT(ic);
5596 
5597 	TAILQ_FOREACH(vap, &ic->ic_vaps, iv_next) {
5598 		if (vap != this && vap->iv_state == IEEE80211_S_RUN)
5599 			return 1;
5600 	}
5601 	return 0;
5602 }
5603 
5604 static int
5605 ath_newstate(struct ieee80211vap *vap, enum ieee80211_state nstate, int arg)
5606 {
5607 	struct ieee80211com *ic = vap->iv_ic;
5608 	struct ath_softc *sc = ic->ic_ifp->if_softc;
5609 	struct ath_vap *avp = ATH_VAP(vap);
5610 	struct ath_hal *ah = sc->sc_ah;
5611 	struct ieee80211_node *ni = NULL;
5612 	int i, error, stamode;
5613 	u_int32_t rfilt;
5614 	static const HAL_LED_STATE leds[] = {
5615 	    HAL_LED_INIT,	/* IEEE80211_S_INIT */
5616 	    HAL_LED_SCAN,	/* IEEE80211_S_SCAN */
5617 	    HAL_LED_AUTH,	/* IEEE80211_S_AUTH */
5618 	    HAL_LED_ASSOC, 	/* IEEE80211_S_ASSOC */
5619 	    HAL_LED_RUN, 	/* IEEE80211_S_CAC */
5620 	    HAL_LED_RUN, 	/* IEEE80211_S_RUN */
5621 	    HAL_LED_RUN, 	/* IEEE80211_S_CSA */
5622 	    HAL_LED_RUN, 	/* IEEE80211_S_SLEEP */
5623 	};
5624 
5625 	DPRINTF(sc, ATH_DEBUG_STATE, "%s: %s -> %s\n", __func__,
5626 		ieee80211_state_name[vap->iv_state],
5627 		ieee80211_state_name[nstate]);
5628 
5629 	callout_stop(&sc->sc_cal_ch);
5630 	ath_hal_setledstate(ah, leds[nstate]);	/* set LED */
5631 
5632 	if (nstate == IEEE80211_S_SCAN) {
5633 		/*
5634 		 * Scanning: turn off beacon miss and don't beacon.
5635 		 * Mark beacon state so when we reach RUN state we'll
5636 		 * [re]setup beacons.  Unblock the task q thread so
5637 		 * deferred interrupt processing is done.
5638 		 */
5639 		ath_hal_intrset(ah,
5640 		    sc->sc_imask &~ (HAL_INT_SWBA | HAL_INT_BMISS));
5641 		sc->sc_imask &= ~(HAL_INT_SWBA | HAL_INT_BMISS);
5642 		sc->sc_beacons = 0;
5643 		taskqueue_unblock(sc->sc_tq);
5644 	}
5645 
5646 	ni = vap->iv_bss;
5647 	rfilt = ath_calcrxfilter(sc);
5648 	stamode = (vap->iv_opmode == IEEE80211_M_STA ||
5649 		   vap->iv_opmode == IEEE80211_M_IBSS);
5650 	if (stamode && nstate == IEEE80211_S_RUN) {
5651 		sc->sc_curaid = ni->ni_associd;
5652 		IEEE80211_ADDR_COPY(sc->sc_curbssid, ni->ni_bssid);
5653 		ath_hal_setassocid(ah, sc->sc_curbssid, sc->sc_curaid);
5654 	}
5655 	DPRINTF(sc, ATH_DEBUG_STATE, "%s: RX filter 0x%x bssid %s aid 0x%x\n",
5656 	   __func__, rfilt, ether_sprintf(sc->sc_curbssid), sc->sc_curaid);
5657 	ath_hal_setrxfilter(ah, rfilt);
5658 
5659 	/* XXX is this to restore keycache on resume? */
5660 	if (vap->iv_opmode != IEEE80211_M_STA &&
5661 	    (vap->iv_flags & IEEE80211_F_PRIVACY)) {
5662 		for (i = 0; i < IEEE80211_WEP_NKID; i++)
5663 			if (ath_hal_keyisvalid(ah, i))
5664 				ath_hal_keysetmac(ah, i, ni->ni_bssid);
5665 	}
5666 	/*
5667 	 * Notify the rate control algorithm so rates
5668 	 * are setup should ath_beacon_alloc be called.
5669 	 */
5670 	ath_rate_newstate(vap, nstate);
5671 
5672 	/*
5673 	 * Invoke the parent method to do net80211 work.
5674 	 */
5675 	error = avp->av_newstate(vap, nstate, arg);
5676 	if (error != 0)
5677 		goto bad;
5678 
5679 	if (nstate == IEEE80211_S_RUN) {
5680 		/* NB: collect bss node again, it may have changed */
5681 		ni = vap->iv_bss;
5682 
5683 		DPRINTF(sc, ATH_DEBUG_STATE,
5684 		    "%s(RUN): iv_flags 0x%08x bintvl %d bssid %s "
5685 		    "capinfo 0x%04x chan %d\n", __func__,
5686 		    vap->iv_flags, ni->ni_intval, ether_sprintf(ni->ni_bssid),
5687 		    ni->ni_capinfo, ieee80211_chan2ieee(ic, ic->ic_curchan));
5688 
5689 		switch (vap->iv_opmode) {
5690 		case IEEE80211_M_HOSTAP:
5691 		case IEEE80211_M_IBSS:
5692 			/*
5693 			 * Allocate and setup the beacon frame.
5694 			 *
5695 			 * Stop any previous beacon DMA.  This may be
5696 			 * necessary, for example, when an ibss merge
5697 			 * causes reconfiguration; there will be a state
5698 			 * transition from RUN->RUN that means we may
5699 			 * be called with beacon transmission active.
5700 			 */
5701 			ath_hal_stoptxdma(ah, sc->sc_bhalq);
5702 
5703 			error = ath_beacon_alloc(sc, ni);
5704 			if (error != 0)
5705 				goto bad;
5706 			/*
5707 			 * If joining an adhoc network defer beacon timer
5708 			 * configuration to the next beacon frame so we
5709 			 * have a current TSF to use.  Otherwise we're
5710 			 * starting an ibss/bss so there's no need to delay;
5711 			 * if this is the first vap moving to RUN state, then
5712 			 * beacon state needs to be [re]configured.
5713 			 */
5714 			if (vap->iv_opmode == IEEE80211_M_IBSS &&
5715 			    ni->ni_tstamp.tsf != 0) {
5716 				sc->sc_syncbeacon = 1;
5717 			} else if (!sc->sc_beacons) {
5718 				ath_beacon_config(sc, vap);
5719 				sc->sc_beacons = 1;
5720 			}
5721 			break;
5722 		case IEEE80211_M_STA:
5723 			/*
5724 			 * Fakeup since we're not called by net80211.
5725 			 */
5726 			ath_newassoc(ni, 1);
5727 			/*
5728 			 * Defer beacon timer configuration to the next
5729 			 * beacon frame so we have a current TSF to use
5730 			 * (any TSF collected when scanning is likely old).
5731 			 */
5732 			sc->sc_syncbeacon = 1;
5733 			break;
5734 		case IEEE80211_M_MONITOR:
5735 			/*
5736 			 * Monitor mode vaps have only INIT->RUN and RUN->RUN
5737 			 * transitions so we must re-enable interrupts here to
5738 			 * handle the case of a single monitor mode vap.
5739 			 */
5740 			ath_hal_intrset(ah, sc->sc_imask);
5741 			break;
5742 		case IEEE80211_M_WDS:
5743 			break;
5744 		default:
5745 			break;
5746 		}
5747 		/*
5748 		 * Let the hal process statistics collected during a
5749 		 * scan so it can provide calibrated noise floor data.
5750 		 */
5751 		ath_hal_process_noisefloor(ah);
5752 		/*
5753 		 * Reset rssi stats; maybe not the best place...
5754 		 */
5755 		sc->sc_halstats.ns_avgbrssi = ATH_RSSI_DUMMY_MARKER;
5756 		sc->sc_halstats.ns_avgrssi = ATH_RSSI_DUMMY_MARKER;
5757 		sc->sc_halstats.ns_avgtxrssi = ATH_RSSI_DUMMY_MARKER;
5758 		/*
5759 		 * Finally, start any timers and the task q thread
5760 		 * (in case we didn't go through SCAN state).
5761 		 */
5762 		if (sc->sc_calinterval != 0) {
5763 			/* start periodic recalibration timer */
5764 			callout_reset(&sc->sc_cal_ch, sc->sc_calinterval * hz,
5765 				ath_calibrate, sc);
5766 		}
5767 		taskqueue_unblock(sc->sc_tq);
5768 	} else if (nstate == IEEE80211_S_INIT) {
5769 		/*
5770 		 * If there are no vaps left in RUN state then
5771 		 * shutdown host/driver operation:
5772 		 * o disable interrupts
5773 		 * o disable the task queue thread
5774 		 * o mark beacon processing as stopped
5775 		 */
5776 		if (!ath_isanyrunningvaps(vap)) {
5777 			sc->sc_imask &= ~(HAL_INT_SWBA | HAL_INT_BMISS);
5778 			/* disable interrupts  */
5779 			ath_hal_intrset(ah, sc->sc_imask &~ HAL_INT_GLOBAL);
5780 			taskqueue_block(sc->sc_tq);
5781 			sc->sc_beacons = 0;
5782 		}
5783 	}
5784 bad:
5785 	return error;
5786 }
5787 
5788 /*
5789  * Allocate a key cache slot to the station so we can
5790  * setup a mapping from key index to node. The key cache
5791  * slot is needed for managing antenna state and for
5792  * compression when stations do not use crypto.  We do
5793  * it uniliaterally here; if crypto is employed this slot
5794  * will be reassigned.
5795  */
5796 static void
5797 ath_setup_stationkey(struct ieee80211_node *ni)
5798 {
5799 	struct ieee80211vap *vap = ni->ni_vap;
5800 	struct ath_softc *sc = vap->iv_ic->ic_ifp->if_softc;
5801 	ieee80211_keyix keyix, rxkeyix;
5802 
5803 	if (!ath_key_alloc(vap, &ni->ni_ucastkey, &keyix, &rxkeyix)) {
5804 		/*
5805 		 * Key cache is full; we'll fall back to doing
5806 		 * the more expensive lookup in software.  Note
5807 		 * this also means no h/w compression.
5808 		 */
5809 		/* XXX msg+statistic */
5810 	} else {
5811 		/* XXX locking? */
5812 		ni->ni_ucastkey.wk_keyix = keyix;
5813 		ni->ni_ucastkey.wk_rxkeyix = rxkeyix;
5814 		IEEE80211_ADDR_COPY(ni->ni_ucastkey.wk_macaddr, ni->ni_macaddr);
5815 		/* NB: this will create a pass-thru key entry */
5816 		ath_keyset(sc, &ni->ni_ucastkey, vap->iv_bss);
5817 	}
5818 }
5819 
5820 /*
5821  * Setup driver-specific state for a newly associated node.
5822  * Note that we're called also on a re-associate, the isnew
5823  * param tells us if this is the first time or not.
5824  */
5825 static void
5826 ath_newassoc(struct ieee80211_node *ni, int isnew)
5827 {
5828 	struct ath_node *an = ATH_NODE(ni);
5829 	struct ieee80211vap *vap = ni->ni_vap;
5830 	struct ath_softc *sc = vap->iv_ic->ic_ifp->if_softc;
5831 	const struct ieee80211_txparam *tp;
5832 	enum ieee80211_phymode mode;
5833 
5834 	/*
5835 	 * Deduce netband of station to simplify setting up xmit
5836 	 * parameters.  Note this allows us to assign different
5837 	 * parameters to each station in a mixed bss (b/g, n/[abg]).
5838 	 */
5839 	if (ni->ni_flags & IEEE80211_NODE_HT) {
5840 		if (IEEE80211_IS_CHAN_5GHZ(ni->ni_chan))
5841 			mode = IEEE80211_MODE_11NA;
5842 		else
5843 			mode = IEEE80211_MODE_11NG;
5844 	} else if (IEEE80211_IS_CHAN_A(ni->ni_chan))
5845 		mode = IEEE80211_MODE_11A;
5846 	else if (ni->ni_flags & IEEE80211_NODE_ERP)
5847 		mode = IEEE80211_MODE_11G;
5848 	else
5849 		mode = IEEE80211_MODE_11B;
5850 	tp = &vap->iv_txparms[mode];
5851 	an->an_tp = tp;
5852 	an->an_mcastrix = ath_tx_findrix(sc->sc_rates[mode], tp->mcastrate);
5853 	an->an_mgmtrix = ath_tx_findrix(sc->sc_rates[mode], tp->mgmtrate);
5854 
5855 	ath_rate_newassoc(sc, an, isnew);
5856 	if (isnew &&
5857 	    (vap->iv_flags & IEEE80211_F_PRIVACY) == 0 && sc->sc_hasclrkey &&
5858 	    ni->ni_ucastkey.wk_keyix == IEEE80211_KEYIX_NONE)
5859 		ath_setup_stationkey(ni);
5860 }
5861 
5862 static int
5863 getchannels(struct ath_softc *sc, int *nchans, struct ieee80211_channel chans[],
5864 	int cc, int ecm, int outdoor)
5865 {
5866 	struct ath_hal *ah = sc->sc_ah;
5867 	HAL_CHANNEL *halchans;
5868 	int i, nhalchans, error;
5869 
5870 	halchans = malloc(IEEE80211_CHAN_MAX * sizeof(HAL_CHANNEL),
5871 			M_TEMP, M_NOWAIT | M_ZERO);
5872 	if (halchans == NULL) {
5873 		device_printf(sc->sc_dev,
5874 		    "%s: unable to allocate channel table\n", __func__);
5875 		return ENOMEM;
5876 	}
5877 	error = 0;
5878 	if (!ath_hal_init_channels(ah, halchans, IEEE80211_CHAN_MAX, &nhalchans,
5879 	    NULL, 0, NULL, CTRY_DEFAULT, HAL_MODE_ALL, AH_FALSE, AH_TRUE)) {
5880 		error = EINVAL;
5881 		goto done;
5882 	}
5883 	if (nchans == NULL)		/* no table requested */
5884 		goto done;
5885 
5886 	/*
5887 	 * Convert HAL channels to ieee80211 ones.
5888 	 */
5889 	for (i = 0; i < nhalchans; i++) {
5890 		HAL_CHANNEL *c = &halchans[i];
5891 		struct ieee80211_channel *ichan = &chans[i];
5892 
5893 		ichan->ic_ieee = ath_hal_mhz2ieee(ah, c->channel,
5894 					c->channelFlags);
5895 		if (bootverbose)
5896 			device_printf(sc->sc_dev, "hal channel %u/%x -> %u "
5897 			    "maxpow %d minpow %d maxreg %d\n",
5898 			    c->channel, c->channelFlags, ichan->ic_ieee,
5899 			    c->maxTxPower, c->minTxPower, c->maxRegTxPower);
5900 		ichan->ic_freq = c->channel;
5901 
5902 		if ((c->channelFlags & CHANNEL_PUREG) == CHANNEL_PUREG) {
5903 			/*
5904 			 * Except for AR5211, HAL's PUREG means mixed
5905 			 * DSSS and OFDM.
5906 			 */
5907 			ichan->ic_flags = c->channelFlags &~ CHANNEL_PUREG;
5908 			ichan->ic_flags |= IEEE80211_CHAN_G;
5909 		} else {
5910 			ichan->ic_flags = c->channelFlags;
5911 		}
5912 
5913 		if (ath_hal_isgsmsku(ah)) {
5914 			/* remap to true frequencies */
5915 			ichan->ic_freq = 922 + (2422 - ichan->ic_freq);
5916 			ichan->ic_flags |= IEEE80211_CHAN_GSM;
5917 			ichan->ic_ieee = ieee80211_mhz2ieee(ichan->ic_freq,
5918 						    ichan->ic_flags);
5919 		}
5920 		ichan->ic_maxregpower = c->maxRegTxPower;	/* dBm */
5921 		/* XXX: old hal's don't provide maxTxPower for some parts */
5922 		ichan->ic_maxpower = (c->maxTxPower != 0) ?
5923 		    c->maxTxPower : 2*c->maxRegTxPower;		/* 1/2 dBm */
5924 		ichan->ic_minpower = c->minTxPower;		/* 1/2 dBm */
5925 	}
5926 	*nchans = nhalchans;
5927 done:
5928 	free(halchans, M_TEMP);
5929 	return error;
5930 }
5931 
5932 static int
5933 ath_setregdomain(struct ieee80211com *ic, struct ieee80211_regdomain *rd,
5934 	int nchans, struct ieee80211_channel chans[])
5935 {
5936 	struct ath_softc *sc = ic->ic_ifp->if_softc;
5937 	struct ath_hal *ah = sc->sc_ah;
5938 	u_int32_t ord;
5939 	int error;
5940 
5941 	(void) ath_hal_getregdomain(ah, &ord);
5942 	/* XXX map sku->rd */
5943 	ath_hal_setregdomain(ah, rd->regdomain);
5944 	error = getchannels(sc, &nchans, chans, rd->country,
5945 	     rd->ecm ? AH_TRUE : AH_FALSE,
5946 	     rd->location == 'O' ? AH_TRUE : AH_FALSE);
5947 	if (error != 0) {
5948 		/*
5949 		 * Restore previous state.
5950 		 */
5951 		ath_hal_setregdomain(ah, ord);
5952 		(void) getchannels(sc, NULL, NULL, ic->ic_regdomain.country,
5953 		     ic->ic_regdomain.ecm ? AH_TRUE : AH_FALSE,
5954 		     ic->ic_regdomain.location == 'O' ? AH_TRUE : AH_FALSE);
5955 		return error;
5956 	}
5957 	return 0;
5958 }
5959 
5960 static void
5961 ath_getradiocaps(struct ieee80211com *ic,
5962 	int *nchans, struct ieee80211_channel chans[])
5963 {
5964 	struct ath_softc *sc = ic->ic_ifp->if_softc;
5965 	struct ath_hal *ah = sc->sc_ah;
5966 	u_int32_t ord;
5967 
5968 	(void) ath_hal_getregdomain(ah, &ord);
5969 	ath_hal_setregdomain(ah, 0);
5970 	/* XXX not quite right but close enough for now */
5971 	getchannels(sc, nchans, chans, CTRY_DEBUG, AH_TRUE, AH_FALSE);
5972 
5973 	/* NB: restore previous state */
5974 	ath_hal_setregdomain(ah, ord);
5975 	(void) getchannels(sc, NULL, NULL, ic->ic_regdomain.country,
5976 	     ic->ic_regdomain.ecm ? AH_TRUE : AH_FALSE,
5977 	     ic->ic_regdomain.location == 'O' ? AH_TRUE : AH_FALSE);
5978 }
5979 
5980 static int
5981 ath_mapregdomain(struct ath_softc *sc, u_int32_t rd)
5982 {
5983 	/* map Atheros rd's to SKU's */
5984 	return rd;
5985 }
5986 
5987 static int
5988 ath_getchannels(struct ath_softc *sc)
5989 {
5990 	struct ifnet *ifp = sc->sc_ifp;
5991 	struct ieee80211com *ic = ifp->if_l2com;
5992 	struct ath_hal *ah = sc->sc_ah;
5993 	int error;
5994 
5995 	/*
5996 	 * Convert HAL channels to ieee80211 ones.
5997 	 */
5998 	error = getchannels(sc, &ic->ic_nchans, ic->ic_channels,
5999 	    CTRY_DEFAULT, AH_TRUE, AH_FALSE);
6000 	(void) ath_hal_getregdomain(ah, &sc->sc_eerd);
6001 	ath_hal_getcountrycode(ah, &sc->sc_eecc);	/* NB: cannot fail */
6002 	if (error) {
6003 		if_printf(ifp, "%s: unable to collect channel list from hal, "
6004 		    "error %d\n", __func__, error);
6005 		if (error == EINVAL) {
6006 			if_printf(ifp, "%s: regdomain likely %u country code %u\n",
6007 			    __func__, sc->sc_eerd, sc->sc_eecc);
6008 		}
6009 		return error;
6010 	}
6011 	ic->ic_regdomain.regdomain = ath_mapregdomain(sc, sc->sc_eerd);
6012 	ic->ic_regdomain.country = sc->sc_eecc;
6013 	ic->ic_regdomain.ecm = 1;
6014 	ic->ic_regdomain.location = 'I';
6015 	ic->ic_regdomain.isocc[0] = ' ';	/* XXX don't know */
6016 	ic->ic_regdomain.isocc[1] = ' ';
6017 	return 0;
6018 }
6019 
6020 static void
6021 ath_led_done(void *arg)
6022 {
6023 	struct ath_softc *sc = arg;
6024 
6025 	sc->sc_blinking = 0;
6026 }
6027 
6028 /*
6029  * Turn the LED off: flip the pin and then set a timer so no
6030  * update will happen for the specified duration.
6031  */
6032 static void
6033 ath_led_off(void *arg)
6034 {
6035 	struct ath_softc *sc = arg;
6036 
6037 	ath_hal_gpioset(sc->sc_ah, sc->sc_ledpin, !sc->sc_ledon);
6038 	callout_reset(&sc->sc_ledtimer, sc->sc_ledoff, ath_led_done, sc);
6039 }
6040 
6041 /*
6042  * Blink the LED according to the specified on/off times.
6043  */
6044 static void
6045 ath_led_blink(struct ath_softc *sc, int on, int off)
6046 {
6047 	DPRINTF(sc, ATH_DEBUG_LED, "%s: on %u off %u\n", __func__, on, off);
6048 	ath_hal_gpioset(sc->sc_ah, sc->sc_ledpin, sc->sc_ledon);
6049 	sc->sc_blinking = 1;
6050 	sc->sc_ledoff = off;
6051 	callout_reset(&sc->sc_ledtimer, on, ath_led_off, sc);
6052 }
6053 
6054 static void
6055 ath_led_event(struct ath_softc *sc, int event)
6056 {
6057 
6058 	sc->sc_ledevent = ticks;	/* time of last event */
6059 	if (sc->sc_blinking)		/* don't interrupt active blink */
6060 		return;
6061 	switch (event) {
6062 	case ATH_LED_POLL:
6063 		ath_led_blink(sc, sc->sc_hwmap[0].ledon,
6064 			sc->sc_hwmap[0].ledoff);
6065 		break;
6066 	case ATH_LED_TX:
6067 		ath_led_blink(sc, sc->sc_hwmap[sc->sc_txrate].ledon,
6068 			sc->sc_hwmap[sc->sc_txrate].ledoff);
6069 		break;
6070 	case ATH_LED_RX:
6071 		ath_led_blink(sc, sc->sc_hwmap[sc->sc_rxrate].ledon,
6072 			sc->sc_hwmap[sc->sc_rxrate].ledoff);
6073 		break;
6074 	}
6075 }
6076 
6077 static int
6078 ath_rate_setup(struct ath_softc *sc, u_int mode)
6079 {
6080 	struct ath_hal *ah = sc->sc_ah;
6081 	const HAL_RATE_TABLE *rt;
6082 
6083 	switch (mode) {
6084 	case IEEE80211_MODE_11A:
6085 		rt = ath_hal_getratetable(ah, HAL_MODE_11A);
6086 		break;
6087 	case IEEE80211_MODE_HALF:
6088 		rt = ath_hal_getratetable(ah, HAL_MODE_11A_HALF_RATE);
6089 		break;
6090 	case IEEE80211_MODE_QUARTER:
6091 		rt = ath_hal_getratetable(ah, HAL_MODE_11A_QUARTER_RATE);
6092 		break;
6093 	case IEEE80211_MODE_11B:
6094 		rt = ath_hal_getratetable(ah, HAL_MODE_11B);
6095 		break;
6096 	case IEEE80211_MODE_11G:
6097 		rt = ath_hal_getratetable(ah, HAL_MODE_11G);
6098 		break;
6099 	case IEEE80211_MODE_TURBO_A:
6100 		rt = ath_hal_getratetable(ah, HAL_MODE_108A);
6101 #if HAL_ABI_VERSION < 0x07013100
6102 		if (rt == NULL)		/* XXX bandaid for old hal's */
6103 			rt = ath_hal_getratetable(ah, HAL_MODE_TURBO);
6104 #endif
6105 		break;
6106 	case IEEE80211_MODE_TURBO_G:
6107 		rt = ath_hal_getratetable(ah, HAL_MODE_108G);
6108 		break;
6109 	case IEEE80211_MODE_STURBO_A:
6110 		rt = ath_hal_getratetable(ah, HAL_MODE_TURBO);
6111 		break;
6112 	case IEEE80211_MODE_11NA:
6113 		rt = ath_hal_getratetable(ah, HAL_MODE_11NA_HT20);
6114 		break;
6115 	case IEEE80211_MODE_11NG:
6116 		rt = ath_hal_getratetable(ah, HAL_MODE_11NG_HT20);
6117 		break;
6118 	default:
6119 		DPRINTF(sc, ATH_DEBUG_ANY, "%s: invalid mode %u\n",
6120 			__func__, mode);
6121 		return 0;
6122 	}
6123 	sc->sc_rates[mode] = rt;
6124 	return (rt != NULL);
6125 }
6126 
6127 static void
6128 ath_setcurmode(struct ath_softc *sc, enum ieee80211_phymode mode)
6129 {
6130 #define	N(a)	(sizeof(a)/sizeof(a[0]))
6131 	/* NB: on/off times from the Atheros NDIS driver, w/ permission */
6132 	static const struct {
6133 		u_int		rate;		/* tx/rx 802.11 rate */
6134 		u_int16_t	timeOn;		/* LED on time (ms) */
6135 		u_int16_t	timeOff;	/* LED off time (ms) */
6136 	} blinkrates[] = {
6137 		{ 108,  40,  10 },
6138 		{  96,  44,  11 },
6139 		{  72,  50,  13 },
6140 		{  48,  57,  14 },
6141 		{  36,  67,  16 },
6142 		{  24,  80,  20 },
6143 		{  22, 100,  25 },
6144 		{  18, 133,  34 },
6145 		{  12, 160,  40 },
6146 		{  10, 200,  50 },
6147 		{   6, 240,  58 },
6148 		{   4, 267,  66 },
6149 		{   2, 400, 100 },
6150 		{   0, 500, 130 },
6151 		/* XXX half/quarter rates */
6152 	};
6153 	const HAL_RATE_TABLE *rt;
6154 	int i, j;
6155 
6156 	memset(sc->sc_rixmap, 0xff, sizeof(sc->sc_rixmap));
6157 	rt = sc->sc_rates[mode];
6158 	KASSERT(rt != NULL, ("no h/w rate set for phy mode %u", mode));
6159 	for (i = 0; i < rt->rateCount; i++)
6160 		sc->sc_rixmap[rt->info[i].dot11Rate & IEEE80211_RATE_VAL] = i;
6161 	memset(sc->sc_hwmap, 0, sizeof(sc->sc_hwmap));
6162 	for (i = 0; i < 32; i++) {
6163 		u_int8_t ix = rt->rateCodeToIndex[i];
6164 		if (ix == 0xff) {
6165 			sc->sc_hwmap[i].ledon = (500 * hz) / 1000;
6166 			sc->sc_hwmap[i].ledoff = (130 * hz) / 1000;
6167 			continue;
6168 		}
6169 		sc->sc_hwmap[i].ieeerate =
6170 			rt->info[ix].dot11Rate & IEEE80211_RATE_VAL;
6171 		if (rt->info[ix].phy == IEEE80211_T_HT)
6172 			sc->sc_hwmap[i].ieeerate |= 0x80;	/* MCS */
6173 		sc->sc_hwmap[i].txflags = IEEE80211_RADIOTAP_F_DATAPAD;
6174 		if (rt->info[ix].shortPreamble ||
6175 		    rt->info[ix].phy == IEEE80211_T_OFDM)
6176 			sc->sc_hwmap[i].txflags |= IEEE80211_RADIOTAP_F_SHORTPRE;
6177 		/* NB: receive frames include FCS */
6178 		sc->sc_hwmap[i].rxflags = sc->sc_hwmap[i].txflags |
6179 			IEEE80211_RADIOTAP_F_FCS;
6180 		/* setup blink rate table to avoid per-packet lookup */
6181 		for (j = 0; j < N(blinkrates)-1; j++)
6182 			if (blinkrates[j].rate == sc->sc_hwmap[i].ieeerate)
6183 				break;
6184 		/* NB: this uses the last entry if the rate isn't found */
6185 		/* XXX beware of overlow */
6186 		sc->sc_hwmap[i].ledon = (blinkrates[j].timeOn * hz) / 1000;
6187 		sc->sc_hwmap[i].ledoff = (blinkrates[j].timeOff * hz) / 1000;
6188 	}
6189 	sc->sc_currates = rt;
6190 	sc->sc_curmode = mode;
6191 	/*
6192 	 * All protection frames are transmited at 2Mb/s for
6193 	 * 11g, otherwise at 1Mb/s.
6194 	 */
6195 	if (mode == IEEE80211_MODE_11G)
6196 		sc->sc_protrix = ath_tx_findrix(rt, 2*2);
6197 	else
6198 		sc->sc_protrix = ath_tx_findrix(rt, 2*1);
6199 	/* NB: caller is responsible for reseting rate control state */
6200 #undef N
6201 }
6202 
6203 #ifdef ATH_DEBUG
6204 static void
6205 ath_printrxbuf(const struct ath_buf *bf, u_int ix, int done)
6206 {
6207 	const struct ath_rx_status *rs = &bf->bf_status.ds_rxstat;
6208 	const struct ath_desc *ds;
6209 	int i;
6210 
6211 	for (i = 0, ds = bf->bf_desc; i < bf->bf_nseg; i++, ds++) {
6212 		printf("R[%2u] (DS.V:%p DS.P:%p) L:%08x D:%08x%s\n"
6213 		       "      %08x %08x %08x %08x\n",
6214 		    ix, ds, (const struct ath_desc *)bf->bf_daddr + i,
6215 		    ds->ds_link, ds->ds_data,
6216 		    !done ? "" : (rs->rs_status == 0) ? " *" : " !",
6217 		    ds->ds_ctl0, ds->ds_ctl1,
6218 		    ds->ds_hw[0], ds->ds_hw[1]);
6219 	}
6220 }
6221 
6222 static void
6223 ath_printtxbuf(const struct ath_buf *bf, u_int qnum, u_int ix, int done)
6224 {
6225 	const struct ath_tx_status *ts = &bf->bf_status.ds_txstat;
6226 	const struct ath_desc *ds;
6227 	int i;
6228 
6229 	printf("Q%u[%3u]", qnum, ix);
6230 	for (i = 0, ds = bf->bf_desc; i < bf->bf_nseg; i++, ds++) {
6231 		printf(" (DS.V:%p DS.P:%p) L:%08x D:%08x F:04%x%s\n"
6232 		       "        %08x %08x %08x %08x %08x %08x\n",
6233 		    ds, (const struct ath_desc *)bf->bf_daddr + i,
6234 		    ds->ds_link, ds->ds_data, bf->bf_flags,
6235 		    !done ? "" : (ts->ts_status == 0) ? " *" : " !",
6236 		    ds->ds_ctl0, ds->ds_ctl1,
6237 		    ds->ds_hw[0], ds->ds_hw[1], ds->ds_hw[2], ds->ds_hw[3]);
6238 	}
6239 }
6240 #endif /* ATH_DEBUG */
6241 
6242 static void
6243 ath_watchdog(struct ifnet *ifp)
6244 {
6245 	struct ath_softc *sc = ifp->if_softc;
6246 
6247 	if ((ifp->if_drv_flags & IFF_DRV_RUNNING) && !sc->sc_invalid) {
6248 		if_printf(ifp, "device timeout\n");
6249 		ath_reset(ifp);
6250 		ifp->if_oerrors++;
6251 		sc->sc_stats.ast_watchdog++;
6252 	}
6253 }
6254 
6255 #ifdef ATH_DIAGAPI
6256 /*
6257  * Diagnostic interface to the HAL.  This is used by various
6258  * tools to do things like retrieve register contents for
6259  * debugging.  The mechanism is intentionally opaque so that
6260  * it can change frequently w/o concern for compatiblity.
6261  */
6262 static int
6263 ath_ioctl_diag(struct ath_softc *sc, struct ath_diag *ad)
6264 {
6265 	struct ath_hal *ah = sc->sc_ah;
6266 	u_int id = ad->ad_id & ATH_DIAG_ID;
6267 	void *indata = NULL;
6268 	void *outdata = NULL;
6269 	u_int32_t insize = ad->ad_in_size;
6270 	u_int32_t outsize = ad->ad_out_size;
6271 	int error = 0;
6272 
6273 	if (ad->ad_id & ATH_DIAG_IN) {
6274 		/*
6275 		 * Copy in data.
6276 		 */
6277 		indata = malloc(insize, M_TEMP, M_NOWAIT);
6278 		if (indata == NULL) {
6279 			error = ENOMEM;
6280 			goto bad;
6281 		}
6282 		error = copyin(ad->ad_in_data, indata, insize);
6283 		if (error)
6284 			goto bad;
6285 	}
6286 	if (ad->ad_id & ATH_DIAG_DYN) {
6287 		/*
6288 		 * Allocate a buffer for the results (otherwise the HAL
6289 		 * returns a pointer to a buffer where we can read the
6290 		 * results).  Note that we depend on the HAL leaving this
6291 		 * pointer for us to use below in reclaiming the buffer;
6292 		 * may want to be more defensive.
6293 		 */
6294 		outdata = malloc(outsize, M_TEMP, M_NOWAIT);
6295 		if (outdata == NULL) {
6296 			error = ENOMEM;
6297 			goto bad;
6298 		}
6299 	}
6300 	if (ath_hal_getdiagstate(ah, id, indata, insize, &outdata, &outsize)) {
6301 		if (outsize < ad->ad_out_size)
6302 			ad->ad_out_size = outsize;
6303 		if (outdata != NULL)
6304 			error = copyout(outdata, ad->ad_out_data,
6305 					ad->ad_out_size);
6306 	} else {
6307 		error = EINVAL;
6308 	}
6309 bad:
6310 	if ((ad->ad_id & ATH_DIAG_IN) && indata != NULL)
6311 		free(indata, M_TEMP);
6312 	if ((ad->ad_id & ATH_DIAG_DYN) && outdata != NULL)
6313 		free(outdata, M_TEMP);
6314 	return error;
6315 }
6316 #endif /* ATH_DIAGAPI */
6317 
6318 static int
6319 ath_ioctl(struct ifnet *ifp, u_long cmd, caddr_t data)
6320 {
6321 #define	IS_RUNNING(ifp) \
6322 	((ifp->if_flags & IFF_UP) && (ifp->if_drv_flags & IFF_DRV_RUNNING))
6323 	struct ath_softc *sc = ifp->if_softc;
6324 	struct ieee80211com *ic = ifp->if_l2com;
6325 	struct ifreq *ifr = (struct ifreq *)data;
6326 	int error = 0;
6327 
6328 	switch (cmd) {
6329 	case SIOCSIFFLAGS:
6330 		ATH_LOCK(sc);
6331 		if (IS_RUNNING(ifp)) {
6332 			/*
6333 			 * To avoid rescanning another access point,
6334 			 * do not call ath_init() here.  Instead,
6335 			 * only reflect promisc mode settings.
6336 			 */
6337 			ath_mode_init(sc);
6338 		} else if (ifp->if_flags & IFF_UP) {
6339 			/*
6340 			 * Beware of being called during attach/detach
6341 			 * to reset promiscuous mode.  In that case we
6342 			 * will still be marked UP but not RUNNING.
6343 			 * However trying to re-init the interface
6344 			 * is the wrong thing to do as we've already
6345 			 * torn down much of our state.  There's
6346 			 * probably a better way to deal with this.
6347 			 */
6348 			if (!sc->sc_invalid)
6349 				ath_init(sc);	/* XXX lose error */
6350 		} else {
6351 			ath_stop_locked(ifp);
6352 #ifdef notyet
6353 			/* XXX must wakeup in places like ath_vap_delete */
6354 			if (!sc->sc_invalid)
6355 				ath_hal_setpower(sc->sc_ah, HAL_PM_FULL_SLEEP);
6356 #endif
6357 		}
6358 		ATH_UNLOCK(sc);
6359 		break;
6360 	case SIOCGIFMEDIA:
6361 	case SIOCSIFMEDIA:
6362 		error = ifmedia_ioctl(ifp, ifr, &ic->ic_media, cmd);
6363 		break;
6364 	case SIOCGATHSTATS:
6365 		/* NB: embed these numbers to get a consistent view */
6366 		sc->sc_stats.ast_tx_packets = ifp->if_opackets;
6367 		sc->sc_stats.ast_rx_packets = ifp->if_ipackets;
6368 #if 0
6369 		ieee80211_getsignal(ic, &sc->sc_stats.ast_rx_rssi,
6370 			&sc->sc_stats.ast_rx_noise);
6371 #endif
6372 		sc->sc_stats.ast_tx_rate = sc->sc_hwmap[sc->sc_txrate].ieeerate;
6373 		return copyout(&sc->sc_stats,
6374 		    ifr->ifr_data, sizeof (sc->sc_stats));
6375 #ifdef ATH_DIAGAPI
6376 	case SIOCGATHDIAG:
6377 		error = ath_ioctl_diag(sc, (struct ath_diag *) ifr);
6378 		break;
6379 #endif
6380 	case SIOCGIFADDR:
6381 		error = ether_ioctl(ifp, cmd, data);
6382 		break;
6383 	default:
6384 		error = EINVAL;
6385 		break;
6386 	}
6387 	return error;
6388 #undef IS_RUNNING
6389 }
6390 
6391 static int
6392 ath_sysctl_slottime(SYSCTL_HANDLER_ARGS)
6393 {
6394 	struct ath_softc *sc = arg1;
6395 	u_int slottime = ath_hal_getslottime(sc->sc_ah);
6396 	int error;
6397 
6398 	error = sysctl_handle_int(oidp, &slottime, 0, req);
6399 	if (error || !req->newptr)
6400 		return error;
6401 	return !ath_hal_setslottime(sc->sc_ah, slottime) ? EINVAL : 0;
6402 }
6403 
6404 static int
6405 ath_sysctl_acktimeout(SYSCTL_HANDLER_ARGS)
6406 {
6407 	struct ath_softc *sc = arg1;
6408 	u_int acktimeout = ath_hal_getacktimeout(sc->sc_ah);
6409 	int error;
6410 
6411 	error = sysctl_handle_int(oidp, &acktimeout, 0, req);
6412 	if (error || !req->newptr)
6413 		return error;
6414 	return !ath_hal_setacktimeout(sc->sc_ah, acktimeout) ? EINVAL : 0;
6415 }
6416 
6417 static int
6418 ath_sysctl_ctstimeout(SYSCTL_HANDLER_ARGS)
6419 {
6420 	struct ath_softc *sc = arg1;
6421 	u_int ctstimeout = ath_hal_getctstimeout(sc->sc_ah);
6422 	int error;
6423 
6424 	error = sysctl_handle_int(oidp, &ctstimeout, 0, req);
6425 	if (error || !req->newptr)
6426 		return error;
6427 	return !ath_hal_setctstimeout(sc->sc_ah, ctstimeout) ? EINVAL : 0;
6428 }
6429 
6430 static int
6431 ath_sysctl_softled(SYSCTL_HANDLER_ARGS)
6432 {
6433 	struct ath_softc *sc = arg1;
6434 	int softled = sc->sc_softled;
6435 	int error;
6436 
6437 	error = sysctl_handle_int(oidp, &softled, 0, req);
6438 	if (error || !req->newptr)
6439 		return error;
6440 	softled = (softled != 0);
6441 	if (softled != sc->sc_softled) {
6442 		if (softled) {
6443 			/* NB: handle any sc_ledpin change */
6444 			ath_hal_gpioCfgOutput(sc->sc_ah, sc->sc_ledpin);
6445 			ath_hal_gpioset(sc->sc_ah, sc->sc_ledpin,
6446 				!sc->sc_ledon);
6447 		}
6448 		sc->sc_softled = softled;
6449 	}
6450 	return 0;
6451 }
6452 
6453 static int
6454 ath_sysctl_ledpin(SYSCTL_HANDLER_ARGS)
6455 {
6456 	struct ath_softc *sc = arg1;
6457 	int ledpin = sc->sc_ledpin;
6458 	int error;
6459 
6460 	error = sysctl_handle_int(oidp, &ledpin, 0, req);
6461 	if (error || !req->newptr)
6462 		return error;
6463 	if (ledpin != sc->sc_ledpin) {
6464 		sc->sc_ledpin = ledpin;
6465 		if (sc->sc_softled) {
6466 			ath_hal_gpioCfgOutput(sc->sc_ah, sc->sc_ledpin);
6467 			ath_hal_gpioset(sc->sc_ah, sc->sc_ledpin,
6468 				!sc->sc_ledon);
6469 		}
6470 	}
6471 	return 0;
6472 }
6473 
6474 static int
6475 ath_sysctl_txantenna(SYSCTL_HANDLER_ARGS)
6476 {
6477 	struct ath_softc *sc = arg1;
6478 	u_int txantenna = ath_hal_getantennaswitch(sc->sc_ah);
6479 	int error;
6480 
6481 	error = sysctl_handle_int(oidp, &txantenna, 0, req);
6482 	if (!error && req->newptr) {
6483 		/* XXX assumes 2 antenna ports */
6484 		if (txantenna < HAL_ANT_VARIABLE || txantenna > HAL_ANT_FIXED_B)
6485 			return EINVAL;
6486 		ath_hal_setantennaswitch(sc->sc_ah, txantenna);
6487 		/*
6488 		 * NB: with the switch locked this isn't meaningful,
6489 		 *     but set it anyway so things like radiotap get
6490 		 *     consistent info in their data.
6491 		 */
6492 		sc->sc_txantenna = txantenna;
6493 	}
6494 	return error;
6495 }
6496 
6497 static int
6498 ath_sysctl_rxantenna(SYSCTL_HANDLER_ARGS)
6499 {
6500 	struct ath_softc *sc = arg1;
6501 	u_int defantenna = ath_hal_getdefantenna(sc->sc_ah);
6502 	int error;
6503 
6504 	error = sysctl_handle_int(oidp, &defantenna, 0, req);
6505 	if (!error && req->newptr)
6506 		ath_hal_setdefantenna(sc->sc_ah, defantenna);
6507 	return error;
6508 }
6509 
6510 static int
6511 ath_sysctl_diversity(SYSCTL_HANDLER_ARGS)
6512 {
6513 	struct ath_softc *sc = arg1;
6514 	u_int diversity = ath_hal_getdiversity(sc->sc_ah);
6515 	int error;
6516 
6517 	error = sysctl_handle_int(oidp, &diversity, 0, req);
6518 	if (error || !req->newptr)
6519 		return error;
6520 	if (!ath_hal_setdiversity(sc->sc_ah, diversity))
6521 		return EINVAL;
6522 	sc->sc_diversity = diversity;
6523 	return 0;
6524 }
6525 
6526 static int
6527 ath_sysctl_diag(SYSCTL_HANDLER_ARGS)
6528 {
6529 	struct ath_softc *sc = arg1;
6530 	u_int32_t diag;
6531 	int error;
6532 
6533 	if (!ath_hal_getdiag(sc->sc_ah, &diag))
6534 		return EINVAL;
6535 	error = sysctl_handle_int(oidp, &diag, 0, req);
6536 	if (error || !req->newptr)
6537 		return error;
6538 	return !ath_hal_setdiag(sc->sc_ah, diag) ? EINVAL : 0;
6539 }
6540 
6541 static int
6542 ath_sysctl_tpscale(SYSCTL_HANDLER_ARGS)
6543 {
6544 	struct ath_softc *sc = arg1;
6545 	struct ifnet *ifp = sc->sc_ifp;
6546 	u_int32_t scale;
6547 	int error;
6548 
6549 	(void) ath_hal_gettpscale(sc->sc_ah, &scale);
6550 	error = sysctl_handle_int(oidp, &scale, 0, req);
6551 	if (error || !req->newptr)
6552 		return error;
6553 	return !ath_hal_settpscale(sc->sc_ah, scale) ? EINVAL :
6554 	    (ifp->if_drv_flags & IFF_DRV_RUNNING) ? ath_reset(ifp) : 0;
6555 }
6556 
6557 static int
6558 ath_sysctl_tpc(SYSCTL_HANDLER_ARGS)
6559 {
6560 	struct ath_softc *sc = arg1;
6561 	u_int tpc = ath_hal_gettpc(sc->sc_ah);
6562 	int error;
6563 
6564 	error = sysctl_handle_int(oidp, &tpc, 0, req);
6565 	if (error || !req->newptr)
6566 		return error;
6567 	return !ath_hal_settpc(sc->sc_ah, tpc) ? EINVAL : 0;
6568 }
6569 
6570 static int
6571 ath_sysctl_rfkill(SYSCTL_HANDLER_ARGS)
6572 {
6573 	struct ath_softc *sc = arg1;
6574 	struct ifnet *ifp = sc->sc_ifp;
6575 	struct ath_hal *ah = sc->sc_ah;
6576 	u_int rfkill = ath_hal_getrfkill(ah);
6577 	int error;
6578 
6579 	error = sysctl_handle_int(oidp, &rfkill, 0, req);
6580 	if (error || !req->newptr)
6581 		return error;
6582 	if (rfkill == ath_hal_getrfkill(ah))	/* unchanged */
6583 		return 0;
6584 	if (!ath_hal_setrfkill(ah, rfkill))
6585 		return EINVAL;
6586 	return (ifp->if_drv_flags & IFF_DRV_RUNNING) ? ath_reset(ifp) : 0;
6587 }
6588 
6589 static int
6590 ath_sysctl_rfsilent(SYSCTL_HANDLER_ARGS)
6591 {
6592 	struct ath_softc *sc = arg1;
6593 	u_int rfsilent;
6594 	int error;
6595 
6596 	(void) ath_hal_getrfsilent(sc->sc_ah, &rfsilent);
6597 	error = sysctl_handle_int(oidp, &rfsilent, 0, req);
6598 	if (error || !req->newptr)
6599 		return error;
6600 	if (!ath_hal_setrfsilent(sc->sc_ah, rfsilent))
6601 		return EINVAL;
6602 	sc->sc_rfsilentpin = rfsilent & 0x1c;
6603 	sc->sc_rfsilentpol = (rfsilent & 0x2) != 0;
6604 	return 0;
6605 }
6606 
6607 static int
6608 ath_sysctl_tpack(SYSCTL_HANDLER_ARGS)
6609 {
6610 	struct ath_softc *sc = arg1;
6611 	u_int32_t tpack;
6612 	int error;
6613 
6614 	(void) ath_hal_gettpack(sc->sc_ah, &tpack);
6615 	error = sysctl_handle_int(oidp, &tpack, 0, req);
6616 	if (error || !req->newptr)
6617 		return error;
6618 	return !ath_hal_settpack(sc->sc_ah, tpack) ? EINVAL : 0;
6619 }
6620 
6621 static int
6622 ath_sysctl_tpcts(SYSCTL_HANDLER_ARGS)
6623 {
6624 	struct ath_softc *sc = arg1;
6625 	u_int32_t tpcts;
6626 	int error;
6627 
6628 	(void) ath_hal_gettpcts(sc->sc_ah, &tpcts);
6629 	error = sysctl_handle_int(oidp, &tpcts, 0, req);
6630 	if (error || !req->newptr)
6631 		return error;
6632 	return !ath_hal_settpcts(sc->sc_ah, tpcts) ? EINVAL : 0;
6633 }
6634 
6635 static void
6636 ath_sysctlattach(struct ath_softc *sc)
6637 {
6638 	struct sysctl_ctx_list *ctx = device_get_sysctl_ctx(sc->sc_dev);
6639 	struct sysctl_oid *tree = device_get_sysctl_tree(sc->sc_dev);
6640 	struct ath_hal *ah = sc->sc_ah;
6641 
6642 	SYSCTL_ADD_INT(ctx, SYSCTL_CHILDREN(tree), OID_AUTO,
6643 		"countrycode", CTLFLAG_RD, &sc->sc_eecc, 0,
6644 		"EEPROM country code");
6645 	SYSCTL_ADD_INT(ctx, SYSCTL_CHILDREN(tree), OID_AUTO,
6646 		"regdomain", CTLFLAG_RD, &sc->sc_eerd, 0,
6647 		"EEPROM regdomain code");
6648 #ifdef	ATH_DEBUG
6649 	sc->sc_debug = ath_debug;
6650 	SYSCTL_ADD_INT(ctx, SYSCTL_CHILDREN(tree), OID_AUTO,
6651 		"debug", CTLFLAG_RW, &sc->sc_debug, 0,
6652 		"control debugging printfs");
6653 #endif
6654 	SYSCTL_ADD_PROC(ctx, SYSCTL_CHILDREN(tree), OID_AUTO,
6655 		"slottime", CTLTYPE_INT | CTLFLAG_RW, sc, 0,
6656 		ath_sysctl_slottime, "I", "802.11 slot time (us)");
6657 	SYSCTL_ADD_PROC(ctx, SYSCTL_CHILDREN(tree), OID_AUTO,
6658 		"acktimeout", CTLTYPE_INT | CTLFLAG_RW, sc, 0,
6659 		ath_sysctl_acktimeout, "I", "802.11 ACK timeout (us)");
6660 	SYSCTL_ADD_PROC(ctx, SYSCTL_CHILDREN(tree), OID_AUTO,
6661 		"ctstimeout", CTLTYPE_INT | CTLFLAG_RW, sc, 0,
6662 		ath_sysctl_ctstimeout, "I", "802.11 CTS timeout (us)");
6663 	SYSCTL_ADD_PROC(ctx, SYSCTL_CHILDREN(tree), OID_AUTO,
6664 		"softled", CTLTYPE_INT | CTLFLAG_RW, sc, 0,
6665 		ath_sysctl_softled, "I", "enable/disable software LED support");
6666 	SYSCTL_ADD_PROC(ctx, SYSCTL_CHILDREN(tree), OID_AUTO,
6667 		"ledpin", CTLTYPE_INT | CTLFLAG_RW, sc, 0,
6668 		ath_sysctl_ledpin, "I", "GPIO pin connected to LED");
6669 	SYSCTL_ADD_INT(ctx, SYSCTL_CHILDREN(tree), OID_AUTO,
6670 		"ledon", CTLFLAG_RW, &sc->sc_ledon, 0,
6671 		"setting to turn LED on");
6672 	SYSCTL_ADD_INT(ctx, SYSCTL_CHILDREN(tree), OID_AUTO,
6673 		"ledidle", CTLFLAG_RW, &sc->sc_ledidle, 0,
6674 		"idle time for inactivity LED (ticks)");
6675 	SYSCTL_ADD_PROC(ctx, SYSCTL_CHILDREN(tree), OID_AUTO,
6676 		"txantenna", CTLTYPE_INT | CTLFLAG_RW, sc, 0,
6677 		ath_sysctl_txantenna, "I", "antenna switch");
6678 	SYSCTL_ADD_PROC(ctx, SYSCTL_CHILDREN(tree), OID_AUTO,
6679 		"rxantenna", CTLTYPE_INT | CTLFLAG_RW, sc, 0,
6680 		ath_sysctl_rxantenna, "I", "default/rx antenna");
6681 	if (ath_hal_hasdiversity(ah))
6682 		SYSCTL_ADD_PROC(ctx, SYSCTL_CHILDREN(tree), OID_AUTO,
6683 			"diversity", CTLTYPE_INT | CTLFLAG_RW, sc, 0,
6684 			ath_sysctl_diversity, "I", "antenna diversity");
6685 	sc->sc_txintrperiod = ATH_TXINTR_PERIOD;
6686 	SYSCTL_ADD_INT(ctx, SYSCTL_CHILDREN(tree), OID_AUTO,
6687 		"txintrperiod", CTLFLAG_RW, &sc->sc_txintrperiod, 0,
6688 		"tx descriptor batching");
6689 	SYSCTL_ADD_PROC(ctx, SYSCTL_CHILDREN(tree), OID_AUTO,
6690 		"diag", CTLTYPE_INT | CTLFLAG_RW, sc, 0,
6691 		ath_sysctl_diag, "I", "h/w diagnostic control");
6692 	SYSCTL_ADD_PROC(ctx, SYSCTL_CHILDREN(tree), OID_AUTO,
6693 		"tpscale", CTLTYPE_INT | CTLFLAG_RW, sc, 0,
6694 		ath_sysctl_tpscale, "I", "tx power scaling");
6695 	if (ath_hal_hastpc(ah)) {
6696 		SYSCTL_ADD_PROC(ctx, SYSCTL_CHILDREN(tree), OID_AUTO,
6697 			"tpc", CTLTYPE_INT | CTLFLAG_RW, sc, 0,
6698 			ath_sysctl_tpc, "I", "enable/disable per-packet TPC");
6699 		SYSCTL_ADD_PROC(ctx, SYSCTL_CHILDREN(tree), OID_AUTO,
6700 			"tpack", CTLTYPE_INT | CTLFLAG_RW, sc, 0,
6701 			ath_sysctl_tpack, "I", "tx power for ack frames");
6702 		SYSCTL_ADD_PROC(ctx, SYSCTL_CHILDREN(tree), OID_AUTO,
6703 			"tpcts", CTLTYPE_INT | CTLFLAG_RW, sc, 0,
6704 			ath_sysctl_tpcts, "I", "tx power for cts frames");
6705 	}
6706 	if (ath_hal_hasfastframes(sc->sc_ah)) {
6707 		sc->sc_fftxqmin = ATH_FF_TXQMIN;
6708 		SYSCTL_ADD_INT(ctx, SYSCTL_CHILDREN(tree), OID_AUTO,
6709 			"fftxqmin", CTLFLAG_RW, &sc->sc_fftxqmin, 0,
6710 			"min frames before fast-frame staging");
6711 		sc->sc_fftxqmax = ATH_FF_TXQMAX;
6712 		SYSCTL_ADD_INT(ctx, SYSCTL_CHILDREN(tree), OID_AUTO,
6713 			"fftxqmax", CTLFLAG_RW, &sc->sc_fftxqmax, 0,
6714 			"max queued frames before tail drop");
6715 	}
6716 	if (ath_hal_hasrfsilent(ah)) {
6717 		SYSCTL_ADD_PROC(ctx, SYSCTL_CHILDREN(tree), OID_AUTO,
6718 			"rfsilent", CTLTYPE_INT | CTLFLAG_RW, sc, 0,
6719 			ath_sysctl_rfsilent, "I", "h/w RF silent config");
6720 		SYSCTL_ADD_PROC(ctx, SYSCTL_CHILDREN(tree), OID_AUTO,
6721 			"rfkill", CTLTYPE_INT | CTLFLAG_RW, sc, 0,
6722 			ath_sysctl_rfkill, "I", "enable/disable RF kill switch");
6723 	}
6724 	sc->sc_monpass = HAL_RXERR_DECRYPT | HAL_RXERR_MIC;
6725 	SYSCTL_ADD_INT(ctx, SYSCTL_CHILDREN(tree), OID_AUTO,
6726 		"monpass", CTLFLAG_RW, &sc->sc_monpass, 0,
6727 		"mask of error frames to pass when monitoring");
6728 }
6729 
6730 static void
6731 ath_bpfattach(struct ath_softc *sc)
6732 {
6733 	struct ifnet *ifp = sc->sc_ifp;
6734 
6735 	bpfattach(ifp, DLT_IEEE802_11_RADIO,
6736 		sizeof(struct ieee80211_frame) + sizeof(sc->sc_tx_th));
6737 	/*
6738 	 * Initialize constant fields.
6739 	 * XXX make header lengths a multiple of 32-bits so subsequent
6740 	 *     headers are properly aligned; this is a kludge to keep
6741 	 *     certain applications happy.
6742 	 *
6743 	 * NB: the channel is setup each time we transition to the
6744 	 *     RUN state to avoid filling it in for each frame.
6745 	 */
6746 	sc->sc_tx_th_len = roundup(sizeof(sc->sc_tx_th), sizeof(u_int32_t));
6747 	sc->sc_tx_th.wt_ihdr.it_len = htole16(sc->sc_tx_th_len);
6748 	sc->sc_tx_th.wt_ihdr.it_present = htole32(ATH_TX_RADIOTAP_PRESENT);
6749 
6750 	sc->sc_rx_th_len = roundup(sizeof(sc->sc_rx_th), sizeof(u_int32_t));
6751 	sc->sc_rx_th.wr_ihdr.it_len = htole16(sc->sc_rx_th_len);
6752 	sc->sc_rx_th.wr_ihdr.it_present = htole32(ATH_RX_RADIOTAP_PRESENT);
6753 }
6754 
6755 static int
6756 ath_tx_raw_start(struct ath_softc *sc, struct ieee80211_node *ni,
6757 	struct ath_buf *bf, struct mbuf *m0,
6758 	const struct ieee80211_bpf_params *params)
6759 {
6760 	struct ifnet *ifp = sc->sc_ifp;
6761 	struct ieee80211com *ic = ifp->if_l2com;
6762 	struct ath_hal *ah = sc->sc_ah;
6763 	int error, ismcast, ismrr;
6764 	int hdrlen, pktlen, try0, txantenna;
6765 	u_int8_t rix, cix, txrate, ctsrate, rate1, rate2, rate3;
6766 	struct ieee80211_frame *wh;
6767 	u_int flags, ctsduration;
6768 	HAL_PKT_TYPE atype;
6769 	const HAL_RATE_TABLE *rt;
6770 	struct ath_desc *ds;
6771 	u_int pri;
6772 
6773 	wh = mtod(m0, struct ieee80211_frame *);
6774 	ismcast = IEEE80211_IS_MULTICAST(wh->i_addr1);
6775 	hdrlen = ieee80211_anyhdrsize(wh);
6776 	/*
6777 	 * Packet length must not include any
6778 	 * pad bytes; deduct them here.
6779 	 */
6780 	/* XXX honor IEEE80211_BPF_DATAPAD */
6781 	pktlen = m0->m_pkthdr.len - (hdrlen & 3) + IEEE80211_CRC_LEN;
6782 
6783 	error = ath_tx_dmasetup(sc, bf, m0);
6784 	if (error != 0)
6785 		return error;
6786 	m0 = bf->bf_m;				/* NB: may have changed */
6787 	wh = mtod(m0, struct ieee80211_frame *);
6788 	bf->bf_node = ni;			/* NB: held reference */
6789 
6790 	flags = HAL_TXDESC_CLRDMASK;		/* XXX needed for crypto errs */
6791 	flags |= HAL_TXDESC_INTREQ;		/* force interrupt */
6792 	if (params->ibp_flags & IEEE80211_BPF_RTS)
6793 		flags |= HAL_TXDESC_RTSENA;
6794 	else if (params->ibp_flags & IEEE80211_BPF_CTS)
6795 		flags |= HAL_TXDESC_CTSENA;
6796 	/* XXX leave ismcast to injector? */
6797 	if ((params->ibp_flags & IEEE80211_BPF_NOACK) || ismcast)
6798 		flags |= HAL_TXDESC_NOACK;
6799 
6800 	rt = sc->sc_currates;
6801 	KASSERT(rt != NULL, ("no rate table, mode %u", sc->sc_curmode));
6802 	rix = ath_tx_findrix(rt, params->ibp_rate0);
6803 	txrate = rt->info[rix].rateCode;
6804 	if (params->ibp_flags & IEEE80211_BPF_SHORTPRE)
6805 		txrate |= rt->info[rix].shortPreamble;
6806 	sc->sc_txrate = txrate;
6807 	try0 = params->ibp_try0;
6808 	ismrr = (params->ibp_try1 != 0);
6809 	txantenna = params->ibp_pri >> 2;
6810 	if (txantenna == 0)			/* XXX? */
6811 		txantenna = sc->sc_txantenna;
6812 	ctsduration = 0;
6813 	if (flags & (HAL_TXDESC_CTSENA | HAL_TXDESC_RTSENA)) {
6814 		cix = ath_tx_findrix(rt, params->ibp_ctsrate);
6815 		ctsrate = rt->info[cix].rateCode;
6816 		if (params->ibp_flags & IEEE80211_BPF_SHORTPRE) {
6817 			ctsrate |= rt->info[cix].shortPreamble;
6818 			if (flags & HAL_TXDESC_RTSENA)		/* SIFS + CTS */
6819 				ctsduration += rt->info[cix].spAckDuration;
6820 			ctsduration += ath_hal_computetxtime(ah,
6821 				rt, pktlen, rix, AH_TRUE);
6822 			if ((flags & HAL_TXDESC_NOACK) == 0)	/* SIFS + ACK */
6823 				ctsduration += rt->info[rix].spAckDuration;
6824 		} else {
6825 			if (flags & HAL_TXDESC_RTSENA)		/* SIFS + CTS */
6826 				ctsduration += rt->info[cix].lpAckDuration;
6827 			ctsduration += ath_hal_computetxtime(ah,
6828 				rt, pktlen, rix, AH_FALSE);
6829 			if ((flags & HAL_TXDESC_NOACK) == 0)	/* SIFS + ACK */
6830 				ctsduration += rt->info[rix].lpAckDuration;
6831 		}
6832 		ismrr = 0;			/* XXX */
6833 	} else
6834 		ctsrate = 0;
6835 	pri = params->ibp_pri & 3;
6836 	/*
6837 	 * NB: we mark all packets as type PSPOLL so the h/w won't
6838 	 * set the sequence number, duration, etc.
6839 	 */
6840 	atype = HAL_PKT_TYPE_PSPOLL;
6841 
6842 	if (IFF_DUMPPKTS(sc, ATH_DEBUG_XMIT))
6843 		ieee80211_dump_pkt(ic, mtod(m0, caddr_t), m0->m_len,
6844 			sc->sc_hwmap[txrate].ieeerate, -1);
6845 
6846 	if (bpf_peers_present(ifp->if_bpf)) {
6847 		u_int64_t tsf = ath_hal_gettsf64(ah);
6848 
6849 		sc->sc_tx_th.wt_tsf = htole64(tsf);
6850 		sc->sc_tx_th.wt_flags = sc->sc_hwmap[txrate].txflags;
6851 		if (wh->i_fc[1] & IEEE80211_FC1_WEP)
6852 			sc->sc_tx_th.wt_flags |= IEEE80211_RADIOTAP_F_WEP;
6853 		sc->sc_tx_th.wt_rate = sc->sc_hwmap[txrate].ieeerate;
6854 		sc->sc_tx_th.wt_txpower = ni->ni_txpower;
6855 		sc->sc_tx_th.wt_antenna = sc->sc_txantenna;
6856 
6857 		bpf_mtap2(ifp->if_bpf, &sc->sc_tx_th, sc->sc_tx_th_len, m0);
6858 	}
6859 
6860 	/*
6861 	 * Formulate first tx descriptor with tx controls.
6862 	 */
6863 	ds = bf->bf_desc;
6864 	/* XXX check return value? */
6865 	ath_hal_setuptxdesc(ah, ds
6866 		, pktlen		/* packet length */
6867 		, hdrlen		/* header length */
6868 		, atype			/* Atheros packet type */
6869 		, params->ibp_power	/* txpower */
6870 		, txrate, try0		/* series 0 rate/tries */
6871 		, HAL_TXKEYIX_INVALID	/* key cache index */
6872 		, txantenna		/* antenna mode */
6873 		, flags			/* flags */
6874 		, ctsrate		/* rts/cts rate */
6875 		, ctsduration		/* rts/cts duration */
6876 	);
6877 	bf->bf_flags = flags;
6878 
6879 	if (ismrr) {
6880 		rix = ath_tx_findrix(rt, params->ibp_rate1);
6881 		rate1 = rt->info[rix].rateCode;
6882 		if (params->ibp_flags & IEEE80211_BPF_SHORTPRE)
6883 			rate1 |= rt->info[rix].shortPreamble;
6884 		if (params->ibp_try2) {
6885 			rix = ath_tx_findrix(rt, params->ibp_rate2);
6886 			rate2 = rt->info[rix].rateCode;
6887 			if (params->ibp_flags & IEEE80211_BPF_SHORTPRE)
6888 				rate2 |= rt->info[rix].shortPreamble;
6889 		} else
6890 			rate2 = 0;
6891 		if (params->ibp_try3) {
6892 			rix = ath_tx_findrix(rt, params->ibp_rate3);
6893 			rate3 = rt->info[rix].rateCode;
6894 			if (params->ibp_flags & IEEE80211_BPF_SHORTPRE)
6895 				rate3 |= rt->info[rix].shortPreamble;
6896 		} else
6897 			rate3 = 0;
6898 		ath_hal_setupxtxdesc(ah, ds
6899 			, rate1, params->ibp_try1	/* series 1 */
6900 			, rate2, params->ibp_try2	/* series 2 */
6901 			, rate3, params->ibp_try3	/* series 3 */
6902 		);
6903 	}
6904 
6905 	/* NB: no buffered multicast in power save support */
6906 	ath_tx_handoff(sc, sc->sc_ac2q[pri], bf);
6907 	return 0;
6908 }
6909 
6910 static int
6911 ath_raw_xmit(struct ieee80211_node *ni, struct mbuf *m,
6912 	const struct ieee80211_bpf_params *params)
6913 {
6914 	struct ieee80211com *ic = ni->ni_ic;
6915 	struct ifnet *ifp = ic->ic_ifp;
6916 	struct ath_softc *sc = ifp->if_softc;
6917 	struct ath_buf *bf;
6918 
6919 	if ((ifp->if_drv_flags & IFF_DRV_RUNNING) == 0 || sc->sc_invalid) {
6920 		ieee80211_free_node(ni);
6921 		m_freem(m);
6922 		return ENETDOWN;
6923 	}
6924 	/*
6925 	 * Grab a TX buffer and associated resources.
6926 	 */
6927 	ATH_TXBUF_LOCK(sc);
6928 	bf = STAILQ_FIRST(&sc->sc_txbuf);
6929 	if (bf != NULL)
6930 		STAILQ_REMOVE_HEAD(&sc->sc_txbuf, bf_list);
6931 	ATH_TXBUF_UNLOCK(sc);
6932 	if (bf == NULL) {
6933 		DPRINTF(sc, ATH_DEBUG_XMIT, "%s: out of xmit buffers\n",
6934 			__func__);
6935 		sc->sc_stats.ast_tx_qstop++;
6936 		ifp->if_drv_flags |= IFF_DRV_OACTIVE;
6937 		ieee80211_free_node(ni);
6938 		m_freem(m);
6939 		return ENOBUFS;
6940 	}
6941 
6942 	ifp->if_opackets++;
6943 	sc->sc_stats.ast_tx_raw++;
6944 
6945 	if (params == NULL) {
6946 		/*
6947 		 * Legacy path; interpret frame contents to decide
6948 		 * precisely how to send the frame.
6949 		 */
6950 		if (ath_tx_start(sc, ni, bf, m))
6951 			goto bad;
6952 	} else {
6953 		/*
6954 		 * Caller supplied explicit parameters to use in
6955 		 * sending the frame.
6956 		 */
6957 		if (ath_tx_raw_start(sc, ni, bf, m, params))
6958 			goto bad;
6959 	}
6960 	ifp->if_timer = 5;
6961 
6962 	return 0;
6963 bad:
6964 	ifp->if_oerrors++;
6965 	ATH_TXBUF_LOCK(sc);
6966 	STAILQ_INSERT_TAIL(&sc->sc_txbuf, bf, bf_list);
6967 	ATH_TXBUF_UNLOCK(sc);
6968 	ieee80211_free_node(ni);
6969 	return EIO;		/* XXX */
6970 }
6971 
6972 /*
6973  * Announce various information on device/driver attach.
6974  */
6975 static void
6976 ath_announce(struct ath_softc *sc)
6977 {
6978 #define	HAL_MODE_DUALBAND	(HAL_MODE_11A|HAL_MODE_11B)
6979 	struct ifnet *ifp = sc->sc_ifp;
6980 	struct ath_hal *ah = sc->sc_ah;
6981 	u_int modes, cc;
6982 
6983 	if_printf(ifp, "mac %d.%d phy %d.%d",
6984 		ah->ah_macVersion, ah->ah_macRev,
6985 		ah->ah_phyRev >> 4, ah->ah_phyRev & 0xf);
6986 	/*
6987 	 * Print radio revision(s).  We check the wireless modes
6988 	 * to avoid falsely printing revs for inoperable parts.
6989 	 * Dual-band radio revs are returned in the 5Ghz rev number.
6990 	 */
6991 	ath_hal_getcountrycode(ah, &cc);
6992 	modes = ath_hal_getwirelessmodes(ah, cc);
6993 	if ((modes & HAL_MODE_DUALBAND) == HAL_MODE_DUALBAND) {
6994 		if (ah->ah_analog5GhzRev && ah->ah_analog2GhzRev)
6995 			printf(" 5ghz radio %d.%d 2ghz radio %d.%d",
6996 				ah->ah_analog5GhzRev >> 4,
6997 				ah->ah_analog5GhzRev & 0xf,
6998 				ah->ah_analog2GhzRev >> 4,
6999 				ah->ah_analog2GhzRev & 0xf);
7000 		else
7001 			printf(" radio %d.%d", ah->ah_analog5GhzRev >> 4,
7002 				ah->ah_analog5GhzRev & 0xf);
7003 	} else
7004 		printf(" radio %d.%d", ah->ah_analog5GhzRev >> 4,
7005 			ah->ah_analog5GhzRev & 0xf);
7006 	printf("\n");
7007 	if (bootverbose) {
7008 		int i;
7009 		for (i = 0; i <= WME_AC_VO; i++) {
7010 			struct ath_txq *txq = sc->sc_ac2q[i];
7011 			if_printf(ifp, "Use hw queue %u for %s traffic\n",
7012 				txq->axq_qnum, ieee80211_wme_acnames[i]);
7013 		}
7014 		if_printf(ifp, "Use hw queue %u for CAB traffic\n",
7015 			sc->sc_cabq->axq_qnum);
7016 		if_printf(ifp, "Use hw queue %u for beacons\n", sc->sc_bhalq);
7017 	}
7018 	if (ath_rxbuf != ATH_RXBUF)
7019 		if_printf(ifp, "using %u rx buffers\n", ath_rxbuf);
7020 	if (ath_txbuf != ATH_TXBUF)
7021 		if_printf(ifp, "using %u tx buffers\n", ath_txbuf);
7022 #undef HAL_MODE_DUALBAND
7023 }
7024