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