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