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