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