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