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