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