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