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