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