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