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