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