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