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