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