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