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