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