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