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