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