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