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