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