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