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