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