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