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