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