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