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