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