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