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