xref: /freebsd/sys/dev/ath/if_ath.c (revision e8e8c939350bdf3c228a411caa9660c607c27a11)
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_ifp->if_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 = ifp->if_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 	device_printf(sc->sc_dev, "hardware error; resetting\n");
2322 	/*
2323 	 * Fatal errors are unrecoverable.  Typically these
2324 	 * are caused by DMA errors.  Collect h/w state from
2325 	 * the hal so we can diagnose what's going on.
2326 	 */
2327 	if (ath_hal_getfatalstate(sc->sc_ah, &sp, &len)) {
2328 		KASSERT(len >= 6*sizeof(u_int32_t), ("len %u bytes", len));
2329 		state = sp;
2330 		device_printf(sc->sc_dev,
2331 		    "0x%08x 0x%08x 0x%08x, 0x%08x 0x%08x 0x%08x\n", state[0],
2332 		    state[1] , state[2], state[3], state[4], state[5]);
2333 	}
2334 	ath_reset(ifp, ATH_RESET_NOLOSS);
2335 }
2336 
2337 static void
2338 ath_bmiss_vap(struct ieee80211vap *vap)
2339 {
2340 	struct ath_softc *sc = vap->iv_ic->ic_ifp->if_softc;
2341 
2342 	/*
2343 	 * Workaround phantom bmiss interrupts by sanity-checking
2344 	 * the time of our last rx'd frame.  If it is within the
2345 	 * beacon miss interval then ignore the interrupt.  If it's
2346 	 * truly a bmiss we'll get another interrupt soon and that'll
2347 	 * be dispatched up for processing.  Note this applies only
2348 	 * for h/w beacon miss events.
2349 	 */
2350 
2351 	/*
2352 	 * XXX TODO: Just read the TSF during the interrupt path;
2353 	 * that way we don't have to wake up again just to read it
2354 	 * again.
2355 	 */
2356 	ATH_LOCK(sc);
2357 	ath_power_set_power_state(sc, HAL_PM_AWAKE);
2358 	ATH_UNLOCK(sc);
2359 
2360 	if ((vap->iv_flags_ext & IEEE80211_FEXT_SWBMISS) == 0) {
2361 		struct ifnet *ifp = vap->iv_ic->ic_ifp;
2362 		struct ath_softc *sc = ifp->if_softc;
2363 		u_int64_t lastrx = sc->sc_lastrx;
2364 		u_int64_t tsf = ath_hal_gettsf64(sc->sc_ah);
2365 		/* XXX should take a locked ref to iv_bss */
2366 		u_int bmisstimeout =
2367 			vap->iv_bmissthreshold * vap->iv_bss->ni_intval * 1024;
2368 
2369 		DPRINTF(sc, ATH_DEBUG_BEACON,
2370 		    "%s: tsf %llu lastrx %lld (%llu) bmiss %u\n",
2371 		    __func__, (unsigned long long) tsf,
2372 		    (unsigned long long)(tsf - lastrx),
2373 		    (unsigned long long) lastrx, bmisstimeout);
2374 
2375 		if (tsf - lastrx <= bmisstimeout) {
2376 			sc->sc_stats.ast_bmiss_phantom++;
2377 
2378 			ATH_LOCK(sc);
2379 			ath_power_restore_power_state(sc);
2380 			ATH_UNLOCK(sc);
2381 
2382 			return;
2383 		}
2384 	}
2385 
2386 	/*
2387 	 * There's no need to keep the hardware awake during the call
2388 	 * to av_bmiss().
2389 	 */
2390 	ATH_LOCK(sc);
2391 	ath_power_restore_power_state(sc);
2392 	ATH_UNLOCK(sc);
2393 
2394 	/*
2395 	 * Attempt to force a beacon resync.
2396 	 */
2397 	sc->sc_syncbeacon = 1;
2398 
2399 	ATH_VAP(vap)->av_bmiss(vap);
2400 }
2401 
2402 /* XXX this needs a force wakeup! */
2403 int
2404 ath_hal_gethangstate(struct ath_hal *ah, uint32_t mask, uint32_t *hangs)
2405 {
2406 	uint32_t rsize;
2407 	void *sp;
2408 
2409 	if (!ath_hal_getdiagstate(ah, HAL_DIAG_CHECK_HANGS, &mask, sizeof(mask), &sp, &rsize))
2410 		return 0;
2411 	KASSERT(rsize == sizeof(uint32_t), ("resultsize %u", rsize));
2412 	*hangs = *(uint32_t *)sp;
2413 	return 1;
2414 }
2415 
2416 static void
2417 ath_bmiss_proc(void *arg, int pending)
2418 {
2419 	struct ath_softc *sc = arg;
2420 	struct ifnet *ifp = sc->sc_ifp;
2421 	uint32_t hangs;
2422 
2423 	DPRINTF(sc, ATH_DEBUG_ANY, "%s: pending %u\n", __func__, pending);
2424 
2425 	ATH_LOCK(sc);
2426 	ath_power_set_power_state(sc, HAL_PM_AWAKE);
2427 	ATH_UNLOCK(sc);
2428 
2429 	ath_beacon_miss(sc);
2430 
2431 	/*
2432 	 * Do a reset upon any becaon miss event.
2433 	 *
2434 	 * It may be a non-recognised RX clear hang which needs a reset
2435 	 * to clear.
2436 	 */
2437 	if (ath_hal_gethangstate(sc->sc_ah, 0xff, &hangs) && hangs != 0) {
2438 		ath_reset(ifp, ATH_RESET_NOLOSS);
2439 		device_printf(sc->sc_dev,
2440 		    "bb hang detected (0x%x), resetting\n", hangs);
2441 	} else {
2442 		ath_reset(ifp, ATH_RESET_NOLOSS);
2443 		ieee80211_beacon_miss(ifp->if_l2com);
2444 	}
2445 
2446 	/* Force a beacon resync, in case they've drifted */
2447 	sc->sc_syncbeacon = 1;
2448 
2449 	ATH_LOCK(sc);
2450 	ath_power_restore_power_state(sc);
2451 	ATH_UNLOCK(sc);
2452 }
2453 
2454 /*
2455  * Handle TKIP MIC setup to deal hardware that doesn't do MIC
2456  * calcs together with WME.  If necessary disable the crypto
2457  * hardware and mark the 802.11 state so keys will be setup
2458  * with the MIC work done in software.
2459  */
2460 static void
2461 ath_settkipmic(struct ath_softc *sc)
2462 {
2463 	struct ifnet *ifp = sc->sc_ifp;
2464 	struct ieee80211com *ic = ifp->if_l2com;
2465 
2466 	if ((ic->ic_cryptocaps & IEEE80211_CRYPTO_TKIP) && !sc->sc_wmetkipmic) {
2467 		if (ic->ic_flags & IEEE80211_F_WME) {
2468 			ath_hal_settkipmic(sc->sc_ah, AH_FALSE);
2469 			ic->ic_cryptocaps &= ~IEEE80211_CRYPTO_TKIPMIC;
2470 		} else {
2471 			ath_hal_settkipmic(sc->sc_ah, AH_TRUE);
2472 			ic->ic_cryptocaps |= IEEE80211_CRYPTO_TKIPMIC;
2473 		}
2474 	}
2475 }
2476 
2477 static void
2478 ath_init(void *arg)
2479 {
2480 	struct ath_softc *sc = (struct ath_softc *) arg;
2481 	struct ifnet *ifp = sc->sc_ifp;
2482 	struct ieee80211com *ic = ifp->if_l2com;
2483 	struct ath_hal *ah = sc->sc_ah;
2484 	HAL_STATUS status;
2485 
2486 	DPRINTF(sc, ATH_DEBUG_ANY, "%s: if_flags 0x%x\n",
2487 		__func__, ifp->if_flags);
2488 
2489 	ATH_LOCK(sc);
2490 	/*
2491 	 * Force the sleep state awake.
2492 	 */
2493 	ath_power_setselfgen(sc, HAL_PM_AWAKE);
2494 	ath_power_set_power_state(sc, HAL_PM_AWAKE);
2495 	ath_power_setpower(sc, HAL_PM_AWAKE);
2496 
2497 	/*
2498 	 * Stop anything previously setup.  This is safe
2499 	 * whether this is the first time through or not.
2500 	 */
2501 	ath_stop_locked(ifp);
2502 
2503 	/*
2504 	 * The basic interface to setting the hardware in a good
2505 	 * state is ``reset''.  On return the hardware is known to
2506 	 * be powered up and with interrupts disabled.  This must
2507 	 * be followed by initialization of the appropriate bits
2508 	 * and then setup of the interrupt mask.
2509 	 */
2510 	ath_settkipmic(sc);
2511 	ath_update_chainmasks(sc, ic->ic_curchan);
2512 	ath_hal_setchainmasks(sc->sc_ah, sc->sc_cur_txchainmask,
2513 	    sc->sc_cur_rxchainmask);
2514 
2515 	if (!ath_hal_reset(ah, sc->sc_opmode, ic->ic_curchan, AH_FALSE,
2516 	    &status)) {
2517 		device_printf(sc->sc_dev,
2518 		    "unable to reset hardware; hal status %u\n", status);
2519 		ATH_UNLOCK(sc);
2520 		return;
2521 	}
2522 
2523 	ATH_RX_LOCK(sc);
2524 	sc->sc_rx_stopped = 1;
2525 	sc->sc_rx_resetted = 1;
2526 	ATH_RX_UNLOCK(sc);
2527 
2528 	ath_chan_change(sc, ic->ic_curchan);
2529 
2530 	/* Let DFS at it in case it's a DFS channel */
2531 	ath_dfs_radar_enable(sc, ic->ic_curchan);
2532 
2533 	/* Let spectral at in case spectral is enabled */
2534 	ath_spectral_enable(sc, ic->ic_curchan);
2535 
2536 	/*
2537 	 * Let bluetooth coexistence at in case it's needed for this channel
2538 	 */
2539 	ath_btcoex_enable(sc, ic->ic_curchan);
2540 
2541 	/*
2542 	 * If we're doing TDMA, enforce the TXOP limitation for chips that
2543 	 * support it.
2544 	 */
2545 	if (sc->sc_hasenforcetxop && sc->sc_tdma)
2546 		ath_hal_setenforcetxop(sc->sc_ah, 1);
2547 	else
2548 		ath_hal_setenforcetxop(sc->sc_ah, 0);
2549 
2550 	/*
2551 	 * Likewise this is set during reset so update
2552 	 * state cached in the driver.
2553 	 */
2554 	sc->sc_diversity = ath_hal_getdiversity(ah);
2555 	sc->sc_lastlongcal = ticks;
2556 	sc->sc_resetcal = 1;
2557 	sc->sc_lastcalreset = 0;
2558 	sc->sc_lastani = ticks;
2559 	sc->sc_lastshortcal = ticks;
2560 	sc->sc_doresetcal = AH_FALSE;
2561 	/*
2562 	 * Beacon timers were cleared here; give ath_newstate()
2563 	 * a hint that the beacon timers should be poked when
2564 	 * things transition to the RUN state.
2565 	 */
2566 	sc->sc_beacons = 0;
2567 
2568 	/*
2569 	 * Setup the hardware after reset: the key cache
2570 	 * is filled as needed and the receive engine is
2571 	 * set going.  Frame transmit is handled entirely
2572 	 * in the frame output path; there's nothing to do
2573 	 * here except setup the interrupt mask.
2574 	 */
2575 	if (ath_startrecv(sc) != 0) {
2576 		device_printf(sc->sc_dev, "unable to start recv logic\n");
2577 		ath_power_restore_power_state(sc);
2578 		ATH_UNLOCK(sc);
2579 		return;
2580 	}
2581 
2582 	/*
2583 	 * Enable interrupts.
2584 	 */
2585 	sc->sc_imask = HAL_INT_RX | HAL_INT_TX
2586 		  | HAL_INT_RXORN | HAL_INT_TXURN
2587 		  | HAL_INT_FATAL | HAL_INT_GLOBAL;
2588 
2589 	/*
2590 	 * Enable RX EDMA bits.  Note these overlap with
2591 	 * HAL_INT_RX and HAL_INT_RXDESC respectively.
2592 	 */
2593 	if (sc->sc_isedma)
2594 		sc->sc_imask |= (HAL_INT_RXHP | HAL_INT_RXLP);
2595 
2596 	/*
2597 	 * If we're an EDMA NIC, we don't care about RXEOL.
2598 	 * Writing a new descriptor in will simply restart
2599 	 * RX DMA.
2600 	 */
2601 	if (! sc->sc_isedma)
2602 		sc->sc_imask |= HAL_INT_RXEOL;
2603 
2604 	/*
2605 	 * Enable MIB interrupts when there are hardware phy counters.
2606 	 * Note we only do this (at the moment) for station mode.
2607 	 */
2608 	if (sc->sc_needmib && ic->ic_opmode == IEEE80211_M_STA)
2609 		sc->sc_imask |= HAL_INT_MIB;
2610 
2611 	/*
2612 	 * XXX add capability for this.
2613 	 *
2614 	 * If we're in STA mode (and maybe IBSS?) then register for
2615 	 * TSFOOR interrupts.
2616 	 */
2617 	if (ic->ic_opmode == IEEE80211_M_STA)
2618 		sc->sc_imask |= HAL_INT_TSFOOR;
2619 
2620 	/* Enable global TX timeout and carrier sense timeout if available */
2621 	if (ath_hal_gtxto_supported(ah))
2622 		sc->sc_imask |= HAL_INT_GTT;
2623 
2624 	DPRINTF(sc, ATH_DEBUG_RESET, "%s: imask=0x%x\n",
2625 		__func__, sc->sc_imask);
2626 
2627 	ifp->if_drv_flags |= IFF_DRV_RUNNING;
2628 	callout_reset(&sc->sc_wd_ch, hz, ath_watchdog, sc);
2629 	ath_hal_intrset(ah, sc->sc_imask);
2630 
2631 	ath_power_restore_power_state(sc);
2632 	ATH_UNLOCK(sc);
2633 
2634 #ifdef ATH_TX99_DIAG
2635 	if (sc->sc_tx99 != NULL)
2636 		sc->sc_tx99->start(sc->sc_tx99);
2637 	else
2638 #endif
2639 	ieee80211_start_all(ic);		/* start all vap's */
2640 }
2641 
2642 static void
2643 ath_stop_locked(struct ifnet *ifp)
2644 {
2645 	struct ath_softc *sc = ifp->if_softc;
2646 	struct ath_hal *ah = sc->sc_ah;
2647 
2648 	DPRINTF(sc, ATH_DEBUG_ANY, "%s: invalid %u if_flags 0x%x\n",
2649 		__func__, sc->sc_invalid, ifp->if_flags);
2650 
2651 	ATH_LOCK_ASSERT(sc);
2652 
2653 	/*
2654 	 * Wake the hardware up before fiddling with it.
2655 	 */
2656 	ath_power_set_power_state(sc, HAL_PM_AWAKE);
2657 
2658 	if (ifp->if_drv_flags & IFF_DRV_RUNNING) {
2659 		/*
2660 		 * Shutdown the hardware and driver:
2661 		 *    reset 802.11 state machine
2662 		 *    turn off timers
2663 		 *    disable interrupts
2664 		 *    turn off the radio
2665 		 *    clear transmit machinery
2666 		 *    clear receive machinery
2667 		 *    drain and release tx queues
2668 		 *    reclaim beacon resources
2669 		 *    power down hardware
2670 		 *
2671 		 * Note that some of this work is not possible if the
2672 		 * hardware is gone (invalid).
2673 		 */
2674 #ifdef ATH_TX99_DIAG
2675 		if (sc->sc_tx99 != NULL)
2676 			sc->sc_tx99->stop(sc->sc_tx99);
2677 #endif
2678 		callout_stop(&sc->sc_wd_ch);
2679 		sc->sc_wd_timer = 0;
2680 		ifp->if_drv_flags &= ~IFF_DRV_RUNNING;
2681 		if (!sc->sc_invalid) {
2682 			if (sc->sc_softled) {
2683 				callout_stop(&sc->sc_ledtimer);
2684 				ath_hal_gpioset(ah, sc->sc_ledpin,
2685 					!sc->sc_ledon);
2686 				sc->sc_blinking = 0;
2687 			}
2688 			ath_hal_intrset(ah, 0);
2689 		}
2690 		/* XXX we should stop RX regardless of whether it's valid */
2691 		if (!sc->sc_invalid) {
2692 			ath_stoprecv(sc, 1);
2693 			ath_hal_phydisable(ah);
2694 		} else
2695 			sc->sc_rxlink = NULL;
2696 		ath_draintxq(sc, ATH_RESET_DEFAULT);
2697 		ath_beacon_free(sc);	/* XXX not needed */
2698 	}
2699 
2700 	/* And now, restore the current power state */
2701 	ath_power_restore_power_state(sc);
2702 }
2703 
2704 /*
2705  * Wait until all pending TX/RX has completed.
2706  *
2707  * This waits until all existing transmit, receive and interrupts
2708  * have completed.  It's assumed that the caller has first
2709  * grabbed the reset lock so it doesn't try to do overlapping
2710  * chip resets.
2711  */
2712 #define	MAX_TXRX_ITERATIONS	100
2713 static void
2714 ath_txrx_stop_locked(struct ath_softc *sc)
2715 {
2716 	int i = MAX_TXRX_ITERATIONS;
2717 
2718 	ATH_UNLOCK_ASSERT(sc);
2719 	ATH_PCU_LOCK_ASSERT(sc);
2720 
2721 	/*
2722 	 * Sleep until all the pending operations have completed.
2723 	 *
2724 	 * The caller must ensure that reset has been incremented
2725 	 * or the pending operations may continue being queued.
2726 	 */
2727 	while (sc->sc_rxproc_cnt || sc->sc_txproc_cnt ||
2728 	    sc->sc_txstart_cnt || sc->sc_intr_cnt) {
2729 		if (i <= 0)
2730 			break;
2731 		msleep(sc, &sc->sc_pcu_mtx, 0, "ath_txrx_stop",
2732 		    msecs_to_ticks(10));
2733 		i--;
2734 	}
2735 
2736 	if (i <= 0)
2737 		device_printf(sc->sc_dev,
2738 		    "%s: didn't finish after %d iterations\n",
2739 		    __func__, MAX_TXRX_ITERATIONS);
2740 }
2741 #undef	MAX_TXRX_ITERATIONS
2742 
2743 #if 0
2744 static void
2745 ath_txrx_stop(struct ath_softc *sc)
2746 {
2747 	ATH_UNLOCK_ASSERT(sc);
2748 	ATH_PCU_UNLOCK_ASSERT(sc);
2749 
2750 	ATH_PCU_LOCK(sc);
2751 	ath_txrx_stop_locked(sc);
2752 	ATH_PCU_UNLOCK(sc);
2753 }
2754 #endif
2755 
2756 static void
2757 ath_txrx_start(struct ath_softc *sc)
2758 {
2759 
2760 	taskqueue_unblock(sc->sc_tq);
2761 }
2762 
2763 /*
2764  * Grab the reset lock, and wait around until noone else
2765  * is trying to do anything with it.
2766  *
2767  * This is totally horrible but we can't hold this lock for
2768  * long enough to do TX/RX or we end up with net80211/ip stack
2769  * LORs and eventual deadlock.
2770  *
2771  * "dowait" signals whether to spin, waiting for the reset
2772  * lock count to reach 0. This should (for now) only be used
2773  * during the reset path, as the rest of the code may not
2774  * be locking-reentrant enough to behave correctly.
2775  *
2776  * Another, cleaner way should be found to serialise all of
2777  * these operations.
2778  */
2779 #define	MAX_RESET_ITERATIONS	25
2780 static int
2781 ath_reset_grablock(struct ath_softc *sc, int dowait)
2782 {
2783 	int w = 0;
2784 	int i = MAX_RESET_ITERATIONS;
2785 
2786 	ATH_PCU_LOCK_ASSERT(sc);
2787 	do {
2788 		if (sc->sc_inreset_cnt == 0) {
2789 			w = 1;
2790 			break;
2791 		}
2792 		if (dowait == 0) {
2793 			w = 0;
2794 			break;
2795 		}
2796 		ATH_PCU_UNLOCK(sc);
2797 		/*
2798 		 * 1 tick is likely not enough time for long calibrations
2799 		 * to complete.  So we should wait quite a while.
2800 		 */
2801 		pause("ath_reset_grablock", msecs_to_ticks(100));
2802 		i--;
2803 		ATH_PCU_LOCK(sc);
2804 	} while (i > 0);
2805 
2806 	/*
2807 	 * We always increment the refcounter, regardless
2808 	 * of whether we succeeded to get it in an exclusive
2809 	 * way.
2810 	 */
2811 	sc->sc_inreset_cnt++;
2812 
2813 	if (i <= 0)
2814 		device_printf(sc->sc_dev,
2815 		    "%s: didn't finish after %d iterations\n",
2816 		    __func__, MAX_RESET_ITERATIONS);
2817 
2818 	if (w == 0)
2819 		device_printf(sc->sc_dev,
2820 		    "%s: warning, recursive reset path!\n",
2821 		    __func__);
2822 
2823 	return w;
2824 }
2825 #undef MAX_RESET_ITERATIONS
2826 
2827 /*
2828  * XXX TODO: write ath_reset_releaselock
2829  */
2830 
2831 static void
2832 ath_stop(struct ifnet *ifp)
2833 {
2834 	struct ath_softc *sc = ifp->if_softc;
2835 
2836 	ATH_LOCK(sc);
2837 	ath_stop_locked(ifp);
2838 	ATH_UNLOCK(sc);
2839 }
2840 
2841 /*
2842  * Reset the hardware w/o losing operational state.  This is
2843  * basically a more efficient way of doing ath_stop, ath_init,
2844  * followed by state transitions to the current 802.11
2845  * operational state.  Used to recover from various errors and
2846  * to reset or reload hardware state.
2847  */
2848 int
2849 ath_reset(struct ifnet *ifp, ATH_RESET_TYPE reset_type)
2850 {
2851 	struct ath_softc *sc = ifp->if_softc;
2852 	struct ieee80211com *ic = ifp->if_l2com;
2853 	struct ath_hal *ah = sc->sc_ah;
2854 	HAL_STATUS status;
2855 	int i;
2856 
2857 	DPRINTF(sc, ATH_DEBUG_RESET, "%s: called\n", __func__);
2858 
2859 	/* Ensure ATH_LOCK isn't held; ath_rx_proc can't be locked */
2860 	ATH_PCU_UNLOCK_ASSERT(sc);
2861 	ATH_UNLOCK_ASSERT(sc);
2862 
2863 	/* Try to (stop any further TX/RX from occuring */
2864 	taskqueue_block(sc->sc_tq);
2865 
2866 	/*
2867 	 * Wake the hardware up.
2868 	 */
2869 	ATH_LOCK(sc);
2870 	ath_power_set_power_state(sc, HAL_PM_AWAKE);
2871 	ATH_UNLOCK(sc);
2872 
2873 	ATH_PCU_LOCK(sc);
2874 
2875 	/*
2876 	 * Grab the reset lock before TX/RX is stopped.
2877 	 *
2878 	 * This is needed to ensure that when the TX/RX actually does finish,
2879 	 * no further TX/RX/reset runs in parallel with this.
2880 	 */
2881 	if (ath_reset_grablock(sc, 1) == 0) {
2882 		device_printf(sc->sc_dev, "%s: concurrent reset! Danger!\n",
2883 		    __func__);
2884 	}
2885 
2886 	/* disable interrupts */
2887 	ath_hal_intrset(ah, 0);
2888 
2889 	/*
2890 	 * Now, ensure that any in progress TX/RX completes before we
2891 	 * continue.
2892 	 */
2893 	ath_txrx_stop_locked(sc);
2894 
2895 	ATH_PCU_UNLOCK(sc);
2896 
2897 	/*
2898 	 * Regardless of whether we're doing a no-loss flush or
2899 	 * not, stop the PCU and handle what's in the RX queue.
2900 	 * That way frames aren't dropped which shouldn't be.
2901 	 */
2902 	ath_stoprecv(sc, (reset_type != ATH_RESET_NOLOSS));
2903 	ath_rx_flush(sc);
2904 
2905 	/*
2906 	 * Should now wait for pending TX/RX to complete
2907 	 * and block future ones from occuring. This needs to be
2908 	 * done before the TX queue is drained.
2909 	 */
2910 	ath_draintxq(sc, reset_type);	/* stop xmit side */
2911 
2912 	ath_settkipmic(sc);		/* configure TKIP MIC handling */
2913 	/* NB: indicate channel change so we do a full reset */
2914 	ath_update_chainmasks(sc, ic->ic_curchan);
2915 	ath_hal_setchainmasks(sc->sc_ah, sc->sc_cur_txchainmask,
2916 	    sc->sc_cur_rxchainmask);
2917 	if (!ath_hal_reset(ah, sc->sc_opmode, ic->ic_curchan, AH_TRUE, &status))
2918 		device_printf(sc->sc_dev,
2919 		    "%s: unable to reset hardware; hal status %u\n",
2920 		    __func__, status);
2921 	sc->sc_diversity = ath_hal_getdiversity(ah);
2922 
2923 	ATH_RX_LOCK(sc);
2924 	sc->sc_rx_stopped = 1;
2925 	sc->sc_rx_resetted = 1;
2926 	ATH_RX_UNLOCK(sc);
2927 
2928 	/* Let DFS at it in case it's a DFS channel */
2929 	ath_dfs_radar_enable(sc, ic->ic_curchan);
2930 
2931 	/* Let spectral at in case spectral is enabled */
2932 	ath_spectral_enable(sc, ic->ic_curchan);
2933 
2934 	/*
2935 	 * Let bluetooth coexistence at in case it's needed for this channel
2936 	 */
2937 	ath_btcoex_enable(sc, ic->ic_curchan);
2938 
2939 	/*
2940 	 * If we're doing TDMA, enforce the TXOP limitation for chips that
2941 	 * support it.
2942 	 */
2943 	if (sc->sc_hasenforcetxop && sc->sc_tdma)
2944 		ath_hal_setenforcetxop(sc->sc_ah, 1);
2945 	else
2946 		ath_hal_setenforcetxop(sc->sc_ah, 0);
2947 
2948 	if (ath_startrecv(sc) != 0)	/* restart recv */
2949 		device_printf(sc->sc_dev,
2950 		    "%s: unable to start recv logic\n", __func__);
2951 	/*
2952 	 * We may be doing a reset in response to an ioctl
2953 	 * that changes the channel so update any state that
2954 	 * might change as a result.
2955 	 */
2956 	ath_chan_change(sc, ic->ic_curchan);
2957 	if (sc->sc_beacons) {		/* restart beacons */
2958 #ifdef IEEE80211_SUPPORT_TDMA
2959 		if (sc->sc_tdma)
2960 			ath_tdma_config(sc, NULL);
2961 		else
2962 #endif
2963 			ath_beacon_config(sc, NULL);
2964 	}
2965 
2966 	/*
2967 	 * Release the reset lock and re-enable interrupts here.
2968 	 * If an interrupt was being processed in ath_intr(),
2969 	 * it would disable interrupts at this point. So we have
2970 	 * to atomically enable interrupts and decrement the
2971 	 * reset counter - this way ath_intr() doesn't end up
2972 	 * disabling interrupts without a corresponding enable
2973 	 * in the rest or channel change path.
2974 	 *
2975 	 * Grab the TX reference in case we need to transmit.
2976 	 * That way a parallel transmit doesn't.
2977 	 */
2978 	ATH_PCU_LOCK(sc);
2979 	sc->sc_inreset_cnt--;
2980 	sc->sc_txstart_cnt++;
2981 	/* XXX only do this if sc_inreset_cnt == 0? */
2982 	ath_hal_intrset(ah, sc->sc_imask);
2983 	ATH_PCU_UNLOCK(sc);
2984 
2985 	/*
2986 	 * TX and RX can be started here. If it were started with
2987 	 * sc_inreset_cnt > 0, the TX and RX path would abort.
2988 	 * Thus if this is a nested call through the reset or
2989 	 * channel change code, TX completion will occur but
2990 	 * RX completion and ath_start / ath_tx_start will not
2991 	 * run.
2992 	 */
2993 
2994 	/* Restart TX/RX as needed */
2995 	ath_txrx_start(sc);
2996 
2997 	/* XXX TODO: we need to hold the tx refcount here! */
2998 
2999 	/* Restart TX completion and pending TX */
3000 	if (reset_type == ATH_RESET_NOLOSS) {
3001 		for (i = 0; i < HAL_NUM_TX_QUEUES; i++) {
3002 			if (ATH_TXQ_SETUP(sc, i)) {
3003 				ATH_TXQ_LOCK(&sc->sc_txq[i]);
3004 				ath_txq_restart_dma(sc, &sc->sc_txq[i]);
3005 				ATH_TXQ_UNLOCK(&sc->sc_txq[i]);
3006 
3007 				ATH_TX_LOCK(sc);
3008 				ath_txq_sched(sc, &sc->sc_txq[i]);
3009 				ATH_TX_UNLOCK(sc);
3010 			}
3011 		}
3012 	}
3013 
3014 	/*
3015 	 * This may have been set during an ath_start() call which
3016 	 * set this once it detected a concurrent TX was going on.
3017 	 * So, clear it.
3018 	 */
3019 	IF_LOCK(&ifp->if_snd);
3020 	ifp->if_drv_flags &= ~IFF_DRV_OACTIVE;
3021 	IF_UNLOCK(&ifp->if_snd);
3022 
3023 	ATH_LOCK(sc);
3024 	ath_power_restore_power_state(sc);
3025 	ATH_UNLOCK(sc);
3026 
3027 	ATH_PCU_LOCK(sc);
3028 	sc->sc_txstart_cnt--;
3029 	ATH_PCU_UNLOCK(sc);
3030 
3031 	/* Handle any frames in the TX queue */
3032 	/*
3033 	 * XXX should this be done by the caller, rather than
3034 	 * ath_reset() ?
3035 	 */
3036 	ath_tx_kick(sc);		/* restart xmit */
3037 	return 0;
3038 }
3039 
3040 static int
3041 ath_reset_vap(struct ieee80211vap *vap, u_long cmd)
3042 {
3043 	struct ieee80211com *ic = vap->iv_ic;
3044 	struct ifnet *ifp = ic->ic_ifp;
3045 	struct ath_softc *sc = ifp->if_softc;
3046 	struct ath_hal *ah = sc->sc_ah;
3047 
3048 	switch (cmd) {
3049 	case IEEE80211_IOC_TXPOWER:
3050 		/*
3051 		 * If per-packet TPC is enabled, then we have nothing
3052 		 * to do; otherwise we need to force the global limit.
3053 		 * All this can happen directly; no need to reset.
3054 		 */
3055 		if (!ath_hal_gettpc(ah))
3056 			ath_hal_settxpowlimit(ah, ic->ic_txpowlimit);
3057 		return 0;
3058 	}
3059 	/* XXX? Full or NOLOSS? */
3060 	return ath_reset(ifp, ATH_RESET_FULL);
3061 }
3062 
3063 struct ath_buf *
3064 _ath_getbuf_locked(struct ath_softc *sc, ath_buf_type_t btype)
3065 {
3066 	struct ath_buf *bf;
3067 
3068 	ATH_TXBUF_LOCK_ASSERT(sc);
3069 
3070 	if (btype == ATH_BUFTYPE_MGMT)
3071 		bf = TAILQ_FIRST(&sc->sc_txbuf_mgmt);
3072 	else
3073 		bf = TAILQ_FIRST(&sc->sc_txbuf);
3074 
3075 	if (bf == NULL) {
3076 		sc->sc_stats.ast_tx_getnobuf++;
3077 	} else {
3078 		if (bf->bf_flags & ATH_BUF_BUSY) {
3079 			sc->sc_stats.ast_tx_getbusybuf++;
3080 			bf = NULL;
3081 		}
3082 	}
3083 
3084 	if (bf != NULL && (bf->bf_flags & ATH_BUF_BUSY) == 0) {
3085 		if (btype == ATH_BUFTYPE_MGMT)
3086 			TAILQ_REMOVE(&sc->sc_txbuf_mgmt, bf, bf_list);
3087 		else {
3088 			TAILQ_REMOVE(&sc->sc_txbuf, bf, bf_list);
3089 			sc->sc_txbuf_cnt--;
3090 
3091 			/*
3092 			 * This shuldn't happen; however just to be
3093 			 * safe print a warning and fudge the txbuf
3094 			 * count.
3095 			 */
3096 			if (sc->sc_txbuf_cnt < 0) {
3097 				device_printf(sc->sc_dev,
3098 				    "%s: sc_txbuf_cnt < 0?\n",
3099 				    __func__);
3100 				sc->sc_txbuf_cnt = 0;
3101 			}
3102 		}
3103 	} else
3104 		bf = NULL;
3105 
3106 	if (bf == NULL) {
3107 		/* XXX should check which list, mgmt or otherwise */
3108 		DPRINTF(sc, ATH_DEBUG_XMIT, "%s: %s\n", __func__,
3109 		    TAILQ_FIRST(&sc->sc_txbuf) == NULL ?
3110 			"out of xmit buffers" : "xmit buffer busy");
3111 		return NULL;
3112 	}
3113 
3114 	/* XXX TODO: should do this at buffer list initialisation */
3115 	/* XXX (then, ensure the buffer has the right flag set) */
3116 	bf->bf_flags = 0;
3117 	if (btype == ATH_BUFTYPE_MGMT)
3118 		bf->bf_flags |= ATH_BUF_MGMT;
3119 	else
3120 		bf->bf_flags &= (~ATH_BUF_MGMT);
3121 
3122 	/* Valid bf here; clear some basic fields */
3123 	bf->bf_next = NULL;	/* XXX just to be sure */
3124 	bf->bf_last = NULL;	/* XXX again, just to be sure */
3125 	bf->bf_comp = NULL;	/* XXX again, just to be sure */
3126 	bzero(&bf->bf_state, sizeof(bf->bf_state));
3127 
3128 	/*
3129 	 * Track the descriptor ID only if doing EDMA
3130 	 */
3131 	if (sc->sc_isedma) {
3132 		bf->bf_descid = sc->sc_txbuf_descid;
3133 		sc->sc_txbuf_descid++;
3134 	}
3135 
3136 	return bf;
3137 }
3138 
3139 /*
3140  * When retrying a software frame, buffers marked ATH_BUF_BUSY
3141  * can't be thrown back on the queue as they could still be
3142  * in use by the hardware.
3143  *
3144  * This duplicates the buffer, or returns NULL.
3145  *
3146  * The descriptor is also copied but the link pointers and
3147  * the DMA segments aren't copied; this frame should thus
3148  * be again passed through the descriptor setup/chain routines
3149  * so the link is correct.
3150  *
3151  * The caller must free the buffer using ath_freebuf().
3152  */
3153 struct ath_buf *
3154 ath_buf_clone(struct ath_softc *sc, struct ath_buf *bf)
3155 {
3156 	struct ath_buf *tbf;
3157 
3158 	tbf = ath_getbuf(sc,
3159 	    (bf->bf_flags & ATH_BUF_MGMT) ?
3160 	     ATH_BUFTYPE_MGMT : ATH_BUFTYPE_NORMAL);
3161 	if (tbf == NULL)
3162 		return NULL;	/* XXX failure? Why? */
3163 
3164 	/* Copy basics */
3165 	tbf->bf_next = NULL;
3166 	tbf->bf_nseg = bf->bf_nseg;
3167 	tbf->bf_flags = bf->bf_flags & ATH_BUF_FLAGS_CLONE;
3168 	tbf->bf_status = bf->bf_status;
3169 	tbf->bf_m = bf->bf_m;
3170 	tbf->bf_node = bf->bf_node;
3171 	KASSERT((bf->bf_node != NULL), ("%s: bf_node=NULL!", __func__));
3172 	/* will be setup by the chain/setup function */
3173 	tbf->bf_lastds = NULL;
3174 	/* for now, last == self */
3175 	tbf->bf_last = tbf;
3176 	tbf->bf_comp = bf->bf_comp;
3177 
3178 	/* NOTE: DMA segments will be setup by the setup/chain functions */
3179 
3180 	/* The caller has to re-init the descriptor + links */
3181 
3182 	/*
3183 	 * Free the DMA mapping here, before we NULL the mbuf.
3184 	 * We must only call bus_dmamap_unload() once per mbuf chain
3185 	 * or behaviour is undefined.
3186 	 */
3187 	if (bf->bf_m != NULL) {
3188 		/*
3189 		 * XXX is this POSTWRITE call required?
3190 		 */
3191 		bus_dmamap_sync(sc->sc_dmat, bf->bf_dmamap,
3192 		    BUS_DMASYNC_POSTWRITE);
3193 		bus_dmamap_unload(sc->sc_dmat, bf->bf_dmamap);
3194 	}
3195 
3196 	bf->bf_m = NULL;
3197 	bf->bf_node = NULL;
3198 
3199 	/* Copy state */
3200 	memcpy(&tbf->bf_state, &bf->bf_state, sizeof(bf->bf_state));
3201 
3202 	return tbf;
3203 }
3204 
3205 struct ath_buf *
3206 ath_getbuf(struct ath_softc *sc, ath_buf_type_t btype)
3207 {
3208 	struct ath_buf *bf;
3209 
3210 	ATH_TXBUF_LOCK(sc);
3211 	bf = _ath_getbuf_locked(sc, btype);
3212 	/*
3213 	 * If a mgmt buffer was requested but we're out of those,
3214 	 * try requesting a normal one.
3215 	 */
3216 	if (bf == NULL && btype == ATH_BUFTYPE_MGMT)
3217 		bf = _ath_getbuf_locked(sc, ATH_BUFTYPE_NORMAL);
3218 	ATH_TXBUF_UNLOCK(sc);
3219 	if (bf == NULL) {
3220 		struct ifnet *ifp = sc->sc_ifp;
3221 
3222 		DPRINTF(sc, ATH_DEBUG_XMIT, "%s: stop queue\n", __func__);
3223 		sc->sc_stats.ast_tx_qstop++;
3224 		IF_LOCK(&ifp->if_snd);
3225 		ifp->if_drv_flags |= IFF_DRV_OACTIVE;
3226 		IF_UNLOCK(&ifp->if_snd);
3227 	}
3228 	return bf;
3229 }
3230 
3231 static void
3232 ath_qflush(struct ifnet *ifp)
3233 {
3234 
3235 	/* XXX TODO */
3236 }
3237 
3238 /*
3239  * Transmit a single frame.
3240  *
3241  * net80211 will free the node reference if the transmit
3242  * fails, so don't free the node reference here.
3243  */
3244 static int
3245 ath_transmit(struct ifnet *ifp, struct mbuf *m)
3246 {
3247 	struct ieee80211com *ic = ifp->if_l2com;
3248 	struct ath_softc *sc = ic->ic_ifp->if_softc;
3249 	struct ieee80211_node *ni;
3250 	struct mbuf *next;
3251 	struct ath_buf *bf;
3252 	ath_bufhead frags;
3253 	int retval = 0;
3254 
3255 	/*
3256 	 * Tell the reset path that we're currently transmitting.
3257 	 */
3258 	ATH_PCU_LOCK(sc);
3259 	if (sc->sc_inreset_cnt > 0) {
3260 		DPRINTF(sc, ATH_DEBUG_XMIT,
3261 		    "%s: sc_inreset_cnt > 0; bailing\n", __func__);
3262 		ATH_PCU_UNLOCK(sc);
3263 		IF_LOCK(&ifp->if_snd);
3264 		sc->sc_stats.ast_tx_qstop++;
3265 		ifp->if_drv_flags |= IFF_DRV_OACTIVE;
3266 		IF_UNLOCK(&ifp->if_snd);
3267 		ATH_KTR(sc, ATH_KTR_TX, 0, "ath_start_task: OACTIVE, finish");
3268 		return (ENOBUFS);	/* XXX should be EINVAL or? */
3269 	}
3270 	sc->sc_txstart_cnt++;
3271 	ATH_PCU_UNLOCK(sc);
3272 
3273 	/* Wake the hardware up already */
3274 	ATH_LOCK(sc);
3275 	ath_power_set_power_state(sc, HAL_PM_AWAKE);
3276 	ATH_UNLOCK(sc);
3277 
3278 	ATH_KTR(sc, ATH_KTR_TX, 0, "ath_transmit: start");
3279 	/*
3280 	 * Grab the TX lock - it's ok to do this here; we haven't
3281 	 * yet started transmitting.
3282 	 */
3283 	ATH_TX_LOCK(sc);
3284 
3285 	/*
3286 	 * Node reference, if there's one.
3287 	 */
3288 	ni = (struct ieee80211_node *) m->m_pkthdr.rcvif;
3289 
3290 	/*
3291 	 * Enforce how deep a node queue can get.
3292 	 *
3293 	 * XXX it would be nicer if we kept an mbuf queue per
3294 	 * node and only whacked them into ath_bufs when we
3295 	 * are ready to schedule some traffic from them.
3296 	 * .. that may come later.
3297 	 *
3298 	 * XXX we should also track the per-node hardware queue
3299 	 * depth so it is easy to limit the _SUM_ of the swq and
3300 	 * hwq frames.  Since we only schedule two HWQ frames
3301 	 * at a time, this should be OK for now.
3302 	 */
3303 	if ((!(m->m_flags & M_EAPOL)) &&
3304 	    (ATH_NODE(ni)->an_swq_depth > sc->sc_txq_node_maxdepth)) {
3305 		sc->sc_stats.ast_tx_nodeq_overflow++;
3306 		m_freem(m);
3307 		m = NULL;
3308 		retval = ENOBUFS;
3309 		goto finish;
3310 	}
3311 
3312 	/*
3313 	 * Check how many TX buffers are available.
3314 	 *
3315 	 * If this is for non-EAPOL traffic, just leave some
3316 	 * space free in order for buffer cloning and raw
3317 	 * frame transmission to occur.
3318 	 *
3319 	 * If it's for EAPOL traffic, ignore this for now.
3320 	 * Management traffic will be sent via the raw transmit
3321 	 * method which bypasses this check.
3322 	 *
3323 	 * This is needed to ensure that EAPOL frames during
3324 	 * (re) keying have a chance to go out.
3325 	 *
3326 	 * See kern/138379 for more information.
3327 	 */
3328 	if ((!(m->m_flags & M_EAPOL)) &&
3329 	    (sc->sc_txbuf_cnt <= sc->sc_txq_data_minfree)) {
3330 		sc->sc_stats.ast_tx_nobuf++;
3331 		m_freem(m);
3332 		m = NULL;
3333 		retval = ENOBUFS;
3334 		goto finish;
3335 	}
3336 
3337 	/*
3338 	 * Grab a TX buffer and associated resources.
3339 	 *
3340 	 * If it's an EAPOL frame, allocate a MGMT ath_buf.
3341 	 * That way even with temporary buffer exhaustion due to
3342 	 * the data path doesn't leave us without the ability
3343 	 * to transmit management frames.
3344 	 *
3345 	 * Otherwise allocate a normal buffer.
3346 	 */
3347 	if (m->m_flags & M_EAPOL)
3348 		bf = ath_getbuf(sc, ATH_BUFTYPE_MGMT);
3349 	else
3350 		bf = ath_getbuf(sc, ATH_BUFTYPE_NORMAL);
3351 
3352 	if (bf == NULL) {
3353 		/*
3354 		 * If we failed to allocate a buffer, fail.
3355 		 *
3356 		 * We shouldn't fail normally, due to the check
3357 		 * above.
3358 		 */
3359 		sc->sc_stats.ast_tx_nobuf++;
3360 		IF_LOCK(&ifp->if_snd);
3361 		ifp->if_drv_flags |= IFF_DRV_OACTIVE;
3362 		IF_UNLOCK(&ifp->if_snd);
3363 		m_freem(m);
3364 		m = NULL;
3365 		retval = ENOBUFS;
3366 		goto finish;
3367 	}
3368 
3369 	/*
3370 	 * At this point we have a buffer; so we need to free it
3371 	 * if we hit any error conditions.
3372 	 */
3373 
3374 	/*
3375 	 * Check for fragmentation.  If this frame
3376 	 * has been broken up verify we have enough
3377 	 * buffers to send all the fragments so all
3378 	 * go out or none...
3379 	 */
3380 	TAILQ_INIT(&frags);
3381 	if ((m->m_flags & M_FRAG) &&
3382 	    !ath_txfrag_setup(sc, &frags, m, ni)) {
3383 		DPRINTF(sc, ATH_DEBUG_XMIT,
3384 		    "%s: out of txfrag buffers\n", __func__);
3385 		sc->sc_stats.ast_tx_nofrag++;
3386 		if_inc_counter(ifp, IFCOUNTER_OERRORS, 1);
3387 		ath_freetx(m);
3388 		goto bad;
3389 	}
3390 
3391 	/*
3392 	 * At this point if we have any TX fragments, then we will
3393 	 * have bumped the node reference once for each of those.
3394 	 */
3395 
3396 	/*
3397 	 * XXX Is there anything actually _enforcing_ that the
3398 	 * fragments are being transmitted in one hit, rather than
3399 	 * being interleaved with other transmissions on that
3400 	 * hardware queue?
3401 	 *
3402 	 * The ATH TX output lock is the only thing serialising this
3403 	 * right now.
3404 	 */
3405 
3406 	/*
3407 	 * Calculate the "next fragment" length field in ath_buf
3408 	 * in order to let the transmit path know enough about
3409 	 * what to next write to the hardware.
3410 	 */
3411 	if (m->m_flags & M_FRAG) {
3412 		struct ath_buf *fbf = bf;
3413 		struct ath_buf *n_fbf = NULL;
3414 		struct mbuf *fm = m->m_nextpkt;
3415 
3416 		/*
3417 		 * We need to walk the list of fragments and set
3418 		 * the next size to the following buffer.
3419 		 * However, the first buffer isn't in the frag
3420 		 * list, so we have to do some gymnastics here.
3421 		 */
3422 		TAILQ_FOREACH(n_fbf, &frags, bf_list) {
3423 			fbf->bf_nextfraglen = fm->m_pkthdr.len;
3424 			fbf = n_fbf;
3425 			fm = fm->m_nextpkt;
3426 		}
3427 	}
3428 
3429 	/*
3430 	 * Bump the ifp output counter.
3431 	 *
3432 	 * XXX should use atomics?
3433 	 */
3434 	if_inc_counter(ifp, IFCOUNTER_OPACKETS, 1);
3435 nextfrag:
3436 	/*
3437 	 * Pass the frame to the h/w for transmission.
3438 	 * Fragmented frames have each frag chained together
3439 	 * with m_nextpkt.  We know there are sufficient ath_buf's
3440 	 * to send all the frags because of work done by
3441 	 * ath_txfrag_setup.  We leave m_nextpkt set while
3442 	 * calling ath_tx_start so it can use it to extend the
3443 	 * the tx duration to cover the subsequent frag and
3444 	 * so it can reclaim all the mbufs in case of an error;
3445 	 * ath_tx_start clears m_nextpkt once it commits to
3446 	 * handing the frame to the hardware.
3447 	 *
3448 	 * Note: if this fails, then the mbufs are freed but
3449 	 * not the node reference.
3450 	 */
3451 	next = m->m_nextpkt;
3452 	if (ath_tx_start(sc, ni, bf, m)) {
3453 bad:
3454 		if_inc_counter(ifp, IFCOUNTER_OERRORS, 1);
3455 reclaim:
3456 		bf->bf_m = NULL;
3457 		bf->bf_node = NULL;
3458 		ATH_TXBUF_LOCK(sc);
3459 		ath_returnbuf_head(sc, bf);
3460 		/*
3461 		 * Free the rest of the node references and
3462 		 * buffers for the fragment list.
3463 		 */
3464 		ath_txfrag_cleanup(sc, &frags, ni);
3465 		ATH_TXBUF_UNLOCK(sc);
3466 		retval = ENOBUFS;
3467 		goto finish;
3468 	}
3469 
3470 	/*
3471 	 * Check here if the node is in power save state.
3472 	 */
3473 	ath_tx_update_tim(sc, ni, 1);
3474 
3475 	if (next != NULL) {
3476 		/*
3477 		 * Beware of state changing between frags.
3478 		 * XXX check sta power-save state?
3479 		 */
3480 		if (ni->ni_vap->iv_state != IEEE80211_S_RUN) {
3481 			DPRINTF(sc, ATH_DEBUG_XMIT,
3482 			    "%s: flush fragmented packet, state %s\n",
3483 			    __func__,
3484 			    ieee80211_state_name[ni->ni_vap->iv_state]);
3485 			/* XXX dmamap */
3486 			ath_freetx(next);
3487 			goto reclaim;
3488 		}
3489 		m = next;
3490 		bf = TAILQ_FIRST(&frags);
3491 		KASSERT(bf != NULL, ("no buf for txfrag"));
3492 		TAILQ_REMOVE(&frags, bf, bf_list);
3493 		goto nextfrag;
3494 	}
3495 
3496 	/*
3497 	 * Bump watchdog timer.
3498 	 */
3499 	sc->sc_wd_timer = 5;
3500 
3501 finish:
3502 	ATH_TX_UNLOCK(sc);
3503 
3504 	/*
3505 	 * Finished transmitting!
3506 	 */
3507 	ATH_PCU_LOCK(sc);
3508 	sc->sc_txstart_cnt--;
3509 	ATH_PCU_UNLOCK(sc);
3510 
3511 	/* Sleep the hardware if required */
3512 	ATH_LOCK(sc);
3513 	ath_power_restore_power_state(sc);
3514 	ATH_UNLOCK(sc);
3515 
3516 	ATH_KTR(sc, ATH_KTR_TX, 0, "ath_transmit: finished");
3517 
3518 	return (retval);
3519 }
3520 
3521 static int
3522 ath_media_change(struct ifnet *ifp)
3523 {
3524 	int error = ieee80211_media_change(ifp);
3525 	/* NB: only the fixed rate can change and that doesn't need a reset */
3526 	return (error == ENETRESET ? 0 : error);
3527 }
3528 
3529 /*
3530  * Block/unblock tx+rx processing while a key change is done.
3531  * We assume the caller serializes key management operations
3532  * so we only need to worry about synchronization with other
3533  * uses that originate in the driver.
3534  */
3535 static void
3536 ath_key_update_begin(struct ieee80211vap *vap)
3537 {
3538 	struct ifnet *ifp = vap->iv_ic->ic_ifp;
3539 	struct ath_softc *sc = ifp->if_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 ifnet *ifp = vap->iv_ic->ic_ifp;
3549 	struct ath_softc *sc = ifp->if_softc;
3550 
3551 	DPRINTF(sc, ATH_DEBUG_KEYCACHE, "%s:\n", __func__);
3552 	taskqueue_unblock(sc->sc_tq);
3553 }
3554 
3555 static void
3556 ath_update_promisc(struct ieee80211com *ic)
3557 {
3558 	struct ath_softc *sc = ic->ic_softc;
3559 	u_int32_t rfilt;
3560 
3561 	/* configure rx filter */
3562 	ATH_LOCK(sc);
3563 	ath_power_set_power_state(sc, HAL_PM_AWAKE);
3564 	rfilt = ath_calcrxfilter(sc);
3565 	ath_hal_setrxfilter(sc->sc_ah, rfilt);
3566 	ath_power_restore_power_state(sc);
3567 	ATH_UNLOCK(sc);
3568 
3569 	DPRINTF(sc, ATH_DEBUG_MODE, "%s: RX filter 0x%x\n", __func__, rfilt);
3570 }
3571 
3572 /*
3573  * Driver-internal mcast update call.
3574  *
3575  * Assumes the hardware is already awake.
3576  */
3577 static void
3578 ath_update_mcast_hw(struct ath_softc *sc)
3579 {
3580 	struct ifnet *ifp = sc->sc_ifp;
3581 	u_int32_t mfilt[2];
3582 
3583 	/* calculate and install multicast filter */
3584 	if ((ifp->if_flags & IFF_ALLMULTI) == 0) {
3585 		struct ifmultiaddr *ifma;
3586 		/*
3587 		 * Merge multicast addresses to form the hardware filter.
3588 		 */
3589 		mfilt[0] = mfilt[1] = 0;
3590 		if_maddr_rlock(ifp);	/* XXX need some fiddling to remove? */
3591 		TAILQ_FOREACH(ifma, &ifp->if_multiaddrs, ifma_link) {
3592 			caddr_t dl;
3593 			u_int32_t val;
3594 			u_int8_t pos;
3595 
3596 			/* calculate XOR of eight 6bit values */
3597 			dl = LLADDR((struct sockaddr_dl *) ifma->ifma_addr);
3598 			val = LE_READ_4(dl + 0);
3599 			pos = (val >> 18) ^ (val >> 12) ^ (val >> 6) ^ val;
3600 			val = LE_READ_4(dl + 3);
3601 			pos ^= (val >> 18) ^ (val >> 12) ^ (val >> 6) ^ val;
3602 			pos &= 0x3f;
3603 			mfilt[pos / 32] |= (1 << (pos % 32));
3604 		}
3605 		if_maddr_runlock(ifp);
3606 	} else
3607 		mfilt[0] = mfilt[1] = ~0;
3608 
3609 	ath_hal_setmcastfilter(sc->sc_ah, mfilt[0], mfilt[1]);
3610 
3611 	DPRINTF(sc, ATH_DEBUG_MODE, "%s: MC filter %08x:%08x\n",
3612 		__func__, mfilt[0], mfilt[1]);
3613 }
3614 
3615 /*
3616  * Called from the net80211 layer - force the hardware
3617  * awake before operating.
3618  */
3619 static void
3620 ath_update_mcast(struct ieee80211com *ic)
3621 {
3622 	struct ath_softc *sc = ic->ic_softc;
3623 
3624 	ATH_LOCK(sc);
3625 	ath_power_set_power_state(sc, HAL_PM_AWAKE);
3626 	ATH_UNLOCK(sc);
3627 
3628 	ath_update_mcast_hw(sc);
3629 
3630 	ATH_LOCK(sc);
3631 	ath_power_restore_power_state(sc);
3632 	ATH_UNLOCK(sc);
3633 }
3634 
3635 void
3636 ath_mode_init(struct ath_softc *sc)
3637 {
3638 	struct ifnet *ifp = sc->sc_ifp;
3639 	struct ath_hal *ah = sc->sc_ah;
3640 	u_int32_t rfilt;
3641 
3642 	/* configure rx filter */
3643 	rfilt = ath_calcrxfilter(sc);
3644 	ath_hal_setrxfilter(ah, rfilt);
3645 
3646 	/* configure operational mode */
3647 	ath_hal_setopmode(ah);
3648 
3649 	DPRINTF(sc, ATH_DEBUG_STATE | ATH_DEBUG_MODE,
3650 	    "%s: ah=%p, ifp=%p, if_addr=%p\n",
3651 	    __func__,
3652 	    ah,
3653 	    ifp,
3654 	    (ifp == NULL) ? NULL : ifp->if_addr);
3655 
3656 	/* handle any link-level address change */
3657 	ath_hal_setmac(ah, IF_LLADDR(ifp));
3658 
3659 	/* calculate and install multicast filter */
3660 	ath_update_mcast_hw(sc);
3661 }
3662 
3663 /*
3664  * Set the slot time based on the current setting.
3665  */
3666 void
3667 ath_setslottime(struct ath_softc *sc)
3668 {
3669 	struct ieee80211com *ic = sc->sc_ifp->if_l2com;
3670 	struct ath_hal *ah = sc->sc_ah;
3671 	u_int usec;
3672 
3673 	if (IEEE80211_IS_CHAN_HALF(ic->ic_curchan))
3674 		usec = 13;
3675 	else if (IEEE80211_IS_CHAN_QUARTER(ic->ic_curchan))
3676 		usec = 21;
3677 	else if (IEEE80211_IS_CHAN_ANYG(ic->ic_curchan)) {
3678 		/* honor short/long slot time only in 11g */
3679 		/* XXX shouldn't honor on pure g or turbo g channel */
3680 		if (ic->ic_flags & IEEE80211_F_SHSLOT)
3681 			usec = HAL_SLOT_TIME_9;
3682 		else
3683 			usec = HAL_SLOT_TIME_20;
3684 	} else
3685 		usec = HAL_SLOT_TIME_9;
3686 
3687 	DPRINTF(sc, ATH_DEBUG_RESET,
3688 	    "%s: chan %u MHz flags 0x%x %s slot, %u usec\n",
3689 	    __func__, ic->ic_curchan->ic_freq, ic->ic_curchan->ic_flags,
3690 	    ic->ic_flags & IEEE80211_F_SHSLOT ? "short" : "long", usec);
3691 
3692 	/* Wake up the hardware first before updating the slot time */
3693 	ATH_LOCK(sc);
3694 	ath_power_set_power_state(sc, HAL_PM_AWAKE);
3695 	ath_hal_setslottime(ah, usec);
3696 	ath_power_restore_power_state(sc);
3697 	sc->sc_updateslot = OK;
3698 	ATH_UNLOCK(sc);
3699 }
3700 
3701 /*
3702  * Callback from the 802.11 layer to update the
3703  * slot time based on the current setting.
3704  */
3705 static void
3706 ath_updateslot(struct ieee80211com *ic)
3707 {
3708 	struct ath_softc *sc = ic->ic_softc;
3709 
3710 	/*
3711 	 * When not coordinating the BSS, change the hardware
3712 	 * immediately.  For other operation we defer the change
3713 	 * until beacon updates have propagated to the stations.
3714 	 *
3715 	 * XXX sc_updateslot isn't changed behind a lock?
3716 	 */
3717 	if (ic->ic_opmode == IEEE80211_M_HOSTAP ||
3718 	    ic->ic_opmode == IEEE80211_M_MBSS)
3719 		sc->sc_updateslot = UPDATE;
3720 	else
3721 		ath_setslottime(sc);
3722 }
3723 
3724 /*
3725  * Append the contents of src to dst; both queues
3726  * are assumed to be locked.
3727  */
3728 void
3729 ath_txqmove(struct ath_txq *dst, struct ath_txq *src)
3730 {
3731 
3732 	ATH_TXQ_LOCK_ASSERT(src);
3733 	ATH_TXQ_LOCK_ASSERT(dst);
3734 
3735 	TAILQ_CONCAT(&dst->axq_q, &src->axq_q, bf_list);
3736 	dst->axq_link = src->axq_link;
3737 	src->axq_link = NULL;
3738 	dst->axq_depth += src->axq_depth;
3739 	dst->axq_aggr_depth += src->axq_aggr_depth;
3740 	src->axq_depth = 0;
3741 	src->axq_aggr_depth = 0;
3742 }
3743 
3744 /*
3745  * Reset the hardware, with no loss.
3746  *
3747  * This can't be used for a general case reset.
3748  */
3749 static void
3750 ath_reset_proc(void *arg, int pending)
3751 {
3752 	struct ath_softc *sc = arg;
3753 	struct ifnet *ifp = sc->sc_ifp;
3754 
3755 #if 0
3756 	device_printf(sc->sc_dev, "%s: resetting\n", __func__);
3757 #endif
3758 	ath_reset(ifp, ATH_RESET_NOLOSS);
3759 }
3760 
3761 /*
3762  * Reset the hardware after detecting beacons have stopped.
3763  */
3764 static void
3765 ath_bstuck_proc(void *arg, int pending)
3766 {
3767 	struct ath_softc *sc = arg;
3768 	struct ifnet *ifp = sc->sc_ifp;
3769 	uint32_t hangs = 0;
3770 
3771 	if (ath_hal_gethangstate(sc->sc_ah, 0xff, &hangs) && hangs != 0)
3772 		device_printf(sc->sc_dev, "bb hang detected (0x%x)\n", hangs);
3773 
3774 #ifdef	ATH_DEBUG_ALQ
3775 	if (if_ath_alq_checkdebug(&sc->sc_alq, ATH_ALQ_STUCK_BEACON))
3776 		if_ath_alq_post(&sc->sc_alq, ATH_ALQ_STUCK_BEACON, 0, NULL);
3777 #endif
3778 
3779 	device_printf(sc->sc_dev, "stuck beacon; resetting (bmiss count %u)\n",
3780 	    sc->sc_bmisscount);
3781 	sc->sc_stats.ast_bstuck++;
3782 	/*
3783 	 * This assumes that there's no simultaneous channel mode change
3784 	 * occuring.
3785 	 */
3786 	ath_reset(ifp, ATH_RESET_NOLOSS);
3787 }
3788 
3789 static void
3790 ath_load_cb(void *arg, bus_dma_segment_t *segs, int nsegs, int error)
3791 {
3792 	bus_addr_t *paddr = (bus_addr_t*) arg;
3793 	KASSERT(error == 0, ("error %u on bus_dma callback", error));
3794 	*paddr = segs->ds_addr;
3795 }
3796 
3797 /*
3798  * Allocate the descriptors and appropriate DMA tag/setup.
3799  *
3800  * For some situations (eg EDMA TX completion), there isn't a requirement
3801  * for the ath_buf entries to be allocated.
3802  */
3803 int
3804 ath_descdma_alloc_desc(struct ath_softc *sc,
3805 	struct ath_descdma *dd, ath_bufhead *head,
3806 	const char *name, int ds_size, int ndesc)
3807 {
3808 #define	DS2PHYS(_dd, _ds) \
3809 	((_dd)->dd_desc_paddr + ((caddr_t)(_ds) - (caddr_t)(_dd)->dd_desc))
3810 #define	ATH_DESC_4KB_BOUND_CHECK(_daddr, _len) \
3811 	((((u_int32_t)(_daddr) & 0xFFF) > (0x1000 - (_len))) ? 1 : 0)
3812 	int error;
3813 
3814 	dd->dd_descsize = ds_size;
3815 
3816 	DPRINTF(sc, ATH_DEBUG_RESET,
3817 	    "%s: %s DMA: %u desc, %d bytes per descriptor\n",
3818 	    __func__, name, ndesc, dd->dd_descsize);
3819 
3820 	dd->dd_name = name;
3821 	dd->dd_desc_len = dd->dd_descsize * ndesc;
3822 
3823 	/*
3824 	 * Merlin work-around:
3825 	 * Descriptors that cross the 4KB boundary can't be used.
3826 	 * Assume one skipped descriptor per 4KB page.
3827 	 */
3828 	if (! ath_hal_split4ktrans(sc->sc_ah)) {
3829 		int numpages = dd->dd_desc_len / 4096;
3830 		dd->dd_desc_len += ds_size * numpages;
3831 	}
3832 
3833 	/*
3834 	 * Setup DMA descriptor area.
3835 	 *
3836 	 * BUS_DMA_ALLOCNOW is not used; we never use bounce
3837 	 * buffers for the descriptors themselves.
3838 	 */
3839 	error = bus_dma_tag_create(bus_get_dma_tag(sc->sc_dev),	/* parent */
3840 		       PAGE_SIZE, 0,		/* alignment, bounds */
3841 		       BUS_SPACE_MAXADDR_32BIT,	/* lowaddr */
3842 		       BUS_SPACE_MAXADDR,	/* highaddr */
3843 		       NULL, NULL,		/* filter, filterarg */
3844 		       dd->dd_desc_len,		/* maxsize */
3845 		       1,			/* nsegments */
3846 		       dd->dd_desc_len,		/* maxsegsize */
3847 		       0,			/* flags */
3848 		       NULL,			/* lockfunc */
3849 		       NULL,			/* lockarg */
3850 		       &dd->dd_dmat);
3851 	if (error != 0) {
3852 		device_printf(sc->sc_dev,
3853 		    "cannot allocate %s DMA tag\n", dd->dd_name);
3854 		return error;
3855 	}
3856 
3857 	/* allocate descriptors */
3858 	error = bus_dmamem_alloc(dd->dd_dmat, (void**) &dd->dd_desc,
3859 				 BUS_DMA_NOWAIT | BUS_DMA_COHERENT,
3860 				 &dd->dd_dmamap);
3861 	if (error != 0) {
3862 		device_printf(sc->sc_dev,
3863 		    "unable to alloc memory for %u %s descriptors, error %u\n",
3864 		    ndesc, dd->dd_name, error);
3865 		goto fail1;
3866 	}
3867 
3868 	error = bus_dmamap_load(dd->dd_dmat, dd->dd_dmamap,
3869 				dd->dd_desc, dd->dd_desc_len,
3870 				ath_load_cb, &dd->dd_desc_paddr,
3871 				BUS_DMA_NOWAIT);
3872 	if (error != 0) {
3873 		device_printf(sc->sc_dev,
3874 		    "unable to map %s descriptors, error %u\n",
3875 		    dd->dd_name, error);
3876 		goto fail2;
3877 	}
3878 
3879 	DPRINTF(sc, ATH_DEBUG_RESET, "%s: %s DMA map: %p (%lu) -> %p (%lu)\n",
3880 	    __func__, dd->dd_name, (uint8_t *) dd->dd_desc,
3881 	    (u_long) dd->dd_desc_len, (caddr_t) dd->dd_desc_paddr,
3882 	    /*XXX*/ (u_long) dd->dd_desc_len);
3883 
3884 	return (0);
3885 
3886 fail2:
3887 	bus_dmamem_free(dd->dd_dmat, dd->dd_desc, dd->dd_dmamap);
3888 fail1:
3889 	bus_dma_tag_destroy(dd->dd_dmat);
3890 	memset(dd, 0, sizeof(*dd));
3891 	return error;
3892 #undef DS2PHYS
3893 #undef ATH_DESC_4KB_BOUND_CHECK
3894 }
3895 
3896 int
3897 ath_descdma_setup(struct ath_softc *sc,
3898 	struct ath_descdma *dd, ath_bufhead *head,
3899 	const char *name, int ds_size, int nbuf, int ndesc)
3900 {
3901 #define	DS2PHYS(_dd, _ds) \
3902 	((_dd)->dd_desc_paddr + ((caddr_t)(_ds) - (caddr_t)(_dd)->dd_desc))
3903 #define	ATH_DESC_4KB_BOUND_CHECK(_daddr, _len) \
3904 	((((u_int32_t)(_daddr) & 0xFFF) > (0x1000 - (_len))) ? 1 : 0)
3905 	uint8_t *ds;
3906 	struct ath_buf *bf;
3907 	int i, bsize, error;
3908 
3909 	/* Allocate descriptors */
3910 	error = ath_descdma_alloc_desc(sc, dd, head, name, ds_size,
3911 	    nbuf * ndesc);
3912 
3913 	/* Assume any errors during allocation were dealt with */
3914 	if (error != 0) {
3915 		return (error);
3916 	}
3917 
3918 	ds = (uint8_t *) dd->dd_desc;
3919 
3920 	/* allocate rx buffers */
3921 	bsize = sizeof(struct ath_buf) * nbuf;
3922 	bf = malloc(bsize, M_ATHDEV, M_NOWAIT | M_ZERO);
3923 	if (bf == NULL) {
3924 		device_printf(sc->sc_dev,
3925 		    "malloc of %s buffers failed, size %u\n",
3926 		    dd->dd_name, bsize);
3927 		goto fail3;
3928 	}
3929 	dd->dd_bufptr = bf;
3930 
3931 	TAILQ_INIT(head);
3932 	for (i = 0; i < nbuf; i++, bf++, ds += (ndesc * dd->dd_descsize)) {
3933 		bf->bf_desc = (struct ath_desc *) ds;
3934 		bf->bf_daddr = DS2PHYS(dd, ds);
3935 		if (! ath_hal_split4ktrans(sc->sc_ah)) {
3936 			/*
3937 			 * Merlin WAR: Skip descriptor addresses which
3938 			 * cause 4KB boundary crossing along any point
3939 			 * in the descriptor.
3940 			 */
3941 			 if (ATH_DESC_4KB_BOUND_CHECK(bf->bf_daddr,
3942 			     dd->dd_descsize)) {
3943 				/* Start at the next page */
3944 				ds += 0x1000 - (bf->bf_daddr & 0xFFF);
3945 				bf->bf_desc = (struct ath_desc *) ds;
3946 				bf->bf_daddr = DS2PHYS(dd, ds);
3947 			}
3948 		}
3949 		error = bus_dmamap_create(sc->sc_dmat, BUS_DMA_NOWAIT,
3950 				&bf->bf_dmamap);
3951 		if (error != 0) {
3952 			device_printf(sc->sc_dev, "unable to create dmamap "
3953 			    "for %s buffer %u, error %u\n",
3954 			    dd->dd_name, i, error);
3955 			ath_descdma_cleanup(sc, dd, head);
3956 			return error;
3957 		}
3958 		bf->bf_lastds = bf->bf_desc;	/* Just an initial value */
3959 		TAILQ_INSERT_TAIL(head, bf, bf_list);
3960 	}
3961 
3962 	/*
3963 	 * XXX TODO: ensure that ds doesn't overflow the descriptor
3964 	 * allocation otherwise weird stuff will occur and crash your
3965 	 * machine.
3966 	 */
3967 	return 0;
3968 	/* XXX this should likely just call ath_descdma_cleanup() */
3969 fail3:
3970 	bus_dmamap_unload(dd->dd_dmat, dd->dd_dmamap);
3971 	bus_dmamem_free(dd->dd_dmat, dd->dd_desc, dd->dd_dmamap);
3972 	bus_dma_tag_destroy(dd->dd_dmat);
3973 	memset(dd, 0, sizeof(*dd));
3974 	return error;
3975 #undef DS2PHYS
3976 #undef ATH_DESC_4KB_BOUND_CHECK
3977 }
3978 
3979 /*
3980  * Allocate ath_buf entries but no descriptor contents.
3981  *
3982  * This is for RX EDMA where the descriptors are the header part of
3983  * the RX buffer.
3984  */
3985 int
3986 ath_descdma_setup_rx_edma(struct ath_softc *sc,
3987 	struct ath_descdma *dd, ath_bufhead *head,
3988 	const char *name, int nbuf, int rx_status_len)
3989 {
3990 	struct ath_buf *bf;
3991 	int i, bsize, error;
3992 
3993 	DPRINTF(sc, ATH_DEBUG_RESET, "%s: %s DMA: %u buffers\n",
3994 	    __func__, name, nbuf);
3995 
3996 	dd->dd_name = name;
3997 	/*
3998 	 * This is (mostly) purely for show.  We're not allocating any actual
3999 	 * descriptors here as EDMA RX has the descriptor be part
4000 	 * of the RX buffer.
4001 	 *
4002 	 * However, dd_desc_len is used by ath_descdma_free() to determine
4003 	 * whether we have already freed this DMA mapping.
4004 	 */
4005 	dd->dd_desc_len = rx_status_len * nbuf;
4006 	dd->dd_descsize = rx_status_len;
4007 
4008 	/* allocate rx buffers */
4009 	bsize = sizeof(struct ath_buf) * nbuf;
4010 	bf = malloc(bsize, M_ATHDEV, M_NOWAIT | M_ZERO);
4011 	if (bf == NULL) {
4012 		device_printf(sc->sc_dev,
4013 		    "malloc of %s buffers failed, size %u\n",
4014 		    dd->dd_name, bsize);
4015 		error = ENOMEM;
4016 		goto fail3;
4017 	}
4018 	dd->dd_bufptr = bf;
4019 
4020 	TAILQ_INIT(head);
4021 	for (i = 0; i < nbuf; i++, bf++) {
4022 		bf->bf_desc = NULL;
4023 		bf->bf_daddr = 0;
4024 		bf->bf_lastds = NULL;	/* Just an initial value */
4025 
4026 		error = bus_dmamap_create(sc->sc_dmat, BUS_DMA_NOWAIT,
4027 				&bf->bf_dmamap);
4028 		if (error != 0) {
4029 			device_printf(sc->sc_dev, "unable to create dmamap "
4030 			    "for %s buffer %u, error %u\n",
4031 			    dd->dd_name, i, error);
4032 			ath_descdma_cleanup(sc, dd, head);
4033 			return error;
4034 		}
4035 		TAILQ_INSERT_TAIL(head, bf, bf_list);
4036 	}
4037 	return 0;
4038 fail3:
4039 	memset(dd, 0, sizeof(*dd));
4040 	return error;
4041 }
4042 
4043 void
4044 ath_descdma_cleanup(struct ath_softc *sc,
4045 	struct ath_descdma *dd, ath_bufhead *head)
4046 {
4047 	struct ath_buf *bf;
4048 	struct ieee80211_node *ni;
4049 	int do_warning = 0;
4050 
4051 	if (dd->dd_dmamap != 0) {
4052 		bus_dmamap_unload(dd->dd_dmat, dd->dd_dmamap);
4053 		bus_dmamem_free(dd->dd_dmat, dd->dd_desc, dd->dd_dmamap);
4054 		bus_dma_tag_destroy(dd->dd_dmat);
4055 	}
4056 
4057 	if (head != NULL) {
4058 		TAILQ_FOREACH(bf, head, bf_list) {
4059 			if (bf->bf_m) {
4060 				/*
4061 				 * XXX warn if there's buffers here.
4062 				 * XXX it should have been freed by the
4063 				 * owner!
4064 				 */
4065 
4066 				if (do_warning == 0) {
4067 					do_warning = 1;
4068 					device_printf(sc->sc_dev,
4069 					    "%s: %s: mbuf should've been"
4070 					    " unmapped/freed!\n",
4071 					    __func__,
4072 					    dd->dd_name);
4073 				}
4074 				bus_dmamap_sync(sc->sc_dmat, bf->bf_dmamap,
4075 				    BUS_DMASYNC_POSTREAD);
4076 				bus_dmamap_unload(sc->sc_dmat, bf->bf_dmamap);
4077 				m_freem(bf->bf_m);
4078 				bf->bf_m = NULL;
4079 			}
4080 			if (bf->bf_dmamap != NULL) {
4081 				bus_dmamap_destroy(sc->sc_dmat, bf->bf_dmamap);
4082 				bf->bf_dmamap = NULL;
4083 			}
4084 			ni = bf->bf_node;
4085 			bf->bf_node = NULL;
4086 			if (ni != NULL) {
4087 				/*
4088 				 * Reclaim node reference.
4089 				 */
4090 				ieee80211_free_node(ni);
4091 			}
4092 		}
4093 	}
4094 
4095 	if (head != NULL)
4096 		TAILQ_INIT(head);
4097 
4098 	if (dd->dd_bufptr != NULL)
4099 		free(dd->dd_bufptr, M_ATHDEV);
4100 	memset(dd, 0, sizeof(*dd));
4101 }
4102 
4103 static int
4104 ath_desc_alloc(struct ath_softc *sc)
4105 {
4106 	int error;
4107 
4108 	error = ath_descdma_setup(sc, &sc->sc_txdma, &sc->sc_txbuf,
4109 		    "tx", sc->sc_tx_desclen, ath_txbuf, ATH_MAX_SCATTER);
4110 	if (error != 0) {
4111 		return error;
4112 	}
4113 	sc->sc_txbuf_cnt = ath_txbuf;
4114 
4115 	error = ath_descdma_setup(sc, &sc->sc_txdma_mgmt, &sc->sc_txbuf_mgmt,
4116 		    "tx_mgmt", sc->sc_tx_desclen, ath_txbuf_mgmt,
4117 		    ATH_TXDESC);
4118 	if (error != 0) {
4119 		ath_descdma_cleanup(sc, &sc->sc_txdma, &sc->sc_txbuf);
4120 		return error;
4121 	}
4122 
4123 	/*
4124 	 * XXX mark txbuf_mgmt frames with ATH_BUF_MGMT, so the
4125 	 * flag doesn't have to be set in ath_getbuf_locked().
4126 	 */
4127 
4128 	error = ath_descdma_setup(sc, &sc->sc_bdma, &sc->sc_bbuf,
4129 			"beacon", sc->sc_tx_desclen, ATH_BCBUF, 1);
4130 	if (error != 0) {
4131 		ath_descdma_cleanup(sc, &sc->sc_txdma, &sc->sc_txbuf);
4132 		ath_descdma_cleanup(sc, &sc->sc_txdma_mgmt,
4133 		    &sc->sc_txbuf_mgmt);
4134 		return error;
4135 	}
4136 	return 0;
4137 }
4138 
4139 static void
4140 ath_desc_free(struct ath_softc *sc)
4141 {
4142 
4143 	if (sc->sc_bdma.dd_desc_len != 0)
4144 		ath_descdma_cleanup(sc, &sc->sc_bdma, &sc->sc_bbuf);
4145 	if (sc->sc_txdma.dd_desc_len != 0)
4146 		ath_descdma_cleanup(sc, &sc->sc_txdma, &sc->sc_txbuf);
4147 	if (sc->sc_txdma_mgmt.dd_desc_len != 0)
4148 		ath_descdma_cleanup(sc, &sc->sc_txdma_mgmt,
4149 		    &sc->sc_txbuf_mgmt);
4150 }
4151 
4152 static struct ieee80211_node *
4153 ath_node_alloc(struct ieee80211vap *vap, const uint8_t mac[IEEE80211_ADDR_LEN])
4154 {
4155 	struct ieee80211com *ic = vap->iv_ic;
4156 	struct ath_softc *sc = ic->ic_ifp->if_softc;
4157 	const size_t space = sizeof(struct ath_node) + sc->sc_rc->arc_space;
4158 	struct ath_node *an;
4159 
4160 	an = malloc(space, M_80211_NODE, M_NOWAIT|M_ZERO);
4161 	if (an == NULL) {
4162 		/* XXX stat+msg */
4163 		return NULL;
4164 	}
4165 	ath_rate_node_init(sc, an);
4166 
4167 	/* Setup the mutex - there's no associd yet so set the name to NULL */
4168 	snprintf(an->an_name, sizeof(an->an_name), "%s: node %p",
4169 	    device_get_nameunit(sc->sc_dev), an);
4170 	mtx_init(&an->an_mtx, an->an_name, NULL, MTX_DEF);
4171 
4172 	/* XXX setup ath_tid */
4173 	ath_tx_tid_init(sc, an);
4174 
4175 	DPRINTF(sc, ATH_DEBUG_NODE, "%s: %6D: an %p\n", __func__, mac, ":", an);
4176 	return &an->an_node;
4177 }
4178 
4179 static void
4180 ath_node_cleanup(struct ieee80211_node *ni)
4181 {
4182 	struct ieee80211com *ic = ni->ni_ic;
4183 	struct ath_softc *sc = ic->ic_ifp->if_softc;
4184 
4185 	DPRINTF(sc, ATH_DEBUG_NODE, "%s: %6D: an %p\n", __func__,
4186 	    ni->ni_macaddr, ":", ATH_NODE(ni));
4187 
4188 	/* Cleanup ath_tid, free unused bufs, unlink bufs in TXQ */
4189 	ath_tx_node_flush(sc, ATH_NODE(ni));
4190 	ath_rate_node_cleanup(sc, ATH_NODE(ni));
4191 	sc->sc_node_cleanup(ni);
4192 }
4193 
4194 static void
4195 ath_node_free(struct ieee80211_node *ni)
4196 {
4197 	struct ieee80211com *ic = ni->ni_ic;
4198 	struct ath_softc *sc = ic->ic_ifp->if_softc;
4199 
4200 	DPRINTF(sc, ATH_DEBUG_NODE, "%s: %6D: an %p\n", __func__,
4201 	    ni->ni_macaddr, ":", ATH_NODE(ni));
4202 	mtx_destroy(&ATH_NODE(ni)->an_mtx);
4203 	sc->sc_node_free(ni);
4204 }
4205 
4206 static void
4207 ath_node_getsignal(const struct ieee80211_node *ni, int8_t *rssi, int8_t *noise)
4208 {
4209 	struct ieee80211com *ic = ni->ni_ic;
4210 	struct ath_softc *sc = ic->ic_ifp->if_softc;
4211 	struct ath_hal *ah = sc->sc_ah;
4212 
4213 	*rssi = ic->ic_node_getrssi(ni);
4214 	if (ni->ni_chan != IEEE80211_CHAN_ANYC)
4215 		*noise = ath_hal_getchannoise(ah, ni->ni_chan);
4216 	else
4217 		*noise = -95;		/* nominally correct */
4218 }
4219 
4220 /*
4221  * Set the default antenna.
4222  */
4223 void
4224 ath_setdefantenna(struct ath_softc *sc, u_int antenna)
4225 {
4226 	struct ath_hal *ah = sc->sc_ah;
4227 
4228 	/* XXX block beacon interrupts */
4229 	ath_hal_setdefantenna(ah, antenna);
4230 	if (sc->sc_defant != antenna)
4231 		sc->sc_stats.ast_ant_defswitch++;
4232 	sc->sc_defant = antenna;
4233 	sc->sc_rxotherant = 0;
4234 }
4235 
4236 static void
4237 ath_txq_init(struct ath_softc *sc, struct ath_txq *txq, int qnum)
4238 {
4239 	txq->axq_qnum = qnum;
4240 	txq->axq_ac = 0;
4241 	txq->axq_depth = 0;
4242 	txq->axq_aggr_depth = 0;
4243 	txq->axq_intrcnt = 0;
4244 	txq->axq_link = NULL;
4245 	txq->axq_softc = sc;
4246 	TAILQ_INIT(&txq->axq_q);
4247 	TAILQ_INIT(&txq->axq_tidq);
4248 	TAILQ_INIT(&txq->fifo.axq_q);
4249 	ATH_TXQ_LOCK_INIT(sc, txq);
4250 }
4251 
4252 /*
4253  * Setup a h/w transmit queue.
4254  */
4255 static struct ath_txq *
4256 ath_txq_setup(struct ath_softc *sc, int qtype, int subtype)
4257 {
4258 #define	N(a)	(sizeof(a)/sizeof(a[0]))
4259 	struct ath_hal *ah = sc->sc_ah;
4260 	HAL_TXQ_INFO qi;
4261 	int qnum;
4262 
4263 	memset(&qi, 0, sizeof(qi));
4264 	qi.tqi_subtype = subtype;
4265 	qi.tqi_aifs = HAL_TXQ_USEDEFAULT;
4266 	qi.tqi_cwmin = HAL_TXQ_USEDEFAULT;
4267 	qi.tqi_cwmax = HAL_TXQ_USEDEFAULT;
4268 	/*
4269 	 * Enable interrupts only for EOL and DESC conditions.
4270 	 * We mark tx descriptors to receive a DESC interrupt
4271 	 * when a tx queue gets deep; otherwise waiting for the
4272 	 * EOL to reap descriptors.  Note that this is done to
4273 	 * reduce interrupt load and this only defers reaping
4274 	 * descriptors, never transmitting frames.  Aside from
4275 	 * reducing interrupts this also permits more concurrency.
4276 	 * The only potential downside is if the tx queue backs
4277 	 * up in which case the top half of the kernel may backup
4278 	 * due to a lack of tx descriptors.
4279 	 */
4280 	if (sc->sc_isedma)
4281 		qi.tqi_qflags = HAL_TXQ_TXEOLINT_ENABLE |
4282 		    HAL_TXQ_TXOKINT_ENABLE;
4283 	else
4284 		qi.tqi_qflags = HAL_TXQ_TXEOLINT_ENABLE |
4285 		    HAL_TXQ_TXDESCINT_ENABLE;
4286 
4287 	qnum = ath_hal_setuptxqueue(ah, qtype, &qi);
4288 	if (qnum == -1) {
4289 		/*
4290 		 * NB: don't print a message, this happens
4291 		 * normally on parts with too few tx queues
4292 		 */
4293 		return NULL;
4294 	}
4295 	if (qnum >= N(sc->sc_txq)) {
4296 		device_printf(sc->sc_dev,
4297 			"hal qnum %u out of range, max %zu!\n",
4298 			qnum, N(sc->sc_txq));
4299 		ath_hal_releasetxqueue(ah, qnum);
4300 		return NULL;
4301 	}
4302 	if (!ATH_TXQ_SETUP(sc, qnum)) {
4303 		ath_txq_init(sc, &sc->sc_txq[qnum], qnum);
4304 		sc->sc_txqsetup |= 1<<qnum;
4305 	}
4306 	return &sc->sc_txq[qnum];
4307 #undef N
4308 }
4309 
4310 /*
4311  * Setup a hardware data transmit queue for the specified
4312  * access control.  The hal may not support all requested
4313  * queues in which case it will return a reference to a
4314  * previously setup queue.  We record the mapping from ac's
4315  * to h/w queues for use by ath_tx_start and also track
4316  * the set of h/w queues being used to optimize work in the
4317  * transmit interrupt handler and related routines.
4318  */
4319 static int
4320 ath_tx_setup(struct ath_softc *sc, int ac, int haltype)
4321 {
4322 #define	N(a)	(sizeof(a)/sizeof(a[0]))
4323 	struct ath_txq *txq;
4324 
4325 	if (ac >= N(sc->sc_ac2q)) {
4326 		device_printf(sc->sc_dev, "AC %u out of range, max %zu!\n",
4327 			ac, N(sc->sc_ac2q));
4328 		return 0;
4329 	}
4330 	txq = ath_txq_setup(sc, HAL_TX_QUEUE_DATA, haltype);
4331 	if (txq != NULL) {
4332 		txq->axq_ac = ac;
4333 		sc->sc_ac2q[ac] = txq;
4334 		return 1;
4335 	} else
4336 		return 0;
4337 #undef N
4338 }
4339 
4340 /*
4341  * Update WME parameters for a transmit queue.
4342  */
4343 static int
4344 ath_txq_update(struct ath_softc *sc, int ac)
4345 {
4346 #define	ATH_EXPONENT_TO_VALUE(v)	((1<<v)-1)
4347 #define	ATH_TXOP_TO_US(v)		(v<<5)
4348 	struct ifnet *ifp = sc->sc_ifp;
4349 	struct ieee80211com *ic = ifp->if_l2com;
4350 	struct ath_txq *txq = sc->sc_ac2q[ac];
4351 	struct wmeParams *wmep = &ic->ic_wme.wme_chanParams.cap_wmeParams[ac];
4352 	struct ath_hal *ah = sc->sc_ah;
4353 	HAL_TXQ_INFO qi;
4354 
4355 	ath_hal_gettxqueueprops(ah, txq->axq_qnum, &qi);
4356 #ifdef IEEE80211_SUPPORT_TDMA
4357 	if (sc->sc_tdma) {
4358 		/*
4359 		 * AIFS is zero so there's no pre-transmit wait.  The
4360 		 * burst time defines the slot duration and is configured
4361 		 * through net80211.  The QCU is setup to not do post-xmit
4362 		 * back off, lockout all lower-priority QCU's, and fire
4363 		 * off the DMA beacon alert timer which is setup based
4364 		 * on the slot configuration.
4365 		 */
4366 		qi.tqi_qflags = HAL_TXQ_TXOKINT_ENABLE
4367 			      | HAL_TXQ_TXERRINT_ENABLE
4368 			      | HAL_TXQ_TXURNINT_ENABLE
4369 			      | HAL_TXQ_TXEOLINT_ENABLE
4370 			      | HAL_TXQ_DBA_GATED
4371 			      | HAL_TXQ_BACKOFF_DISABLE
4372 			      | HAL_TXQ_ARB_LOCKOUT_GLOBAL
4373 			      ;
4374 		qi.tqi_aifs = 0;
4375 		/* XXX +dbaprep? */
4376 		qi.tqi_readyTime = sc->sc_tdmaslotlen;
4377 		qi.tqi_burstTime = qi.tqi_readyTime;
4378 	} else {
4379 #endif
4380 		/*
4381 		 * XXX shouldn't this just use the default flags
4382 		 * used in the previous queue setup?
4383 		 */
4384 		qi.tqi_qflags = HAL_TXQ_TXOKINT_ENABLE
4385 			      | HAL_TXQ_TXERRINT_ENABLE
4386 			      | HAL_TXQ_TXDESCINT_ENABLE
4387 			      | HAL_TXQ_TXURNINT_ENABLE
4388 			      | HAL_TXQ_TXEOLINT_ENABLE
4389 			      ;
4390 		qi.tqi_aifs = wmep->wmep_aifsn;
4391 		qi.tqi_cwmin = ATH_EXPONENT_TO_VALUE(wmep->wmep_logcwmin);
4392 		qi.tqi_cwmax = ATH_EXPONENT_TO_VALUE(wmep->wmep_logcwmax);
4393 		qi.tqi_readyTime = 0;
4394 		qi.tqi_burstTime = ATH_TXOP_TO_US(wmep->wmep_txopLimit);
4395 #ifdef IEEE80211_SUPPORT_TDMA
4396 	}
4397 #endif
4398 
4399 	DPRINTF(sc, ATH_DEBUG_RESET,
4400 	    "%s: Q%u qflags 0x%x aifs %u cwmin %u cwmax %u burstTime %u\n",
4401 	    __func__, txq->axq_qnum, qi.tqi_qflags,
4402 	    qi.tqi_aifs, qi.tqi_cwmin, qi.tqi_cwmax, qi.tqi_burstTime);
4403 
4404 	if (!ath_hal_settxqueueprops(ah, txq->axq_qnum, &qi)) {
4405 		device_printf(sc->sc_dev, "unable to update hardware queue "
4406 		    "parameters for %s traffic!\n", ieee80211_wme_acnames[ac]);
4407 		return 0;
4408 	} else {
4409 		ath_hal_resettxqueue(ah, txq->axq_qnum); /* push to h/w */
4410 		return 1;
4411 	}
4412 #undef ATH_TXOP_TO_US
4413 #undef ATH_EXPONENT_TO_VALUE
4414 }
4415 
4416 /*
4417  * Callback from the 802.11 layer to update WME parameters.
4418  */
4419 int
4420 ath_wme_update(struct ieee80211com *ic)
4421 {
4422 	struct ath_softc *sc = ic->ic_ifp->if_softc;
4423 
4424 	return !ath_txq_update(sc, WME_AC_BE) ||
4425 	    !ath_txq_update(sc, WME_AC_BK) ||
4426 	    !ath_txq_update(sc, WME_AC_VI) ||
4427 	    !ath_txq_update(sc, WME_AC_VO) ? EIO : 0;
4428 }
4429 
4430 /*
4431  * Reclaim resources for a setup queue.
4432  */
4433 static void
4434 ath_tx_cleanupq(struct ath_softc *sc, struct ath_txq *txq)
4435 {
4436 
4437 	ath_hal_releasetxqueue(sc->sc_ah, txq->axq_qnum);
4438 	sc->sc_txqsetup &= ~(1<<txq->axq_qnum);
4439 	ATH_TXQ_LOCK_DESTROY(txq);
4440 }
4441 
4442 /*
4443  * Reclaim all tx queue resources.
4444  */
4445 static void
4446 ath_tx_cleanup(struct ath_softc *sc)
4447 {
4448 	int i;
4449 
4450 	ATH_TXBUF_LOCK_DESTROY(sc);
4451 	for (i = 0; i < HAL_NUM_TX_QUEUES; i++)
4452 		if (ATH_TXQ_SETUP(sc, i))
4453 			ath_tx_cleanupq(sc, &sc->sc_txq[i]);
4454 }
4455 
4456 /*
4457  * Return h/w rate index for an IEEE rate (w/o basic rate bit)
4458  * using the current rates in sc_rixmap.
4459  */
4460 int
4461 ath_tx_findrix(const struct ath_softc *sc, uint8_t rate)
4462 {
4463 	int rix = sc->sc_rixmap[rate];
4464 	/* NB: return lowest rix for invalid rate */
4465 	return (rix == 0xff ? 0 : rix);
4466 }
4467 
4468 static void
4469 ath_tx_update_stats(struct ath_softc *sc, struct ath_tx_status *ts,
4470     struct ath_buf *bf)
4471 {
4472 	struct ieee80211_node *ni = bf->bf_node;
4473 	struct ifnet *ifp = sc->sc_ifp;
4474 	struct ieee80211com *ic = ifp->if_l2com;
4475 	int sr, lr, pri;
4476 
4477 	if (ts->ts_status == 0) {
4478 		u_int8_t txant = ts->ts_antenna;
4479 		sc->sc_stats.ast_ant_tx[txant]++;
4480 		sc->sc_ant_tx[txant]++;
4481 		if (ts->ts_finaltsi != 0)
4482 			sc->sc_stats.ast_tx_altrate++;
4483 		pri = M_WME_GETAC(bf->bf_m);
4484 		if (pri >= WME_AC_VO)
4485 			ic->ic_wme.wme_hipri_traffic++;
4486 		if ((bf->bf_state.bfs_txflags & HAL_TXDESC_NOACK) == 0)
4487 			ni->ni_inact = ni->ni_inact_reload;
4488 	} else {
4489 		if (ts->ts_status & HAL_TXERR_XRETRY)
4490 			sc->sc_stats.ast_tx_xretries++;
4491 		if (ts->ts_status & HAL_TXERR_FIFO)
4492 			sc->sc_stats.ast_tx_fifoerr++;
4493 		if (ts->ts_status & HAL_TXERR_FILT)
4494 			sc->sc_stats.ast_tx_filtered++;
4495 		if (ts->ts_status & HAL_TXERR_XTXOP)
4496 			sc->sc_stats.ast_tx_xtxop++;
4497 		if (ts->ts_status & HAL_TXERR_TIMER_EXPIRED)
4498 			sc->sc_stats.ast_tx_timerexpired++;
4499 
4500 		if (bf->bf_m->m_flags & M_FF)
4501 			sc->sc_stats.ast_ff_txerr++;
4502 	}
4503 	/* XXX when is this valid? */
4504 	if (ts->ts_flags & HAL_TX_DESC_CFG_ERR)
4505 		sc->sc_stats.ast_tx_desccfgerr++;
4506 	/*
4507 	 * This can be valid for successful frame transmission!
4508 	 * If there's a TX FIFO underrun during aggregate transmission,
4509 	 * the MAC will pad the rest of the aggregate with delimiters.
4510 	 * If a BA is returned, the frame is marked as "OK" and it's up
4511 	 * to the TX completion code to notice which frames weren't
4512 	 * successfully transmitted.
4513 	 */
4514 	if (ts->ts_flags & HAL_TX_DATA_UNDERRUN)
4515 		sc->sc_stats.ast_tx_data_underrun++;
4516 	if (ts->ts_flags & HAL_TX_DELIM_UNDERRUN)
4517 		sc->sc_stats.ast_tx_delim_underrun++;
4518 
4519 	sr = ts->ts_shortretry;
4520 	lr = ts->ts_longretry;
4521 	sc->sc_stats.ast_tx_shortretry += sr;
4522 	sc->sc_stats.ast_tx_longretry += lr;
4523 
4524 }
4525 
4526 /*
4527  * The default completion. If fail is 1, this means
4528  * "please don't retry the frame, and just return -1 status
4529  * to the net80211 stack.
4530  */
4531 void
4532 ath_tx_default_comp(struct ath_softc *sc, struct ath_buf *bf, int fail)
4533 {
4534 	struct ath_tx_status *ts = &bf->bf_status.ds_txstat;
4535 	int st;
4536 
4537 	if (fail == 1)
4538 		st = -1;
4539 	else
4540 		st = ((bf->bf_state.bfs_txflags & HAL_TXDESC_NOACK) == 0) ?
4541 		    ts->ts_status : HAL_TXERR_XRETRY;
4542 
4543 #if 0
4544 	if (bf->bf_state.bfs_dobaw)
4545 		device_printf(sc->sc_dev,
4546 		    "%s: bf %p: seqno %d: dobaw should've been cleared!\n",
4547 		    __func__,
4548 		    bf,
4549 		    SEQNO(bf->bf_state.bfs_seqno));
4550 #endif
4551 	if (bf->bf_next != NULL)
4552 		device_printf(sc->sc_dev,
4553 		    "%s: bf %p: seqno %d: bf_next not NULL!\n",
4554 		    __func__,
4555 		    bf,
4556 		    SEQNO(bf->bf_state.bfs_seqno));
4557 
4558 	/*
4559 	 * Check if the node software queue is empty; if so
4560 	 * then clear the TIM.
4561 	 *
4562 	 * This needs to be done before the buffer is freed as
4563 	 * otherwise the node reference will have been released
4564 	 * and the node may not actually exist any longer.
4565 	 *
4566 	 * XXX I don't like this belonging here, but it's cleaner
4567 	 * to do it here right now then all the other places
4568 	 * where ath_tx_default_comp() is called.
4569 	 *
4570 	 * XXX TODO: during drain, ensure that the callback is
4571 	 * being called so we get a chance to update the TIM.
4572 	 */
4573 	if (bf->bf_node) {
4574 		ATH_TX_LOCK(sc);
4575 		ath_tx_update_tim(sc, bf->bf_node, 0);
4576 		ATH_TX_UNLOCK(sc);
4577 	}
4578 
4579 	/*
4580 	 * Do any tx complete callback.  Note this must
4581 	 * be done before releasing the node reference.
4582 	 * This will free the mbuf, release the net80211
4583 	 * node and recycle the ath_buf.
4584 	 */
4585 	ath_tx_freebuf(sc, bf, st);
4586 }
4587 
4588 /*
4589  * Update rate control with the given completion status.
4590  */
4591 void
4592 ath_tx_update_ratectrl(struct ath_softc *sc, struct ieee80211_node *ni,
4593     struct ath_rc_series *rc, struct ath_tx_status *ts, int frmlen,
4594     int nframes, int nbad)
4595 {
4596 	struct ath_node *an;
4597 
4598 	/* Only for unicast frames */
4599 	if (ni == NULL)
4600 		return;
4601 
4602 	an = ATH_NODE(ni);
4603 	ATH_NODE_UNLOCK_ASSERT(an);
4604 
4605 	if ((ts->ts_status & HAL_TXERR_FILT) == 0) {
4606 		ATH_NODE_LOCK(an);
4607 		ath_rate_tx_complete(sc, an, rc, ts, frmlen, nframes, nbad);
4608 		ATH_NODE_UNLOCK(an);
4609 	}
4610 }
4611 
4612 /*
4613  * Process the completion of the given buffer.
4614  *
4615  * This calls the rate control update and then the buffer completion.
4616  * This will either free the buffer or requeue it.  In any case, the
4617  * bf pointer should be treated as invalid after this function is called.
4618  */
4619 void
4620 ath_tx_process_buf_completion(struct ath_softc *sc, struct ath_txq *txq,
4621     struct ath_tx_status *ts, struct ath_buf *bf)
4622 {
4623 	struct ieee80211_node *ni = bf->bf_node;
4624 
4625 	ATH_TX_UNLOCK_ASSERT(sc);
4626 	ATH_TXQ_UNLOCK_ASSERT(txq);
4627 
4628 	/* If unicast frame, update general statistics */
4629 	if (ni != NULL) {
4630 		/* update statistics */
4631 		ath_tx_update_stats(sc, ts, bf);
4632 	}
4633 
4634 	/*
4635 	 * Call the completion handler.
4636 	 * The completion handler is responsible for
4637 	 * calling the rate control code.
4638 	 *
4639 	 * Frames with no completion handler get the
4640 	 * rate control code called here.
4641 	 */
4642 	if (bf->bf_comp == NULL) {
4643 		if ((ts->ts_status & HAL_TXERR_FILT) == 0 &&
4644 		    (bf->bf_state.bfs_txflags & HAL_TXDESC_NOACK) == 0) {
4645 			/*
4646 			 * XXX assume this isn't an aggregate
4647 			 * frame.
4648 			 */
4649 			ath_tx_update_ratectrl(sc, ni,
4650 			     bf->bf_state.bfs_rc, ts,
4651 			    bf->bf_state.bfs_pktlen, 1,
4652 			    (ts->ts_status == 0 ? 0 : 1));
4653 		}
4654 		ath_tx_default_comp(sc, bf, 0);
4655 	} else
4656 		bf->bf_comp(sc, bf, 0);
4657 }
4658 
4659 
4660 
4661 /*
4662  * Process completed xmit descriptors from the specified queue.
4663  * Kick the packet scheduler if needed. This can occur from this
4664  * particular task.
4665  */
4666 static int
4667 ath_tx_processq(struct ath_softc *sc, struct ath_txq *txq, int dosched)
4668 {
4669 	struct ath_hal *ah = sc->sc_ah;
4670 	struct ath_buf *bf;
4671 	struct ath_desc *ds;
4672 	struct ath_tx_status *ts;
4673 	struct ieee80211_node *ni;
4674 #ifdef	IEEE80211_SUPPORT_SUPERG
4675 	struct ieee80211com *ic = sc->sc_ifp->if_l2com;
4676 #endif	/* IEEE80211_SUPPORT_SUPERG */
4677 	int nacked;
4678 	HAL_STATUS status;
4679 
4680 	DPRINTF(sc, ATH_DEBUG_TX_PROC, "%s: tx queue %u head %p link %p\n",
4681 		__func__, txq->axq_qnum,
4682 		(caddr_t)(uintptr_t) ath_hal_gettxbuf(sc->sc_ah, txq->axq_qnum),
4683 		txq->axq_link);
4684 
4685 	ATH_KTR(sc, ATH_KTR_TXCOMP, 4,
4686 	    "ath_tx_processq: txq=%u head %p link %p depth %p",
4687 	    txq->axq_qnum,
4688 	    (caddr_t)(uintptr_t) ath_hal_gettxbuf(sc->sc_ah, txq->axq_qnum),
4689 	    txq->axq_link,
4690 	    txq->axq_depth);
4691 
4692 	nacked = 0;
4693 	for (;;) {
4694 		ATH_TXQ_LOCK(txq);
4695 		txq->axq_intrcnt = 0;	/* reset periodic desc intr count */
4696 		bf = TAILQ_FIRST(&txq->axq_q);
4697 		if (bf == NULL) {
4698 			ATH_TXQ_UNLOCK(txq);
4699 			break;
4700 		}
4701 		ds = bf->bf_lastds;	/* XXX must be setup correctly! */
4702 		ts = &bf->bf_status.ds_txstat;
4703 
4704 		status = ath_hal_txprocdesc(ah, ds, ts);
4705 #ifdef ATH_DEBUG
4706 		if (sc->sc_debug & ATH_DEBUG_XMIT_DESC)
4707 			ath_printtxbuf(sc, bf, txq->axq_qnum, 0,
4708 			    status == HAL_OK);
4709 		else if ((sc->sc_debug & ATH_DEBUG_RESET) && (dosched == 0))
4710 			ath_printtxbuf(sc, bf, txq->axq_qnum, 0,
4711 			    status == HAL_OK);
4712 #endif
4713 #ifdef	ATH_DEBUG_ALQ
4714 		if (if_ath_alq_checkdebug(&sc->sc_alq,
4715 		    ATH_ALQ_EDMA_TXSTATUS)) {
4716 			if_ath_alq_post(&sc->sc_alq, ATH_ALQ_EDMA_TXSTATUS,
4717 			sc->sc_tx_statuslen,
4718 			(char *) ds);
4719 		}
4720 #endif
4721 
4722 		if (status == HAL_EINPROGRESS) {
4723 			ATH_KTR(sc, ATH_KTR_TXCOMP, 3,
4724 			    "ath_tx_processq: txq=%u, bf=%p ds=%p, HAL_EINPROGRESS",
4725 			    txq->axq_qnum, bf, ds);
4726 			ATH_TXQ_UNLOCK(txq);
4727 			break;
4728 		}
4729 		ATH_TXQ_REMOVE(txq, bf, bf_list);
4730 
4731 		/*
4732 		 * Sanity check.
4733 		 */
4734 		if (txq->axq_qnum != bf->bf_state.bfs_tx_queue) {
4735 			device_printf(sc->sc_dev,
4736 			    "%s: TXQ=%d: bf=%p, bfs_tx_queue=%d\n",
4737 			    __func__,
4738 			    txq->axq_qnum,
4739 			    bf,
4740 			    bf->bf_state.bfs_tx_queue);
4741 		}
4742 		if (txq->axq_qnum != bf->bf_last->bf_state.bfs_tx_queue) {
4743 			device_printf(sc->sc_dev,
4744 			    "%s: TXQ=%d: bf_last=%p, bfs_tx_queue=%d\n",
4745 			    __func__,
4746 			    txq->axq_qnum,
4747 			    bf->bf_last,
4748 			    bf->bf_last->bf_state.bfs_tx_queue);
4749 		}
4750 
4751 #if 0
4752 		if (txq->axq_depth > 0) {
4753 			/*
4754 			 * More frames follow.  Mark the buffer busy
4755 			 * so it's not re-used while the hardware may
4756 			 * still re-read the link field in the descriptor.
4757 			 *
4758 			 * Use the last buffer in an aggregate as that
4759 			 * is where the hardware may be - intermediate
4760 			 * descriptors won't be "busy".
4761 			 */
4762 			bf->bf_last->bf_flags |= ATH_BUF_BUSY;
4763 		} else
4764 			txq->axq_link = NULL;
4765 #else
4766 		bf->bf_last->bf_flags |= ATH_BUF_BUSY;
4767 #endif
4768 		if (bf->bf_state.bfs_aggr)
4769 			txq->axq_aggr_depth--;
4770 
4771 		ni = bf->bf_node;
4772 
4773 		ATH_KTR(sc, ATH_KTR_TXCOMP, 5,
4774 		    "ath_tx_processq: txq=%u, bf=%p, ds=%p, ni=%p, ts_status=0x%08x",
4775 		    txq->axq_qnum, bf, ds, ni, ts->ts_status);
4776 		/*
4777 		 * If unicast frame was ack'd update RSSI,
4778 		 * including the last rx time used to
4779 		 * workaround phantom bmiss interrupts.
4780 		 */
4781 		if (ni != NULL && ts->ts_status == 0 &&
4782 		    ((bf->bf_state.bfs_txflags & HAL_TXDESC_NOACK) == 0)) {
4783 			nacked++;
4784 			sc->sc_stats.ast_tx_rssi = ts->ts_rssi;
4785 			ATH_RSSI_LPF(sc->sc_halstats.ns_avgtxrssi,
4786 				ts->ts_rssi);
4787 		}
4788 		ATH_TXQ_UNLOCK(txq);
4789 
4790 		/*
4791 		 * Update statistics and call completion
4792 		 */
4793 		ath_tx_process_buf_completion(sc, txq, ts, bf);
4794 
4795 		/* XXX at this point, bf and ni may be totally invalid */
4796 	}
4797 #ifdef IEEE80211_SUPPORT_SUPERG
4798 	/*
4799 	 * Flush fast-frame staging queue when traffic slows.
4800 	 */
4801 	if (txq->axq_depth <= 1)
4802 		ieee80211_ff_flush(ic, txq->axq_ac);
4803 #endif
4804 
4805 	/* Kick the software TXQ scheduler */
4806 	if (dosched) {
4807 		ATH_TX_LOCK(sc);
4808 		ath_txq_sched(sc, txq);
4809 		ATH_TX_UNLOCK(sc);
4810 	}
4811 
4812 	ATH_KTR(sc, ATH_KTR_TXCOMP, 1,
4813 	    "ath_tx_processq: txq=%u: done",
4814 	    txq->axq_qnum);
4815 
4816 	return nacked;
4817 }
4818 
4819 #define	TXQACTIVE(t, q)		( (t) & (1 << (q)))
4820 
4821 /*
4822  * Deferred processing of transmit interrupt; special-cased
4823  * for a single hardware transmit queue (e.g. 5210 and 5211).
4824  */
4825 static void
4826 ath_tx_proc_q0(void *arg, int npending)
4827 {
4828 	struct ath_softc *sc = arg;
4829 	struct ifnet *ifp = sc->sc_ifp;
4830 	uint32_t txqs;
4831 
4832 	ATH_PCU_LOCK(sc);
4833 	sc->sc_txproc_cnt++;
4834 	txqs = sc->sc_txq_active;
4835 	sc->sc_txq_active &= ~txqs;
4836 	ATH_PCU_UNLOCK(sc);
4837 
4838 	ATH_LOCK(sc);
4839 	ath_power_set_power_state(sc, HAL_PM_AWAKE);
4840 	ATH_UNLOCK(sc);
4841 
4842 	ATH_KTR(sc, ATH_KTR_TXCOMP, 1,
4843 	    "ath_tx_proc_q0: txqs=0x%08x", txqs);
4844 
4845 	if (TXQACTIVE(txqs, 0) && ath_tx_processq(sc, &sc->sc_txq[0], 1))
4846 		/* XXX why is lastrx updated in tx code? */
4847 		sc->sc_lastrx = ath_hal_gettsf64(sc->sc_ah);
4848 	if (TXQACTIVE(txqs, sc->sc_cabq->axq_qnum))
4849 		ath_tx_processq(sc, sc->sc_cabq, 1);
4850 	IF_LOCK(&ifp->if_snd);
4851 	ifp->if_drv_flags &= ~IFF_DRV_OACTIVE;
4852 	IF_UNLOCK(&ifp->if_snd);
4853 	sc->sc_wd_timer = 0;
4854 
4855 	if (sc->sc_softled)
4856 		ath_led_event(sc, sc->sc_txrix);
4857 
4858 	ATH_PCU_LOCK(sc);
4859 	sc->sc_txproc_cnt--;
4860 	ATH_PCU_UNLOCK(sc);
4861 
4862 	ATH_LOCK(sc);
4863 	ath_power_restore_power_state(sc);
4864 	ATH_UNLOCK(sc);
4865 
4866 	ath_tx_kick(sc);
4867 }
4868 
4869 /*
4870  * Deferred processing of transmit interrupt; special-cased
4871  * for four hardware queues, 0-3 (e.g. 5212 w/ WME support).
4872  */
4873 static void
4874 ath_tx_proc_q0123(void *arg, int npending)
4875 {
4876 	struct ath_softc *sc = arg;
4877 	struct ifnet *ifp = sc->sc_ifp;
4878 	int nacked;
4879 	uint32_t txqs;
4880 
4881 	ATH_PCU_LOCK(sc);
4882 	sc->sc_txproc_cnt++;
4883 	txqs = sc->sc_txq_active;
4884 	sc->sc_txq_active &= ~txqs;
4885 	ATH_PCU_UNLOCK(sc);
4886 
4887 	ATH_LOCK(sc);
4888 	ath_power_set_power_state(sc, HAL_PM_AWAKE);
4889 	ATH_UNLOCK(sc);
4890 
4891 	ATH_KTR(sc, ATH_KTR_TXCOMP, 1,
4892 	    "ath_tx_proc_q0123: txqs=0x%08x", txqs);
4893 
4894 	/*
4895 	 * Process each active queue.
4896 	 */
4897 	nacked = 0;
4898 	if (TXQACTIVE(txqs, 0))
4899 		nacked += ath_tx_processq(sc, &sc->sc_txq[0], 1);
4900 	if (TXQACTIVE(txqs, 1))
4901 		nacked += ath_tx_processq(sc, &sc->sc_txq[1], 1);
4902 	if (TXQACTIVE(txqs, 2))
4903 		nacked += ath_tx_processq(sc, &sc->sc_txq[2], 1);
4904 	if (TXQACTIVE(txqs, 3))
4905 		nacked += ath_tx_processq(sc, &sc->sc_txq[3], 1);
4906 	if (TXQACTIVE(txqs, sc->sc_cabq->axq_qnum))
4907 		ath_tx_processq(sc, sc->sc_cabq, 1);
4908 	if (nacked)
4909 		sc->sc_lastrx = ath_hal_gettsf64(sc->sc_ah);
4910 
4911 	IF_LOCK(&ifp->if_snd);
4912 	ifp->if_drv_flags &= ~IFF_DRV_OACTIVE;
4913 	IF_UNLOCK(&ifp->if_snd);
4914 	sc->sc_wd_timer = 0;
4915 
4916 	if (sc->sc_softled)
4917 		ath_led_event(sc, sc->sc_txrix);
4918 
4919 	ATH_PCU_LOCK(sc);
4920 	sc->sc_txproc_cnt--;
4921 	ATH_PCU_UNLOCK(sc);
4922 
4923 	ATH_LOCK(sc);
4924 	ath_power_restore_power_state(sc);
4925 	ATH_UNLOCK(sc);
4926 
4927 	ath_tx_kick(sc);
4928 }
4929 
4930 /*
4931  * Deferred processing of transmit interrupt.
4932  */
4933 static void
4934 ath_tx_proc(void *arg, int npending)
4935 {
4936 	struct ath_softc *sc = arg;
4937 	struct ifnet *ifp = sc->sc_ifp;
4938 	int i, nacked;
4939 	uint32_t txqs;
4940 
4941 	ATH_PCU_LOCK(sc);
4942 	sc->sc_txproc_cnt++;
4943 	txqs = sc->sc_txq_active;
4944 	sc->sc_txq_active &= ~txqs;
4945 	ATH_PCU_UNLOCK(sc);
4946 
4947 	ATH_LOCK(sc);
4948 	ath_power_set_power_state(sc, HAL_PM_AWAKE);
4949 	ATH_UNLOCK(sc);
4950 
4951 	ATH_KTR(sc, ATH_KTR_TXCOMP, 1, "ath_tx_proc: txqs=0x%08x", txqs);
4952 
4953 	/*
4954 	 * Process each active queue.
4955 	 */
4956 	nacked = 0;
4957 	for (i = 0; i < HAL_NUM_TX_QUEUES; i++)
4958 		if (ATH_TXQ_SETUP(sc, i) && TXQACTIVE(txqs, i))
4959 			nacked += ath_tx_processq(sc, &sc->sc_txq[i], 1);
4960 	if (nacked)
4961 		sc->sc_lastrx = ath_hal_gettsf64(sc->sc_ah);
4962 
4963 	/* XXX check this inside of IF_LOCK? */
4964 	IF_LOCK(&ifp->if_snd);
4965 	ifp->if_drv_flags &= ~IFF_DRV_OACTIVE;
4966 	IF_UNLOCK(&ifp->if_snd);
4967 	sc->sc_wd_timer = 0;
4968 
4969 	if (sc->sc_softled)
4970 		ath_led_event(sc, sc->sc_txrix);
4971 
4972 	ATH_PCU_LOCK(sc);
4973 	sc->sc_txproc_cnt--;
4974 	ATH_PCU_UNLOCK(sc);
4975 
4976 	ATH_LOCK(sc);
4977 	ath_power_restore_power_state(sc);
4978 	ATH_UNLOCK(sc);
4979 
4980 	ath_tx_kick(sc);
4981 }
4982 #undef	TXQACTIVE
4983 
4984 /*
4985  * Deferred processing of TXQ rescheduling.
4986  */
4987 static void
4988 ath_txq_sched_tasklet(void *arg, int npending)
4989 {
4990 	struct ath_softc *sc = arg;
4991 	int i;
4992 
4993 	/* XXX is skipping ok? */
4994 	ATH_PCU_LOCK(sc);
4995 #if 0
4996 	if (sc->sc_inreset_cnt > 0) {
4997 		device_printf(sc->sc_dev,
4998 		    "%s: sc_inreset_cnt > 0; skipping\n", __func__);
4999 		ATH_PCU_UNLOCK(sc);
5000 		return;
5001 	}
5002 #endif
5003 	sc->sc_txproc_cnt++;
5004 	ATH_PCU_UNLOCK(sc);
5005 
5006 	ATH_LOCK(sc);
5007 	ath_power_set_power_state(sc, HAL_PM_AWAKE);
5008 	ATH_UNLOCK(sc);
5009 
5010 	ATH_TX_LOCK(sc);
5011 	for (i = 0; i < HAL_NUM_TX_QUEUES; i++) {
5012 		if (ATH_TXQ_SETUP(sc, i)) {
5013 			ath_txq_sched(sc, &sc->sc_txq[i]);
5014 		}
5015 	}
5016 	ATH_TX_UNLOCK(sc);
5017 
5018 	ATH_LOCK(sc);
5019 	ath_power_restore_power_state(sc);
5020 	ATH_UNLOCK(sc);
5021 
5022 	ATH_PCU_LOCK(sc);
5023 	sc->sc_txproc_cnt--;
5024 	ATH_PCU_UNLOCK(sc);
5025 }
5026 
5027 void
5028 ath_returnbuf_tail(struct ath_softc *sc, struct ath_buf *bf)
5029 {
5030 
5031 	ATH_TXBUF_LOCK_ASSERT(sc);
5032 
5033 	if (bf->bf_flags & ATH_BUF_MGMT)
5034 		TAILQ_INSERT_TAIL(&sc->sc_txbuf_mgmt, bf, bf_list);
5035 	else {
5036 		TAILQ_INSERT_TAIL(&sc->sc_txbuf, bf, bf_list);
5037 		sc->sc_txbuf_cnt++;
5038 		if (sc->sc_txbuf_cnt > ath_txbuf) {
5039 			device_printf(sc->sc_dev,
5040 			    "%s: sc_txbuf_cnt > %d?\n",
5041 			    __func__,
5042 			    ath_txbuf);
5043 			sc->sc_txbuf_cnt = ath_txbuf;
5044 		}
5045 	}
5046 }
5047 
5048 void
5049 ath_returnbuf_head(struct ath_softc *sc, struct ath_buf *bf)
5050 {
5051 
5052 	ATH_TXBUF_LOCK_ASSERT(sc);
5053 
5054 	if (bf->bf_flags & ATH_BUF_MGMT)
5055 		TAILQ_INSERT_HEAD(&sc->sc_txbuf_mgmt, bf, bf_list);
5056 	else {
5057 		TAILQ_INSERT_HEAD(&sc->sc_txbuf, bf, bf_list);
5058 		sc->sc_txbuf_cnt++;
5059 		if (sc->sc_txbuf_cnt > ATH_TXBUF) {
5060 			device_printf(sc->sc_dev,
5061 			    "%s: sc_txbuf_cnt > %d?\n",
5062 			    __func__,
5063 			    ATH_TXBUF);
5064 			sc->sc_txbuf_cnt = ATH_TXBUF;
5065 		}
5066 	}
5067 }
5068 
5069 /*
5070  * Free the holding buffer if it exists
5071  */
5072 void
5073 ath_txq_freeholdingbuf(struct ath_softc *sc, struct ath_txq *txq)
5074 {
5075 	ATH_TXBUF_UNLOCK_ASSERT(sc);
5076 	ATH_TXQ_LOCK_ASSERT(txq);
5077 
5078 	if (txq->axq_holdingbf == NULL)
5079 		return;
5080 
5081 	txq->axq_holdingbf->bf_flags &= ~ATH_BUF_BUSY;
5082 
5083 	ATH_TXBUF_LOCK(sc);
5084 	ath_returnbuf_tail(sc, txq->axq_holdingbf);
5085 	ATH_TXBUF_UNLOCK(sc);
5086 
5087 	txq->axq_holdingbf = NULL;
5088 }
5089 
5090 /*
5091  * Add this buffer to the holding queue, freeing the previous
5092  * one if it exists.
5093  */
5094 static void
5095 ath_txq_addholdingbuf(struct ath_softc *sc, struct ath_buf *bf)
5096 {
5097 	struct ath_txq *txq;
5098 
5099 	txq = &sc->sc_txq[bf->bf_state.bfs_tx_queue];
5100 
5101 	ATH_TXBUF_UNLOCK_ASSERT(sc);
5102 	ATH_TXQ_LOCK_ASSERT(txq);
5103 
5104 	/* XXX assert ATH_BUF_BUSY is set */
5105 
5106 	/* XXX assert the tx queue is under the max number */
5107 	if (bf->bf_state.bfs_tx_queue > HAL_NUM_TX_QUEUES) {
5108 		device_printf(sc->sc_dev, "%s: bf=%p: invalid tx queue (%d)\n",
5109 		    __func__,
5110 		    bf,
5111 		    bf->bf_state.bfs_tx_queue);
5112 		bf->bf_flags &= ~ATH_BUF_BUSY;
5113 		ath_returnbuf_tail(sc, bf);
5114 		return;
5115 	}
5116 	ath_txq_freeholdingbuf(sc, txq);
5117 	txq->axq_holdingbf = bf;
5118 }
5119 
5120 /*
5121  * Return a buffer to the pool and update the 'busy' flag on the
5122  * previous 'tail' entry.
5123  *
5124  * This _must_ only be called when the buffer is involved in a completed
5125  * TX. The logic is that if it was part of an active TX, the previous
5126  * buffer on the list is now not involved in a halted TX DMA queue, waiting
5127  * for restart (eg for TDMA.)
5128  *
5129  * The caller must free the mbuf and recycle the node reference.
5130  *
5131  * XXX This method of handling busy / holding buffers is insanely stupid.
5132  * It requires bf_state.bfs_tx_queue to be correctly assigned.  It would
5133  * be much nicer if buffers in the processq() methods would instead be
5134  * always completed there (pushed onto a txq or ath_bufhead) so we knew
5135  * exactly what hardware queue they came from in the first place.
5136  */
5137 void
5138 ath_freebuf(struct ath_softc *sc, struct ath_buf *bf)
5139 {
5140 	struct ath_txq *txq;
5141 
5142 	txq = &sc->sc_txq[bf->bf_state.bfs_tx_queue];
5143 
5144 	KASSERT((bf->bf_node == NULL), ("%s: bf->bf_node != NULL\n", __func__));
5145 	KASSERT((bf->bf_m == NULL), ("%s: bf->bf_m != NULL\n", __func__));
5146 
5147 	/*
5148 	 * If this buffer is busy, push it onto the holding queue.
5149 	 */
5150 	if (bf->bf_flags & ATH_BUF_BUSY) {
5151 		ATH_TXQ_LOCK(txq);
5152 		ath_txq_addholdingbuf(sc, bf);
5153 		ATH_TXQ_UNLOCK(txq);
5154 		return;
5155 	}
5156 
5157 	/*
5158 	 * Not a busy buffer, so free normally
5159 	 */
5160 	ATH_TXBUF_LOCK(sc);
5161 	ath_returnbuf_tail(sc, bf);
5162 	ATH_TXBUF_UNLOCK(sc);
5163 }
5164 
5165 /*
5166  * This is currently used by ath_tx_draintxq() and
5167  * ath_tx_tid_free_pkts().
5168  *
5169  * It recycles a single ath_buf.
5170  */
5171 void
5172 ath_tx_freebuf(struct ath_softc *sc, struct ath_buf *bf, int status)
5173 {
5174 	struct ieee80211_node *ni = bf->bf_node;
5175 	struct mbuf *m0 = bf->bf_m;
5176 
5177 	/*
5178 	 * Make sure that we only sync/unload if there's an mbuf.
5179 	 * If not (eg we cloned a buffer), the unload will have already
5180 	 * occured.
5181 	 */
5182 	if (bf->bf_m != NULL) {
5183 		bus_dmamap_sync(sc->sc_dmat, bf->bf_dmamap,
5184 		    BUS_DMASYNC_POSTWRITE);
5185 		bus_dmamap_unload(sc->sc_dmat, bf->bf_dmamap);
5186 	}
5187 
5188 	bf->bf_node = NULL;
5189 	bf->bf_m = NULL;
5190 
5191 	/* Free the buffer, it's not needed any longer */
5192 	ath_freebuf(sc, bf);
5193 
5194 	/* Pass the buffer back to net80211 - completing it */
5195 	ieee80211_tx_complete(ni, m0, status);
5196 }
5197 
5198 static struct ath_buf *
5199 ath_tx_draintxq_get_one(struct ath_softc *sc, struct ath_txq *txq)
5200 {
5201 	struct ath_buf *bf;
5202 
5203 	ATH_TXQ_LOCK_ASSERT(txq);
5204 
5205 	/*
5206 	 * Drain the FIFO queue first, then if it's
5207 	 * empty, move to the normal frame queue.
5208 	 */
5209 	bf = TAILQ_FIRST(&txq->fifo.axq_q);
5210 	if (bf != NULL) {
5211 		/*
5212 		 * Is it the last buffer in this set?
5213 		 * Decrement the FIFO counter.
5214 		 */
5215 		if (bf->bf_flags & ATH_BUF_FIFOEND) {
5216 			if (txq->axq_fifo_depth == 0) {
5217 				device_printf(sc->sc_dev,
5218 				    "%s: Q%d: fifo_depth=0, fifo.axq_depth=%d?\n",
5219 				    __func__,
5220 				    txq->axq_qnum,
5221 				    txq->fifo.axq_depth);
5222 			} else
5223 				txq->axq_fifo_depth--;
5224 		}
5225 		ATH_TXQ_REMOVE(&txq->fifo, bf, bf_list);
5226 		return (bf);
5227 	}
5228 
5229 	/*
5230 	 * Debugging!
5231 	 */
5232 	if (txq->axq_fifo_depth != 0 || txq->fifo.axq_depth != 0) {
5233 		device_printf(sc->sc_dev,
5234 		    "%s: Q%d: fifo_depth=%d, fifo.axq_depth=%d\n",
5235 		    __func__,
5236 		    txq->axq_qnum,
5237 		    txq->axq_fifo_depth,
5238 		    txq->fifo.axq_depth);
5239 	}
5240 
5241 	/*
5242 	 * Now drain the pending queue.
5243 	 */
5244 	bf = TAILQ_FIRST(&txq->axq_q);
5245 	if (bf == NULL) {
5246 		txq->axq_link = NULL;
5247 		return (NULL);
5248 	}
5249 	ATH_TXQ_REMOVE(txq, bf, bf_list);
5250 	return (bf);
5251 }
5252 
5253 void
5254 ath_tx_draintxq(struct ath_softc *sc, struct ath_txq *txq)
5255 {
5256 #ifdef ATH_DEBUG
5257 	struct ath_hal *ah = sc->sc_ah;
5258 #endif
5259 	struct ath_buf *bf;
5260 	u_int ix;
5261 
5262 	/*
5263 	 * NB: this assumes output has been stopped and
5264 	 *     we do not need to block ath_tx_proc
5265 	 */
5266 	for (ix = 0;; ix++) {
5267 		ATH_TXQ_LOCK(txq);
5268 		bf = ath_tx_draintxq_get_one(sc, txq);
5269 		if (bf == NULL) {
5270 			ATH_TXQ_UNLOCK(txq);
5271 			break;
5272 		}
5273 		if (bf->bf_state.bfs_aggr)
5274 			txq->axq_aggr_depth--;
5275 #ifdef ATH_DEBUG
5276 		if (sc->sc_debug & ATH_DEBUG_RESET) {
5277 			struct ieee80211com *ic = sc->sc_ifp->if_l2com;
5278 			int status = 0;
5279 
5280 			/*
5281 			 * EDMA operation has a TX completion FIFO
5282 			 * separate from the TX descriptor, so this
5283 			 * method of checking the "completion" status
5284 			 * is wrong.
5285 			 */
5286 			if (! sc->sc_isedma) {
5287 				status = (ath_hal_txprocdesc(ah,
5288 				    bf->bf_lastds,
5289 				    &bf->bf_status.ds_txstat) == HAL_OK);
5290 			}
5291 			ath_printtxbuf(sc, bf, txq->axq_qnum, ix, status);
5292 			ieee80211_dump_pkt(ic, mtod(bf->bf_m, const uint8_t *),
5293 			    bf->bf_m->m_len, 0, -1);
5294 		}
5295 #endif /* ATH_DEBUG */
5296 		/*
5297 		 * Since we're now doing magic in the completion
5298 		 * functions, we -must- call it for aggregation
5299 		 * destinations or BAW tracking will get upset.
5300 		 */
5301 		/*
5302 		 * Clear ATH_BUF_BUSY; the completion handler
5303 		 * will free the buffer.
5304 		 */
5305 		ATH_TXQ_UNLOCK(txq);
5306 		bf->bf_flags &= ~ATH_BUF_BUSY;
5307 		if (bf->bf_comp)
5308 			bf->bf_comp(sc, bf, 1);
5309 		else
5310 			ath_tx_default_comp(sc, bf, 1);
5311 	}
5312 
5313 	/*
5314 	 * Free the holding buffer if it exists
5315 	 */
5316 	ATH_TXQ_LOCK(txq);
5317 	ath_txq_freeholdingbuf(sc, txq);
5318 	ATH_TXQ_UNLOCK(txq);
5319 
5320 	/*
5321 	 * Drain software queued frames which are on
5322 	 * active TIDs.
5323 	 */
5324 	ath_tx_txq_drain(sc, txq);
5325 }
5326 
5327 static void
5328 ath_tx_stopdma(struct ath_softc *sc, struct ath_txq *txq)
5329 {
5330 	struct ath_hal *ah = sc->sc_ah;
5331 
5332 	ATH_TXQ_LOCK_ASSERT(txq);
5333 
5334 	DPRINTF(sc, ATH_DEBUG_RESET,
5335 	    "%s: tx queue [%u] %p, active=%d, hwpending=%d, flags 0x%08x, "
5336 	    "link %p, holdingbf=%p\n",
5337 	    __func__,
5338 	    txq->axq_qnum,
5339 	    (caddr_t)(uintptr_t) ath_hal_gettxbuf(ah, txq->axq_qnum),
5340 	    (int) (!! ath_hal_txqenabled(ah, txq->axq_qnum)),
5341 	    (int) ath_hal_numtxpending(ah, txq->axq_qnum),
5342 	    txq->axq_flags,
5343 	    txq->axq_link,
5344 	    txq->axq_holdingbf);
5345 
5346 	(void) ath_hal_stoptxdma(ah, txq->axq_qnum);
5347 	/* We've stopped TX DMA, so mark this as stopped. */
5348 	txq->axq_flags &= ~ATH_TXQ_PUTRUNNING;
5349 
5350 #ifdef	ATH_DEBUG
5351 	if ((sc->sc_debug & ATH_DEBUG_RESET)
5352 	    && (txq->axq_holdingbf != NULL)) {
5353 		ath_printtxbuf(sc, txq->axq_holdingbf, txq->axq_qnum, 0, 0);
5354 	}
5355 #endif
5356 }
5357 
5358 int
5359 ath_stoptxdma(struct ath_softc *sc)
5360 {
5361 	struct ath_hal *ah = sc->sc_ah;
5362 	int i;
5363 
5364 	/* XXX return value */
5365 	if (sc->sc_invalid)
5366 		return 0;
5367 
5368 	if (!sc->sc_invalid) {
5369 		/* don't touch the hardware if marked invalid */
5370 		DPRINTF(sc, ATH_DEBUG_RESET, "%s: tx queue [%u] %p, link %p\n",
5371 		    __func__, sc->sc_bhalq,
5372 		    (caddr_t)(uintptr_t) ath_hal_gettxbuf(ah, sc->sc_bhalq),
5373 		    NULL);
5374 
5375 		/* stop the beacon queue */
5376 		(void) ath_hal_stoptxdma(ah, sc->sc_bhalq);
5377 
5378 		/* Stop the data queues */
5379 		for (i = 0; i < HAL_NUM_TX_QUEUES; i++) {
5380 			if (ATH_TXQ_SETUP(sc, i)) {
5381 				ATH_TXQ_LOCK(&sc->sc_txq[i]);
5382 				ath_tx_stopdma(sc, &sc->sc_txq[i]);
5383 				ATH_TXQ_UNLOCK(&sc->sc_txq[i]);
5384 			}
5385 		}
5386 	}
5387 
5388 	return 1;
5389 }
5390 
5391 #ifdef	ATH_DEBUG
5392 void
5393 ath_tx_dump(struct ath_softc *sc, struct ath_txq *txq)
5394 {
5395 	struct ath_hal *ah = sc->sc_ah;
5396 	struct ath_buf *bf;
5397 	int i = 0;
5398 
5399 	if (! (sc->sc_debug & ATH_DEBUG_RESET))
5400 		return;
5401 
5402 	device_printf(sc->sc_dev, "%s: Q%d: begin\n",
5403 	    __func__, txq->axq_qnum);
5404 	TAILQ_FOREACH(bf, &txq->axq_q, bf_list) {
5405 		ath_printtxbuf(sc, bf, txq->axq_qnum, i,
5406 			ath_hal_txprocdesc(ah, bf->bf_lastds,
5407 			    &bf->bf_status.ds_txstat) == HAL_OK);
5408 		i++;
5409 	}
5410 	device_printf(sc->sc_dev, "%s: Q%d: end\n",
5411 	    __func__, txq->axq_qnum);
5412 }
5413 #endif /* ATH_DEBUG */
5414 
5415 /*
5416  * Drain the transmit queues and reclaim resources.
5417  */
5418 void
5419 ath_legacy_tx_drain(struct ath_softc *sc, ATH_RESET_TYPE reset_type)
5420 {
5421 	struct ath_hal *ah = sc->sc_ah;
5422 	struct ifnet *ifp = sc->sc_ifp;
5423 	int i;
5424 	struct ath_buf *bf_last;
5425 
5426 	(void) ath_stoptxdma(sc);
5427 
5428 	/*
5429 	 * Dump the queue contents
5430 	 */
5431 	for (i = 0; i < HAL_NUM_TX_QUEUES; i++) {
5432 		/*
5433 		 * XXX TODO: should we just handle the completed TX frames
5434 		 * here, whether or not the reset is a full one or not?
5435 		 */
5436 		if (ATH_TXQ_SETUP(sc, i)) {
5437 #ifdef	ATH_DEBUG
5438 			if (sc->sc_debug & ATH_DEBUG_RESET)
5439 				ath_tx_dump(sc, &sc->sc_txq[i]);
5440 #endif	/* ATH_DEBUG */
5441 			if (reset_type == ATH_RESET_NOLOSS) {
5442 				ath_tx_processq(sc, &sc->sc_txq[i], 0);
5443 				ATH_TXQ_LOCK(&sc->sc_txq[i]);
5444 				/*
5445 				 * Free the holding buffer; DMA is now
5446 				 * stopped.
5447 				 */
5448 				ath_txq_freeholdingbuf(sc, &sc->sc_txq[i]);
5449 				/*
5450 				 * Setup the link pointer to be the
5451 				 * _last_ buffer/descriptor in the list.
5452 				 * If there's nothing in the list, set it
5453 				 * to NULL.
5454 				 */
5455 				bf_last = ATH_TXQ_LAST(&sc->sc_txq[i],
5456 				    axq_q_s);
5457 				if (bf_last != NULL) {
5458 					ath_hal_gettxdesclinkptr(ah,
5459 					    bf_last->bf_lastds,
5460 					    &sc->sc_txq[i].axq_link);
5461 				} else {
5462 					sc->sc_txq[i].axq_link = NULL;
5463 				}
5464 				ATH_TXQ_UNLOCK(&sc->sc_txq[i]);
5465 			} else
5466 				ath_tx_draintxq(sc, &sc->sc_txq[i]);
5467 		}
5468 	}
5469 #ifdef ATH_DEBUG
5470 	if (sc->sc_debug & ATH_DEBUG_RESET) {
5471 		struct ath_buf *bf = TAILQ_FIRST(&sc->sc_bbuf);
5472 		if (bf != NULL && bf->bf_m != NULL) {
5473 			ath_printtxbuf(sc, bf, sc->sc_bhalq, 0,
5474 				ath_hal_txprocdesc(ah, bf->bf_lastds,
5475 				    &bf->bf_status.ds_txstat) == HAL_OK);
5476 			ieee80211_dump_pkt(ifp->if_l2com,
5477 			    mtod(bf->bf_m, const uint8_t *), bf->bf_m->m_len,
5478 			    0, -1);
5479 		}
5480 	}
5481 #endif /* ATH_DEBUG */
5482 	IF_LOCK(&ifp->if_snd);
5483 	ifp->if_drv_flags &= ~IFF_DRV_OACTIVE;
5484 	IF_UNLOCK(&ifp->if_snd);
5485 	sc->sc_wd_timer = 0;
5486 }
5487 
5488 /*
5489  * Update internal state after a channel change.
5490  */
5491 static void
5492 ath_chan_change(struct ath_softc *sc, struct ieee80211_channel *chan)
5493 {
5494 	enum ieee80211_phymode mode;
5495 
5496 	/*
5497 	 * Change channels and update the h/w rate map
5498 	 * if we're switching; e.g. 11a to 11b/g.
5499 	 */
5500 	mode = ieee80211_chan2mode(chan);
5501 	if (mode != sc->sc_curmode)
5502 		ath_setcurmode(sc, mode);
5503 	sc->sc_curchan = chan;
5504 }
5505 
5506 /*
5507  * Set/change channels.  If the channel is really being changed,
5508  * it's done by resetting the chip.  To accomplish this we must
5509  * first cleanup any pending DMA, then restart stuff after a la
5510  * ath_init.
5511  */
5512 static int
5513 ath_chan_set(struct ath_softc *sc, struct ieee80211_channel *chan)
5514 {
5515 	struct ifnet *ifp = sc->sc_ifp;
5516 	struct ieee80211com *ic = ifp->if_l2com;
5517 	struct ath_hal *ah = sc->sc_ah;
5518 	int ret = 0;
5519 
5520 	/* Treat this as an interface reset */
5521 	ATH_PCU_UNLOCK_ASSERT(sc);
5522 	ATH_UNLOCK_ASSERT(sc);
5523 
5524 	/* (Try to) stop TX/RX from occuring */
5525 	taskqueue_block(sc->sc_tq);
5526 
5527 	ATH_PCU_LOCK(sc);
5528 
5529 	/* Disable interrupts */
5530 	ath_hal_intrset(ah, 0);
5531 
5532 	/* Stop new RX/TX/interrupt completion */
5533 	if (ath_reset_grablock(sc, 1) == 0) {
5534 		device_printf(sc->sc_dev, "%s: concurrent reset! Danger!\n",
5535 		    __func__);
5536 	}
5537 
5538 	/* Stop pending RX/TX completion */
5539 	ath_txrx_stop_locked(sc);
5540 
5541 	ATH_PCU_UNLOCK(sc);
5542 
5543 	DPRINTF(sc, ATH_DEBUG_RESET, "%s: %u (%u MHz, flags 0x%x)\n",
5544 	    __func__, ieee80211_chan2ieee(ic, chan),
5545 	    chan->ic_freq, chan->ic_flags);
5546 	if (chan != sc->sc_curchan) {
5547 		HAL_STATUS status;
5548 		/*
5549 		 * To switch channels clear any pending DMA operations;
5550 		 * wait long enough for the RX fifo to drain, reset the
5551 		 * hardware at the new frequency, and then re-enable
5552 		 * the relevant bits of the h/w.
5553 		 */
5554 #if 0
5555 		ath_hal_intrset(ah, 0);		/* disable interrupts */
5556 #endif
5557 		ath_stoprecv(sc, 1);		/* turn off frame recv */
5558 		/*
5559 		 * First, handle completed TX/RX frames.
5560 		 */
5561 		ath_rx_flush(sc);
5562 		ath_draintxq(sc, ATH_RESET_NOLOSS);
5563 		/*
5564 		 * Next, flush the non-scheduled frames.
5565 		 */
5566 		ath_draintxq(sc, ATH_RESET_FULL);	/* clear pending tx frames */
5567 
5568 		ath_update_chainmasks(sc, chan);
5569 		ath_hal_setchainmasks(sc->sc_ah, sc->sc_cur_txchainmask,
5570 		    sc->sc_cur_rxchainmask);
5571 		if (!ath_hal_reset(ah, sc->sc_opmode, chan, AH_TRUE, &status)) {
5572 			device_printf(sc->sc_dev, "%s: unable to reset "
5573 			    "channel %u (%u MHz, flags 0x%x), hal status %u\n",
5574 			    __func__, ieee80211_chan2ieee(ic, chan),
5575 			    chan->ic_freq, chan->ic_flags, status);
5576 			ret = EIO;
5577 			goto finish;
5578 		}
5579 		sc->sc_diversity = ath_hal_getdiversity(ah);
5580 
5581 		ATH_RX_LOCK(sc);
5582 		sc->sc_rx_stopped = 1;
5583 		sc->sc_rx_resetted = 1;
5584 		ATH_RX_UNLOCK(sc);
5585 
5586 		/* Let DFS at it in case it's a DFS channel */
5587 		ath_dfs_radar_enable(sc, chan);
5588 
5589 		/* Let spectral at in case spectral is enabled */
5590 		ath_spectral_enable(sc, chan);
5591 
5592 		/*
5593 		 * Let bluetooth coexistence at in case it's needed for this
5594 		 * channel
5595 		 */
5596 		ath_btcoex_enable(sc, ic->ic_curchan);
5597 
5598 		/*
5599 		 * If we're doing TDMA, enforce the TXOP limitation for chips
5600 		 * that support it.
5601 		 */
5602 		if (sc->sc_hasenforcetxop && sc->sc_tdma)
5603 			ath_hal_setenforcetxop(sc->sc_ah, 1);
5604 		else
5605 			ath_hal_setenforcetxop(sc->sc_ah, 0);
5606 
5607 		/*
5608 		 * Re-enable rx framework.
5609 		 */
5610 		if (ath_startrecv(sc) != 0) {
5611 			device_printf(sc->sc_dev,
5612 			    "%s: unable to restart recv logic\n", __func__);
5613 			ret = EIO;
5614 			goto finish;
5615 		}
5616 
5617 		/*
5618 		 * Change channels and update the h/w rate map
5619 		 * if we're switching; e.g. 11a to 11b/g.
5620 		 */
5621 		ath_chan_change(sc, chan);
5622 
5623 		/*
5624 		 * Reset clears the beacon timers; reset them
5625 		 * here if needed.
5626 		 */
5627 		if (sc->sc_beacons) {		/* restart beacons */
5628 #ifdef IEEE80211_SUPPORT_TDMA
5629 			if (sc->sc_tdma)
5630 				ath_tdma_config(sc, NULL);
5631 			else
5632 #endif
5633 			ath_beacon_config(sc, NULL);
5634 		}
5635 
5636 		/*
5637 		 * Re-enable interrupts.
5638 		 */
5639 #if 0
5640 		ath_hal_intrset(ah, sc->sc_imask);
5641 #endif
5642 	}
5643 
5644 finish:
5645 	ATH_PCU_LOCK(sc);
5646 	sc->sc_inreset_cnt--;
5647 	/* XXX only do this if sc_inreset_cnt == 0? */
5648 	ath_hal_intrset(ah, sc->sc_imask);
5649 	ATH_PCU_UNLOCK(sc);
5650 
5651 	IF_LOCK(&ifp->if_snd);
5652 	ifp->if_drv_flags &= ~IFF_DRV_OACTIVE;
5653 	IF_UNLOCK(&ifp->if_snd);
5654 	ath_txrx_start(sc);
5655 	/* XXX ath_start? */
5656 
5657 	return ret;
5658 }
5659 
5660 /*
5661  * Periodically recalibrate the PHY to account
5662  * for temperature/environment changes.
5663  */
5664 static void
5665 ath_calibrate(void *arg)
5666 {
5667 	struct ath_softc *sc = arg;
5668 	struct ath_hal *ah = sc->sc_ah;
5669 	struct ifnet *ifp = sc->sc_ifp;
5670 	struct ieee80211com *ic = ifp->if_l2com;
5671 	HAL_BOOL longCal, isCalDone = AH_TRUE;
5672 	HAL_BOOL aniCal, shortCal = AH_FALSE;
5673 	int nextcal;
5674 
5675 	ATH_LOCK_ASSERT(sc);
5676 
5677 	/*
5678 	 * Force the hardware awake for ANI work.
5679 	 */
5680 	ath_power_set_power_state(sc, HAL_PM_AWAKE);
5681 
5682 	/* Skip trying to do this if we're in reset */
5683 	if (sc->sc_inreset_cnt)
5684 		goto restart;
5685 
5686 	if (ic->ic_flags & IEEE80211_F_SCAN)	/* defer, off channel */
5687 		goto restart;
5688 	longCal = (ticks - sc->sc_lastlongcal >= ath_longcalinterval*hz);
5689 	aniCal = (ticks - sc->sc_lastani >= ath_anicalinterval*hz/1000);
5690 	if (sc->sc_doresetcal)
5691 		shortCal = (ticks - sc->sc_lastshortcal >= ath_shortcalinterval*hz/1000);
5692 
5693 	DPRINTF(sc, ATH_DEBUG_CALIBRATE, "%s: shortCal=%d; longCal=%d; aniCal=%d\n", __func__, shortCal, longCal, aniCal);
5694 	if (aniCal) {
5695 		sc->sc_stats.ast_ani_cal++;
5696 		sc->sc_lastani = ticks;
5697 		ath_hal_ani_poll(ah, sc->sc_curchan);
5698 	}
5699 
5700 	if (longCal) {
5701 		sc->sc_stats.ast_per_cal++;
5702 		sc->sc_lastlongcal = ticks;
5703 		if (ath_hal_getrfgain(ah) == HAL_RFGAIN_NEED_CHANGE) {
5704 			/*
5705 			 * Rfgain is out of bounds, reset the chip
5706 			 * to load new gain values.
5707 			 */
5708 			DPRINTF(sc, ATH_DEBUG_CALIBRATE,
5709 				"%s: rfgain change\n", __func__);
5710 			sc->sc_stats.ast_per_rfgain++;
5711 			sc->sc_resetcal = 0;
5712 			sc->sc_doresetcal = AH_TRUE;
5713 			taskqueue_enqueue(sc->sc_tq, &sc->sc_resettask);
5714 			callout_reset(&sc->sc_cal_ch, 1, ath_calibrate, sc);
5715 			ath_power_restore_power_state(sc);
5716 			return;
5717 		}
5718 		/*
5719 		 * If this long cal is after an idle period, then
5720 		 * reset the data collection state so we start fresh.
5721 		 */
5722 		if (sc->sc_resetcal) {
5723 			(void) ath_hal_calreset(ah, sc->sc_curchan);
5724 			sc->sc_lastcalreset = ticks;
5725 			sc->sc_lastshortcal = ticks;
5726 			sc->sc_resetcal = 0;
5727 			sc->sc_doresetcal = AH_TRUE;
5728 		}
5729 	}
5730 
5731 	/* Only call if we're doing a short/long cal, not for ANI calibration */
5732 	if (shortCal || longCal) {
5733 		isCalDone = AH_FALSE;
5734 		if (ath_hal_calibrateN(ah, sc->sc_curchan, longCal, &isCalDone)) {
5735 			if (longCal) {
5736 				/*
5737 				 * Calibrate noise floor data again in case of change.
5738 				 */
5739 				ath_hal_process_noisefloor(ah);
5740 			}
5741 		} else {
5742 			DPRINTF(sc, ATH_DEBUG_ANY,
5743 				"%s: calibration of channel %u failed\n",
5744 				__func__, sc->sc_curchan->ic_freq);
5745 			sc->sc_stats.ast_per_calfail++;
5746 		}
5747 		if (shortCal)
5748 			sc->sc_lastshortcal = ticks;
5749 	}
5750 	if (!isCalDone) {
5751 restart:
5752 		/*
5753 		 * Use a shorter interval to potentially collect multiple
5754 		 * data samples required to complete calibration.  Once
5755 		 * we're told the work is done we drop back to a longer
5756 		 * interval between requests.  We're more aggressive doing
5757 		 * work when operating as an AP to improve operation right
5758 		 * after startup.
5759 		 */
5760 		sc->sc_lastshortcal = ticks;
5761 		nextcal = ath_shortcalinterval*hz/1000;
5762 		if (sc->sc_opmode != HAL_M_HOSTAP)
5763 			nextcal *= 10;
5764 		sc->sc_doresetcal = AH_TRUE;
5765 	} else {
5766 		/* nextcal should be the shortest time for next event */
5767 		nextcal = ath_longcalinterval*hz;
5768 		if (sc->sc_lastcalreset == 0)
5769 			sc->sc_lastcalreset = sc->sc_lastlongcal;
5770 		else if (ticks - sc->sc_lastcalreset >= ath_resetcalinterval*hz)
5771 			sc->sc_resetcal = 1;	/* setup reset next trip */
5772 		sc->sc_doresetcal = AH_FALSE;
5773 	}
5774 	/* ANI calibration may occur more often than short/long/resetcal */
5775 	if (ath_anicalinterval > 0)
5776 		nextcal = MIN(nextcal, ath_anicalinterval*hz/1000);
5777 
5778 	if (nextcal != 0) {
5779 		DPRINTF(sc, ATH_DEBUG_CALIBRATE, "%s: next +%u (%sisCalDone)\n",
5780 		    __func__, nextcal, isCalDone ? "" : "!");
5781 		callout_reset(&sc->sc_cal_ch, nextcal, ath_calibrate, sc);
5782 	} else {
5783 		DPRINTF(sc, ATH_DEBUG_CALIBRATE, "%s: calibration disabled\n",
5784 		    __func__);
5785 		/* NB: don't rearm timer */
5786 	}
5787 	/*
5788 	 * Restore power state now that we're done.
5789 	 */
5790 	ath_power_restore_power_state(sc);
5791 }
5792 
5793 static void
5794 ath_scan_start(struct ieee80211com *ic)
5795 {
5796 	struct ifnet *ifp = ic->ic_ifp;
5797 	struct ath_softc *sc = ifp->if_softc;
5798 	struct ath_hal *ah = sc->sc_ah;
5799 	u_int32_t rfilt;
5800 
5801 	/* XXX calibration timer? */
5802 
5803 	ATH_LOCK(sc);
5804 	sc->sc_scanning = 1;
5805 	sc->sc_syncbeacon = 0;
5806 	rfilt = ath_calcrxfilter(sc);
5807 	ATH_UNLOCK(sc);
5808 
5809 	ATH_PCU_LOCK(sc);
5810 	ath_hal_setrxfilter(ah, rfilt);
5811 	ath_hal_setassocid(ah, ifp->if_broadcastaddr, 0);
5812 	ATH_PCU_UNLOCK(sc);
5813 
5814 	DPRINTF(sc, ATH_DEBUG_STATE, "%s: RX filter 0x%x bssid %s aid 0\n",
5815 		 __func__, rfilt, ether_sprintf(ifp->if_broadcastaddr));
5816 }
5817 
5818 static void
5819 ath_scan_end(struct ieee80211com *ic)
5820 {
5821 	struct ifnet *ifp = ic->ic_ifp;
5822 	struct ath_softc *sc = ifp->if_softc;
5823 	struct ath_hal *ah = sc->sc_ah;
5824 	u_int32_t rfilt;
5825 
5826 	ATH_LOCK(sc);
5827 	sc->sc_scanning = 0;
5828 	rfilt = ath_calcrxfilter(sc);
5829 	ATH_UNLOCK(sc);
5830 
5831 	ATH_PCU_LOCK(sc);
5832 	ath_hal_setrxfilter(ah, rfilt);
5833 	ath_hal_setassocid(ah, sc->sc_curbssid, sc->sc_curaid);
5834 
5835 	ath_hal_process_noisefloor(ah);
5836 	ATH_PCU_UNLOCK(sc);
5837 
5838 	DPRINTF(sc, ATH_DEBUG_STATE, "%s: RX filter 0x%x bssid %s aid 0x%x\n",
5839 		 __func__, rfilt, ether_sprintf(sc->sc_curbssid),
5840 		 sc->sc_curaid);
5841 }
5842 
5843 #ifdef	ATH_ENABLE_11N
5844 /*
5845  * For now, just do a channel change.
5846  *
5847  * Later, we'll go through the hard slog of suspending tx/rx, changing rate
5848  * control state and resetting the hardware without dropping frames out
5849  * of the queue.
5850  *
5851  * The unfortunate trouble here is making absolutely sure that the
5852  * channel width change has propagated enough so the hardware
5853  * absolutely isn't handed bogus frames for it's current operating
5854  * mode. (Eg, 40MHz frames in 20MHz mode.) Since TX and RX can and
5855  * does occur in parallel, we need to make certain we've blocked
5856  * any further ongoing TX (and RX, that can cause raw TX)
5857  * before we do this.
5858  */
5859 static void
5860 ath_update_chw(struct ieee80211com *ic)
5861 {
5862 	struct ifnet *ifp = ic->ic_ifp;
5863 	struct ath_softc *sc = ifp->if_softc;
5864 
5865 	DPRINTF(sc, ATH_DEBUG_STATE, "%s: called\n", __func__);
5866 	ath_set_channel(ic);
5867 }
5868 #endif	/* ATH_ENABLE_11N */
5869 
5870 static void
5871 ath_set_channel(struct ieee80211com *ic)
5872 {
5873 	struct ifnet *ifp = ic->ic_ifp;
5874 	struct ath_softc *sc = ifp->if_softc;
5875 
5876 	ATH_LOCK(sc);
5877 	ath_power_set_power_state(sc, HAL_PM_AWAKE);
5878 	ATH_UNLOCK(sc);
5879 
5880 	(void) ath_chan_set(sc, ic->ic_curchan);
5881 	/*
5882 	 * If we are returning to our bss channel then mark state
5883 	 * so the next recv'd beacon's tsf will be used to sync the
5884 	 * beacon timers.  Note that since we only hear beacons in
5885 	 * sta/ibss mode this has no effect in other operating modes.
5886 	 */
5887 	ATH_LOCK(sc);
5888 	if (!sc->sc_scanning && ic->ic_curchan == ic->ic_bsschan)
5889 		sc->sc_syncbeacon = 1;
5890 	ath_power_restore_power_state(sc);
5891 	ATH_UNLOCK(sc);
5892 }
5893 
5894 /*
5895  * Walk the vap list and check if there any vap's in RUN state.
5896  */
5897 static int
5898 ath_isanyrunningvaps(struct ieee80211vap *this)
5899 {
5900 	struct ieee80211com *ic = this->iv_ic;
5901 	struct ieee80211vap *vap;
5902 
5903 	IEEE80211_LOCK_ASSERT(ic);
5904 
5905 	TAILQ_FOREACH(vap, &ic->ic_vaps, iv_next) {
5906 		if (vap != this && vap->iv_state >= IEEE80211_S_RUN)
5907 			return 1;
5908 	}
5909 	return 0;
5910 }
5911 
5912 static int
5913 ath_newstate(struct ieee80211vap *vap, enum ieee80211_state nstate, int arg)
5914 {
5915 	struct ieee80211com *ic = vap->iv_ic;
5916 	struct ath_softc *sc = ic->ic_ifp->if_softc;
5917 	struct ath_vap *avp = ATH_VAP(vap);
5918 	struct ath_hal *ah = sc->sc_ah;
5919 	struct ieee80211_node *ni = NULL;
5920 	int i, error, stamode;
5921 	u_int32_t rfilt;
5922 	int csa_run_transition = 0;
5923 	enum ieee80211_state ostate = vap->iv_state;
5924 
5925 	static const HAL_LED_STATE leds[] = {
5926 	    HAL_LED_INIT,	/* IEEE80211_S_INIT */
5927 	    HAL_LED_SCAN,	/* IEEE80211_S_SCAN */
5928 	    HAL_LED_AUTH,	/* IEEE80211_S_AUTH */
5929 	    HAL_LED_ASSOC, 	/* IEEE80211_S_ASSOC */
5930 	    HAL_LED_RUN, 	/* IEEE80211_S_CAC */
5931 	    HAL_LED_RUN, 	/* IEEE80211_S_RUN */
5932 	    HAL_LED_RUN, 	/* IEEE80211_S_CSA */
5933 	    HAL_LED_RUN, 	/* IEEE80211_S_SLEEP */
5934 	};
5935 
5936 	DPRINTF(sc, ATH_DEBUG_STATE, "%s: %s -> %s\n", __func__,
5937 		ieee80211_state_name[ostate],
5938 		ieee80211_state_name[nstate]);
5939 
5940 	/*
5941 	 * net80211 _should_ have the comlock asserted at this point.
5942 	 * There are some comments around the calls to vap->iv_newstate
5943 	 * which indicate that it (newstate) may end up dropping the
5944 	 * lock.  This and the subsequent lock assert check after newstate
5945 	 * are an attempt to catch these and figure out how/why.
5946 	 */
5947 	IEEE80211_LOCK_ASSERT(ic);
5948 
5949 	/* Before we touch the hardware - wake it up */
5950 	ATH_LOCK(sc);
5951 	/*
5952 	 * If the NIC is in anything other than SLEEP state,
5953 	 * we need to ensure that self-generated frames are
5954 	 * set for PWRMGT=0.  Otherwise we may end up with
5955 	 * strange situations.
5956 	 *
5957 	 * XXX TODO: is this actually the case? :-)
5958 	 */
5959 	if (nstate != IEEE80211_S_SLEEP)
5960 		ath_power_setselfgen(sc, HAL_PM_AWAKE);
5961 
5962 	/*
5963 	 * Now, wake the thing up.
5964 	 */
5965 	ath_power_set_power_state(sc, HAL_PM_AWAKE);
5966 
5967 	/*
5968 	 * And stop the calibration callout whilst we have
5969 	 * ATH_LOCK held.
5970 	 */
5971 	callout_stop(&sc->sc_cal_ch);
5972 	ATH_UNLOCK(sc);
5973 
5974 	if (ostate == IEEE80211_S_CSA && nstate == IEEE80211_S_RUN)
5975 		csa_run_transition = 1;
5976 
5977 	ath_hal_setledstate(ah, leds[nstate]);	/* set LED */
5978 
5979 	if (nstate == IEEE80211_S_SCAN) {
5980 		/*
5981 		 * Scanning: turn off beacon miss and don't beacon.
5982 		 * Mark beacon state so when we reach RUN state we'll
5983 		 * [re]setup beacons.  Unblock the task q thread so
5984 		 * deferred interrupt processing is done.
5985 		 */
5986 
5987 		/* Ensure we stay awake during scan */
5988 		ATH_LOCK(sc);
5989 		ath_power_setselfgen(sc, HAL_PM_AWAKE);
5990 		ath_power_setpower(sc, HAL_PM_AWAKE);
5991 		ATH_UNLOCK(sc);
5992 
5993 		ath_hal_intrset(ah,
5994 		    sc->sc_imask &~ (HAL_INT_SWBA | HAL_INT_BMISS));
5995 		sc->sc_imask &= ~(HAL_INT_SWBA | HAL_INT_BMISS);
5996 		sc->sc_beacons = 0;
5997 		taskqueue_unblock(sc->sc_tq);
5998 	}
5999 
6000 	ni = ieee80211_ref_node(vap->iv_bss);
6001 	rfilt = ath_calcrxfilter(sc);
6002 	stamode = (vap->iv_opmode == IEEE80211_M_STA ||
6003 		   vap->iv_opmode == IEEE80211_M_AHDEMO ||
6004 		   vap->iv_opmode == IEEE80211_M_IBSS);
6005 
6006 	/*
6007 	 * XXX Dont need to do this (and others) if we've transitioned
6008 	 * from SLEEP->RUN.
6009 	 */
6010 	if (stamode && nstate == IEEE80211_S_RUN) {
6011 		sc->sc_curaid = ni->ni_associd;
6012 		IEEE80211_ADDR_COPY(sc->sc_curbssid, ni->ni_bssid);
6013 		ath_hal_setassocid(ah, sc->sc_curbssid, sc->sc_curaid);
6014 	}
6015 	DPRINTF(sc, ATH_DEBUG_STATE, "%s: RX filter 0x%x bssid %s aid 0x%x\n",
6016 	   __func__, rfilt, ether_sprintf(sc->sc_curbssid), sc->sc_curaid);
6017 	ath_hal_setrxfilter(ah, rfilt);
6018 
6019 	/* XXX is this to restore keycache on resume? */
6020 	if (vap->iv_opmode != IEEE80211_M_STA &&
6021 	    (vap->iv_flags & IEEE80211_F_PRIVACY)) {
6022 		for (i = 0; i < IEEE80211_WEP_NKID; i++)
6023 			if (ath_hal_keyisvalid(ah, i))
6024 				ath_hal_keysetmac(ah, i, ni->ni_bssid);
6025 	}
6026 
6027 	/*
6028 	 * Invoke the parent method to do net80211 work.
6029 	 */
6030 	error = avp->av_newstate(vap, nstate, arg);
6031 	if (error != 0)
6032 		goto bad;
6033 
6034 	/*
6035 	 * See above: ensure av_newstate() doesn't drop the lock
6036 	 * on us.
6037 	 */
6038 	IEEE80211_LOCK_ASSERT(ic);
6039 
6040 	if (nstate == IEEE80211_S_RUN) {
6041 		/* NB: collect bss node again, it may have changed */
6042 		ieee80211_free_node(ni);
6043 		ni = ieee80211_ref_node(vap->iv_bss);
6044 
6045 		DPRINTF(sc, ATH_DEBUG_STATE,
6046 		    "%s(RUN): iv_flags 0x%08x bintvl %d bssid %s "
6047 		    "capinfo 0x%04x chan %d\n", __func__,
6048 		    vap->iv_flags, ni->ni_intval, ether_sprintf(ni->ni_bssid),
6049 		    ni->ni_capinfo, ieee80211_chan2ieee(ic, ic->ic_curchan));
6050 
6051 		switch (vap->iv_opmode) {
6052 #ifdef IEEE80211_SUPPORT_TDMA
6053 		case IEEE80211_M_AHDEMO:
6054 			if ((vap->iv_caps & IEEE80211_C_TDMA) == 0)
6055 				break;
6056 			/* fall thru... */
6057 #endif
6058 		case IEEE80211_M_HOSTAP:
6059 		case IEEE80211_M_IBSS:
6060 		case IEEE80211_M_MBSS:
6061 			/*
6062 			 * Allocate and setup the beacon frame.
6063 			 *
6064 			 * Stop any previous beacon DMA.  This may be
6065 			 * necessary, for example, when an ibss merge
6066 			 * causes reconfiguration; there will be a state
6067 			 * transition from RUN->RUN that means we may
6068 			 * be called with beacon transmission active.
6069 			 */
6070 			ath_hal_stoptxdma(ah, sc->sc_bhalq);
6071 
6072 			error = ath_beacon_alloc(sc, ni);
6073 			if (error != 0)
6074 				goto bad;
6075 			/*
6076 			 * If joining an adhoc network defer beacon timer
6077 			 * configuration to the next beacon frame so we
6078 			 * have a current TSF to use.  Otherwise we're
6079 			 * starting an ibss/bss so there's no need to delay;
6080 			 * if this is the first vap moving to RUN state, then
6081 			 * beacon state needs to be [re]configured.
6082 			 */
6083 			if (vap->iv_opmode == IEEE80211_M_IBSS &&
6084 			    ni->ni_tstamp.tsf != 0) {
6085 				sc->sc_syncbeacon = 1;
6086 			} else if (!sc->sc_beacons) {
6087 #ifdef IEEE80211_SUPPORT_TDMA
6088 				if (vap->iv_caps & IEEE80211_C_TDMA)
6089 					ath_tdma_config(sc, vap);
6090 				else
6091 #endif
6092 					ath_beacon_config(sc, vap);
6093 				sc->sc_beacons = 1;
6094 			}
6095 			break;
6096 		case IEEE80211_M_STA:
6097 			/*
6098 			 * Defer beacon timer configuration to the next
6099 			 * beacon frame so we have a current TSF to use
6100 			 * (any TSF collected when scanning is likely old).
6101 			 * However if it's due to a CSA -> RUN transition,
6102 			 * force a beacon update so we pick up a lack of
6103 			 * beacons from an AP in CAC and thus force a
6104 			 * scan.
6105 			 *
6106 			 * And, there's also corner cases here where
6107 			 * after a scan, the AP may have disappeared.
6108 			 * In that case, we may not receive an actual
6109 			 * beacon to update the beacon timer and thus we
6110 			 * won't get notified of the missing beacons.
6111 			 */
6112 			if (ostate != IEEE80211_S_RUN &&
6113 			    ostate != IEEE80211_S_SLEEP) {
6114 				DPRINTF(sc, ATH_DEBUG_BEACON,
6115 				    "%s: STA; syncbeacon=1\n", __func__);
6116 				sc->sc_syncbeacon = 1;
6117 
6118 				if (csa_run_transition)
6119 					ath_beacon_config(sc, vap);
6120 
6121 			/*
6122 			 * PR: kern/175227
6123 			 *
6124 			 * Reconfigure beacons during reset; as otherwise
6125 			 * we won't get the beacon timers reprogrammed
6126 			 * after a reset and thus we won't pick up a
6127 			 * beacon miss interrupt.
6128 			 *
6129 			 * Hopefully we'll see a beacon before the BMISS
6130 			 * timer fires (too often), leading to a STA
6131 			 * disassociation.
6132 			 */
6133 				sc->sc_beacons = 1;
6134 			}
6135 			break;
6136 		case IEEE80211_M_MONITOR:
6137 			/*
6138 			 * Monitor mode vaps have only INIT->RUN and RUN->RUN
6139 			 * transitions so we must re-enable interrupts here to
6140 			 * handle the case of a single monitor mode vap.
6141 			 */
6142 			ath_hal_intrset(ah, sc->sc_imask);
6143 			break;
6144 		case IEEE80211_M_WDS:
6145 			break;
6146 		default:
6147 			break;
6148 		}
6149 		/*
6150 		 * Let the hal process statistics collected during a
6151 		 * scan so it can provide calibrated noise floor data.
6152 		 */
6153 		ath_hal_process_noisefloor(ah);
6154 		/*
6155 		 * Reset rssi stats; maybe not the best place...
6156 		 */
6157 		sc->sc_halstats.ns_avgbrssi = ATH_RSSI_DUMMY_MARKER;
6158 		sc->sc_halstats.ns_avgrssi = ATH_RSSI_DUMMY_MARKER;
6159 		sc->sc_halstats.ns_avgtxrssi = ATH_RSSI_DUMMY_MARKER;
6160 
6161 		/*
6162 		 * Force awake for RUN mode.
6163 		 */
6164 		ATH_LOCK(sc);
6165 		ath_power_setselfgen(sc, HAL_PM_AWAKE);
6166 		ath_power_setpower(sc, HAL_PM_AWAKE);
6167 
6168 		/*
6169 		 * Finally, start any timers and the task q thread
6170 		 * (in case we didn't go through SCAN state).
6171 		 */
6172 		if (ath_longcalinterval != 0) {
6173 			/* start periodic recalibration timer */
6174 			callout_reset(&sc->sc_cal_ch, 1, ath_calibrate, sc);
6175 		} else {
6176 			DPRINTF(sc, ATH_DEBUG_CALIBRATE,
6177 			    "%s: calibration disabled\n", __func__);
6178 		}
6179 		ATH_UNLOCK(sc);
6180 
6181 		taskqueue_unblock(sc->sc_tq);
6182 	} else if (nstate == IEEE80211_S_INIT) {
6183 		/*
6184 		 * If there are no vaps left in RUN state then
6185 		 * shutdown host/driver operation:
6186 		 * o disable interrupts
6187 		 * o disable the task queue thread
6188 		 * o mark beacon processing as stopped
6189 		 */
6190 		if (!ath_isanyrunningvaps(vap)) {
6191 			sc->sc_imask &= ~(HAL_INT_SWBA | HAL_INT_BMISS);
6192 			/* disable interrupts  */
6193 			ath_hal_intrset(ah, sc->sc_imask &~ HAL_INT_GLOBAL);
6194 			taskqueue_block(sc->sc_tq);
6195 			sc->sc_beacons = 0;
6196 		}
6197 #ifdef IEEE80211_SUPPORT_TDMA
6198 		ath_hal_setcca(ah, AH_TRUE);
6199 #endif
6200 	} else if (nstate == IEEE80211_S_SLEEP) {
6201 		/* We're going to sleep, so transition appropriately */
6202 		/* For now, only do this if we're a single STA vap */
6203 		if (sc->sc_nvaps == 1 &&
6204 		    vap->iv_opmode == IEEE80211_M_STA) {
6205 			DPRINTF(sc, ATH_DEBUG_BEACON, "%s: syncbeacon=%d\n", __func__, sc->sc_syncbeacon);
6206 			ATH_LOCK(sc);
6207 			/*
6208 			 * Always at least set the self-generated
6209 			 * frame config to set PWRMGT=1.
6210 			 */
6211 			ath_power_setselfgen(sc, HAL_PM_NETWORK_SLEEP);
6212 
6213 			/*
6214 			 * If we're not syncing beacons, transition
6215 			 * to NETWORK_SLEEP.
6216 			 *
6217 			 * We stay awake if syncbeacon > 0 in case
6218 			 * we need to listen for some beacons otherwise
6219 			 * our beacon timer config may be wrong.
6220 			 */
6221 			if (sc->sc_syncbeacon == 0) {
6222 				ath_power_setpower(sc, HAL_PM_NETWORK_SLEEP);
6223 			}
6224 			ATH_UNLOCK(sc);
6225 		}
6226 	}
6227 bad:
6228 	ieee80211_free_node(ni);
6229 
6230 	/*
6231 	 * Restore the power state - either to what it was, or
6232 	 * to network_sleep if it's alright.
6233 	 */
6234 	ATH_LOCK(sc);
6235 	ath_power_restore_power_state(sc);
6236 	ATH_UNLOCK(sc);
6237 	return error;
6238 }
6239 
6240 /*
6241  * Allocate a key cache slot to the station so we can
6242  * setup a mapping from key index to node. The key cache
6243  * slot is needed for managing antenna state and for
6244  * compression when stations do not use crypto.  We do
6245  * it uniliaterally here; if crypto is employed this slot
6246  * will be reassigned.
6247  */
6248 static void
6249 ath_setup_stationkey(struct ieee80211_node *ni)
6250 {
6251 	struct ieee80211vap *vap = ni->ni_vap;
6252 	struct ath_softc *sc = vap->iv_ic->ic_ifp->if_softc;
6253 	ieee80211_keyix keyix, rxkeyix;
6254 
6255 	/* XXX should take a locked ref to vap->iv_bss */
6256 	if (!ath_key_alloc(vap, &ni->ni_ucastkey, &keyix, &rxkeyix)) {
6257 		/*
6258 		 * Key cache is full; we'll fall back to doing
6259 		 * the more expensive lookup in software.  Note
6260 		 * this also means no h/w compression.
6261 		 */
6262 		/* XXX msg+statistic */
6263 	} else {
6264 		/* XXX locking? */
6265 		ni->ni_ucastkey.wk_keyix = keyix;
6266 		ni->ni_ucastkey.wk_rxkeyix = rxkeyix;
6267 		/* NB: must mark device key to get called back on delete */
6268 		ni->ni_ucastkey.wk_flags |= IEEE80211_KEY_DEVKEY;
6269 		IEEE80211_ADDR_COPY(ni->ni_ucastkey.wk_macaddr, ni->ni_macaddr);
6270 		/* NB: this will create a pass-thru key entry */
6271 		ath_keyset(sc, vap, &ni->ni_ucastkey, vap->iv_bss);
6272 	}
6273 }
6274 
6275 /*
6276  * Setup driver-specific state for a newly associated node.
6277  * Note that we're called also on a re-associate, the isnew
6278  * param tells us if this is the first time or not.
6279  */
6280 static void
6281 ath_newassoc(struct ieee80211_node *ni, int isnew)
6282 {
6283 	struct ath_node *an = ATH_NODE(ni);
6284 	struct ieee80211vap *vap = ni->ni_vap;
6285 	struct ath_softc *sc = vap->iv_ic->ic_ifp->if_softc;
6286 	const struct ieee80211_txparam *tp = ni->ni_txparms;
6287 
6288 	an->an_mcastrix = ath_tx_findrix(sc, tp->mcastrate);
6289 	an->an_mgmtrix = ath_tx_findrix(sc, tp->mgmtrate);
6290 
6291 	DPRINTF(sc, ATH_DEBUG_NODE, "%s: %6D: reassoc; isnew=%d, is_powersave=%d\n",
6292 	    __func__,
6293 	    ni->ni_macaddr,
6294 	    ":",
6295 	    isnew,
6296 	    an->an_is_powersave);
6297 
6298 	ATH_NODE_LOCK(an);
6299 	ath_rate_newassoc(sc, an, isnew);
6300 	ATH_NODE_UNLOCK(an);
6301 
6302 	if (isnew &&
6303 	    (vap->iv_flags & IEEE80211_F_PRIVACY) == 0 && sc->sc_hasclrkey &&
6304 	    ni->ni_ucastkey.wk_keyix == IEEE80211_KEYIX_NONE)
6305 		ath_setup_stationkey(ni);
6306 
6307 	/*
6308 	 * If we're reassociating, make sure that any paused queues
6309 	 * get unpaused.
6310 	 *
6311 	 * Now, we may hvae frames in the hardware queue for this node.
6312 	 * So if we are reassociating and there are frames in the queue,
6313 	 * we need to go through the cleanup path to ensure that they're
6314 	 * marked as non-aggregate.
6315 	 */
6316 	if (! isnew) {
6317 		DPRINTF(sc, ATH_DEBUG_NODE,
6318 		    "%s: %6D: reassoc; is_powersave=%d\n",
6319 		    __func__,
6320 		    ni->ni_macaddr,
6321 		    ":",
6322 		    an->an_is_powersave);
6323 
6324 		/* XXX for now, we can't hold the lock across assoc */
6325 		ath_tx_node_reassoc(sc, an);
6326 
6327 		/* XXX for now, we can't hold the lock across wakeup */
6328 		if (an->an_is_powersave)
6329 			ath_tx_node_wakeup(sc, an);
6330 	}
6331 }
6332 
6333 static int
6334 ath_setregdomain(struct ieee80211com *ic, struct ieee80211_regdomain *reg,
6335 	int nchans, struct ieee80211_channel chans[])
6336 {
6337 	struct ath_softc *sc = ic->ic_ifp->if_softc;
6338 	struct ath_hal *ah = sc->sc_ah;
6339 	HAL_STATUS status;
6340 
6341 	DPRINTF(sc, ATH_DEBUG_REGDOMAIN,
6342 	    "%s: rd %u cc %u location %c%s\n",
6343 	    __func__, reg->regdomain, reg->country, reg->location,
6344 	    reg->ecm ? " ecm" : "");
6345 
6346 	status = ath_hal_set_channels(ah, chans, nchans,
6347 	    reg->country, reg->regdomain);
6348 	if (status != HAL_OK) {
6349 		DPRINTF(sc, ATH_DEBUG_REGDOMAIN, "%s: failed, status %u\n",
6350 		    __func__, status);
6351 		return EINVAL;		/* XXX */
6352 	}
6353 
6354 	return 0;
6355 }
6356 
6357 static void
6358 ath_getradiocaps(struct ieee80211com *ic,
6359 	int maxchans, int *nchans, struct ieee80211_channel chans[])
6360 {
6361 	struct ath_softc *sc = ic->ic_ifp->if_softc;
6362 	struct ath_hal *ah = sc->sc_ah;
6363 
6364 	DPRINTF(sc, ATH_DEBUG_REGDOMAIN, "%s: use rd %u cc %d\n",
6365 	    __func__, SKU_DEBUG, CTRY_DEFAULT);
6366 
6367 	/* XXX check return */
6368 	(void) ath_hal_getchannels(ah, chans, maxchans, nchans,
6369 	    HAL_MODE_ALL, CTRY_DEFAULT, SKU_DEBUG, AH_TRUE);
6370 
6371 }
6372 
6373 static int
6374 ath_getchannels(struct ath_softc *sc)
6375 {
6376 	struct ifnet *ifp = sc->sc_ifp;
6377 	struct ieee80211com *ic = ifp->if_l2com;
6378 	struct ath_hal *ah = sc->sc_ah;
6379 	HAL_STATUS status;
6380 
6381 	/*
6382 	 * Collect channel set based on EEPROM contents.
6383 	 */
6384 	status = ath_hal_init_channels(ah, ic->ic_channels, IEEE80211_CHAN_MAX,
6385 	    &ic->ic_nchans, HAL_MODE_ALL, CTRY_DEFAULT, SKU_NONE, AH_TRUE);
6386 	if (status != HAL_OK) {
6387 		device_printf(sc->sc_dev,
6388 		    "%s: unable to collect channel list from hal, status %d\n",
6389 		    __func__, status);
6390 		return EINVAL;
6391 	}
6392 	(void) ath_hal_getregdomain(ah, &sc->sc_eerd);
6393 	ath_hal_getcountrycode(ah, &sc->sc_eecc);	/* NB: cannot fail */
6394 	/* XXX map Atheros sku's to net80211 SKU's */
6395 	/* XXX net80211 types too small */
6396 	ic->ic_regdomain.regdomain = (uint16_t) sc->sc_eerd;
6397 	ic->ic_regdomain.country = (uint16_t) sc->sc_eecc;
6398 	ic->ic_regdomain.isocc[0] = ' ';	/* XXX don't know */
6399 	ic->ic_regdomain.isocc[1] = ' ';
6400 
6401 	ic->ic_regdomain.ecm = 1;
6402 	ic->ic_regdomain.location = 'I';
6403 
6404 	DPRINTF(sc, ATH_DEBUG_REGDOMAIN,
6405 	    "%s: eeprom rd %u cc %u (mapped rd %u cc %u) location %c%s\n",
6406 	    __func__, sc->sc_eerd, sc->sc_eecc,
6407 	    ic->ic_regdomain.regdomain, ic->ic_regdomain.country,
6408 	    ic->ic_regdomain.location, ic->ic_regdomain.ecm ? " ecm" : "");
6409 	return 0;
6410 }
6411 
6412 static int
6413 ath_rate_setup(struct ath_softc *sc, u_int mode)
6414 {
6415 	struct ath_hal *ah = sc->sc_ah;
6416 	const HAL_RATE_TABLE *rt;
6417 
6418 	switch (mode) {
6419 	case IEEE80211_MODE_11A:
6420 		rt = ath_hal_getratetable(ah, HAL_MODE_11A);
6421 		break;
6422 	case IEEE80211_MODE_HALF:
6423 		rt = ath_hal_getratetable(ah, HAL_MODE_11A_HALF_RATE);
6424 		break;
6425 	case IEEE80211_MODE_QUARTER:
6426 		rt = ath_hal_getratetable(ah, HAL_MODE_11A_QUARTER_RATE);
6427 		break;
6428 	case IEEE80211_MODE_11B:
6429 		rt = ath_hal_getratetable(ah, HAL_MODE_11B);
6430 		break;
6431 	case IEEE80211_MODE_11G:
6432 		rt = ath_hal_getratetable(ah, HAL_MODE_11G);
6433 		break;
6434 	case IEEE80211_MODE_TURBO_A:
6435 		rt = ath_hal_getratetable(ah, HAL_MODE_108A);
6436 		break;
6437 	case IEEE80211_MODE_TURBO_G:
6438 		rt = ath_hal_getratetable(ah, HAL_MODE_108G);
6439 		break;
6440 	case IEEE80211_MODE_STURBO_A:
6441 		rt = ath_hal_getratetable(ah, HAL_MODE_TURBO);
6442 		break;
6443 	case IEEE80211_MODE_11NA:
6444 		rt = ath_hal_getratetable(ah, HAL_MODE_11NA_HT20);
6445 		break;
6446 	case IEEE80211_MODE_11NG:
6447 		rt = ath_hal_getratetable(ah, HAL_MODE_11NG_HT20);
6448 		break;
6449 	default:
6450 		DPRINTF(sc, ATH_DEBUG_ANY, "%s: invalid mode %u\n",
6451 			__func__, mode);
6452 		return 0;
6453 	}
6454 	sc->sc_rates[mode] = rt;
6455 	return (rt != NULL);
6456 }
6457 
6458 static void
6459 ath_setcurmode(struct ath_softc *sc, enum ieee80211_phymode mode)
6460 {
6461 #define	N(a)	(sizeof(a)/sizeof(a[0]))
6462 	/* NB: on/off times from the Atheros NDIS driver, w/ permission */
6463 	static const struct {
6464 		u_int		rate;		/* tx/rx 802.11 rate */
6465 		u_int16_t	timeOn;		/* LED on time (ms) */
6466 		u_int16_t	timeOff;	/* LED off time (ms) */
6467 	} blinkrates[] = {
6468 		{ 108,  40,  10 },
6469 		{  96,  44,  11 },
6470 		{  72,  50,  13 },
6471 		{  48,  57,  14 },
6472 		{  36,  67,  16 },
6473 		{  24,  80,  20 },
6474 		{  22, 100,  25 },
6475 		{  18, 133,  34 },
6476 		{  12, 160,  40 },
6477 		{  10, 200,  50 },
6478 		{   6, 240,  58 },
6479 		{   4, 267,  66 },
6480 		{   2, 400, 100 },
6481 		{   0, 500, 130 },
6482 		/* XXX half/quarter rates */
6483 	};
6484 	const HAL_RATE_TABLE *rt;
6485 	int i, j;
6486 
6487 	memset(sc->sc_rixmap, 0xff, sizeof(sc->sc_rixmap));
6488 	rt = sc->sc_rates[mode];
6489 	KASSERT(rt != NULL, ("no h/w rate set for phy mode %u", mode));
6490 	for (i = 0; i < rt->rateCount; i++) {
6491 		uint8_t ieeerate = rt->info[i].dot11Rate & IEEE80211_RATE_VAL;
6492 		if (rt->info[i].phy != IEEE80211_T_HT)
6493 			sc->sc_rixmap[ieeerate] = i;
6494 		else
6495 			sc->sc_rixmap[ieeerate | IEEE80211_RATE_MCS] = i;
6496 	}
6497 	memset(sc->sc_hwmap, 0, sizeof(sc->sc_hwmap));
6498 	for (i = 0; i < N(sc->sc_hwmap); i++) {
6499 		if (i >= rt->rateCount) {
6500 			sc->sc_hwmap[i].ledon = (500 * hz) / 1000;
6501 			sc->sc_hwmap[i].ledoff = (130 * hz) / 1000;
6502 			continue;
6503 		}
6504 		sc->sc_hwmap[i].ieeerate =
6505 			rt->info[i].dot11Rate & IEEE80211_RATE_VAL;
6506 		if (rt->info[i].phy == IEEE80211_T_HT)
6507 			sc->sc_hwmap[i].ieeerate |= IEEE80211_RATE_MCS;
6508 		sc->sc_hwmap[i].txflags = IEEE80211_RADIOTAP_F_DATAPAD;
6509 		if (rt->info[i].shortPreamble ||
6510 		    rt->info[i].phy == IEEE80211_T_OFDM)
6511 			sc->sc_hwmap[i].txflags |= IEEE80211_RADIOTAP_F_SHORTPRE;
6512 		sc->sc_hwmap[i].rxflags = sc->sc_hwmap[i].txflags;
6513 		for (j = 0; j < N(blinkrates)-1; j++)
6514 			if (blinkrates[j].rate == sc->sc_hwmap[i].ieeerate)
6515 				break;
6516 		/* NB: this uses the last entry if the rate isn't found */
6517 		/* XXX beware of overlow */
6518 		sc->sc_hwmap[i].ledon = (blinkrates[j].timeOn * hz) / 1000;
6519 		sc->sc_hwmap[i].ledoff = (blinkrates[j].timeOff * hz) / 1000;
6520 	}
6521 	sc->sc_currates = rt;
6522 	sc->sc_curmode = mode;
6523 	/*
6524 	 * All protection frames are transmited at 2Mb/s for
6525 	 * 11g, otherwise at 1Mb/s.
6526 	 */
6527 	if (mode == IEEE80211_MODE_11G)
6528 		sc->sc_protrix = ath_tx_findrix(sc, 2*2);
6529 	else
6530 		sc->sc_protrix = ath_tx_findrix(sc, 2*1);
6531 	/* NB: caller is responsible for resetting rate control state */
6532 #undef N
6533 }
6534 
6535 static void
6536 ath_watchdog(void *arg)
6537 {
6538 	struct ath_softc *sc = arg;
6539 	int do_reset = 0;
6540 
6541 	ATH_LOCK_ASSERT(sc);
6542 
6543 	if (sc->sc_wd_timer != 0 && --sc->sc_wd_timer == 0) {
6544 		struct ifnet *ifp = sc->sc_ifp;
6545 		uint32_t hangs;
6546 
6547 		ath_power_set_power_state(sc, HAL_PM_AWAKE);
6548 
6549 		if (ath_hal_gethangstate(sc->sc_ah, 0xffff, &hangs) &&
6550 		    hangs != 0) {
6551 			device_printf(sc->sc_dev, "%s hang detected (0x%x)\n",
6552 			    hangs & 0xff ? "bb" : "mac", hangs);
6553 		} else
6554 			device_printf(sc->sc_dev, "device timeout\n");
6555 		do_reset = 1;
6556 		if_inc_counter(ifp, IFCOUNTER_OERRORS, 1);
6557 		sc->sc_stats.ast_watchdog++;
6558 
6559 		ath_power_restore_power_state(sc);
6560 	}
6561 
6562 	/*
6563 	 * We can't hold the lock across the ath_reset() call.
6564 	 *
6565 	 * And since this routine can't hold a lock and sleep,
6566 	 * do the reset deferred.
6567 	 */
6568 	if (do_reset) {
6569 		taskqueue_enqueue(sc->sc_tq, &sc->sc_resettask);
6570 	}
6571 
6572 	callout_schedule(&sc->sc_wd_ch, hz);
6573 }
6574 
6575 /*
6576  * Fetch the rate control statistics for the given node.
6577  */
6578 static int
6579 ath_ioctl_ratestats(struct ath_softc *sc, struct ath_rateioctl *rs)
6580 {
6581 	struct ath_node *an;
6582 	struct ieee80211com *ic = sc->sc_ifp->if_l2com;
6583 	struct ieee80211_node *ni;
6584 	int error = 0;
6585 
6586 	/* Perform a lookup on the given node */
6587 	ni = ieee80211_find_node(&ic->ic_sta, rs->is_u.macaddr);
6588 	if (ni == NULL) {
6589 		error = EINVAL;
6590 		goto bad;
6591 	}
6592 
6593 	/* Lock the ath_node */
6594 	an = ATH_NODE(ni);
6595 	ATH_NODE_LOCK(an);
6596 
6597 	/* Fetch the rate control stats for this node */
6598 	error = ath_rate_fetch_node_stats(sc, an, rs);
6599 
6600 	/* No matter what happens here, just drop through */
6601 
6602 	/* Unlock the ath_node */
6603 	ATH_NODE_UNLOCK(an);
6604 
6605 	/* Unref the node */
6606 	ieee80211_node_decref(ni);
6607 
6608 bad:
6609 	return (error);
6610 }
6611 
6612 #ifdef ATH_DIAGAPI
6613 /*
6614  * Diagnostic interface to the HAL.  This is used by various
6615  * tools to do things like retrieve register contents for
6616  * debugging.  The mechanism is intentionally opaque so that
6617  * it can change frequently w/o concern for compatiblity.
6618  */
6619 static int
6620 ath_ioctl_diag(struct ath_softc *sc, struct ath_diag *ad)
6621 {
6622 	struct ath_hal *ah = sc->sc_ah;
6623 	u_int id = ad->ad_id & ATH_DIAG_ID;
6624 	void *indata = NULL;
6625 	void *outdata = NULL;
6626 	u_int32_t insize = ad->ad_in_size;
6627 	u_int32_t outsize = ad->ad_out_size;
6628 	int error = 0;
6629 
6630 	if (ad->ad_id & ATH_DIAG_IN) {
6631 		/*
6632 		 * Copy in data.
6633 		 */
6634 		indata = malloc(insize, M_TEMP, M_NOWAIT);
6635 		if (indata == NULL) {
6636 			error = ENOMEM;
6637 			goto bad;
6638 		}
6639 		error = copyin(ad->ad_in_data, indata, insize);
6640 		if (error)
6641 			goto bad;
6642 	}
6643 	if (ad->ad_id & ATH_DIAG_DYN) {
6644 		/*
6645 		 * Allocate a buffer for the results (otherwise the HAL
6646 		 * returns a pointer to a buffer where we can read the
6647 		 * results).  Note that we depend on the HAL leaving this
6648 		 * pointer for us to use below in reclaiming the buffer;
6649 		 * may want to be more defensive.
6650 		 */
6651 		outdata = malloc(outsize, M_TEMP, M_NOWAIT);
6652 		if (outdata == NULL) {
6653 			error = ENOMEM;
6654 			goto bad;
6655 		}
6656 	}
6657 
6658 
6659 	ATH_LOCK(sc);
6660 	if (id != HAL_DIAG_REGS)
6661 		ath_power_set_power_state(sc, HAL_PM_AWAKE);
6662 	ATH_UNLOCK(sc);
6663 
6664 	if (ath_hal_getdiagstate(ah, id, indata, insize, &outdata, &outsize)) {
6665 		if (outsize < ad->ad_out_size)
6666 			ad->ad_out_size = outsize;
6667 		if (outdata != NULL)
6668 			error = copyout(outdata, ad->ad_out_data,
6669 					ad->ad_out_size);
6670 	} else {
6671 		error = EINVAL;
6672 	}
6673 
6674 	ATH_LOCK(sc);
6675 	if (id != HAL_DIAG_REGS)
6676 		ath_power_restore_power_state(sc);
6677 	ATH_UNLOCK(sc);
6678 
6679 bad:
6680 	if ((ad->ad_id & ATH_DIAG_IN) && indata != NULL)
6681 		free(indata, M_TEMP);
6682 	if ((ad->ad_id & ATH_DIAG_DYN) && outdata != NULL)
6683 		free(outdata, M_TEMP);
6684 	return error;
6685 }
6686 #endif /* ATH_DIAGAPI */
6687 
6688 static int
6689 ath_ioctl(struct ifnet *ifp, u_long cmd, caddr_t data)
6690 {
6691 #define	IS_RUNNING(ifp) \
6692 	((ifp->if_flags & IFF_UP) && (ifp->if_drv_flags & IFF_DRV_RUNNING))
6693 	struct ath_softc *sc = ifp->if_softc;
6694 	struct ieee80211com *ic = ifp->if_l2com;
6695 	struct ifreq *ifr = (struct ifreq *)data;
6696 	const HAL_RATE_TABLE *rt;
6697 	int error = 0;
6698 
6699 	switch (cmd) {
6700 	case SIOCSIFFLAGS:
6701 		if (IS_RUNNING(ifp)) {
6702 			/*
6703 			 * To avoid rescanning another access point,
6704 			 * do not call ath_init() here.  Instead,
6705 			 * only reflect promisc mode settings.
6706 			 */
6707 			ATH_LOCK(sc);
6708 			ath_power_set_power_state(sc, HAL_PM_AWAKE);
6709 			ath_mode_init(sc);
6710 			ath_power_restore_power_state(sc);
6711 			ATH_UNLOCK(sc);
6712 		} else if (ifp->if_flags & IFF_UP) {
6713 			/*
6714 			 * Beware of being called during attach/detach
6715 			 * to reset promiscuous mode.  In that case we
6716 			 * will still be marked UP but not RUNNING.
6717 			 * However trying to re-init the interface
6718 			 * is the wrong thing to do as we've already
6719 			 * torn down much of our state.  There's
6720 			 * probably a better way to deal with this.
6721 			 */
6722 			if (!sc->sc_invalid)
6723 				ath_init(sc);	/* XXX lose error */
6724 		} else {
6725 			ATH_LOCK(sc);
6726 			ath_stop_locked(ifp);
6727 			if (!sc->sc_invalid)
6728 				ath_power_setpower(sc, HAL_PM_FULL_SLEEP);
6729 			ATH_UNLOCK(sc);
6730 		}
6731 		break;
6732 	case SIOCGIFMEDIA:
6733 	case SIOCSIFMEDIA:
6734 		error = ifmedia_ioctl(ifp, ifr, &ic->ic_media, cmd);
6735 		break;
6736 	case SIOCGATHSTATS:
6737 		/* NB: embed these numbers to get a consistent view */
6738 		sc->sc_stats.ast_tx_packets = ifp->if_get_counter(ifp,
6739 		    IFCOUNTER_OPACKETS);
6740 		sc->sc_stats.ast_rx_packets = ifp->if_get_counter(ifp,
6741 		    IFCOUNTER_IPACKETS);
6742 		sc->sc_stats.ast_tx_rssi = ATH_RSSI(sc->sc_halstats.ns_avgtxrssi);
6743 		sc->sc_stats.ast_rx_rssi = ATH_RSSI(sc->sc_halstats.ns_avgrssi);
6744 #ifdef IEEE80211_SUPPORT_TDMA
6745 		sc->sc_stats.ast_tdma_tsfadjp = TDMA_AVG(sc->sc_avgtsfdeltap);
6746 		sc->sc_stats.ast_tdma_tsfadjm = TDMA_AVG(sc->sc_avgtsfdeltam);
6747 #endif
6748 		rt = sc->sc_currates;
6749 		sc->sc_stats.ast_tx_rate =
6750 		    rt->info[sc->sc_txrix].dot11Rate &~ IEEE80211_RATE_BASIC;
6751 		if (rt->info[sc->sc_txrix].phy & IEEE80211_T_HT)
6752 			sc->sc_stats.ast_tx_rate |= IEEE80211_RATE_MCS;
6753 		return copyout(&sc->sc_stats,
6754 		    ifr->ifr_data, sizeof (sc->sc_stats));
6755 	case SIOCGATHAGSTATS:
6756 		return copyout(&sc->sc_aggr_stats,
6757 		    ifr->ifr_data, sizeof (sc->sc_aggr_stats));
6758 	case SIOCZATHSTATS:
6759 		error = priv_check(curthread, PRIV_DRIVER);
6760 		if (error == 0) {
6761 			memset(&sc->sc_stats, 0, sizeof(sc->sc_stats));
6762 			memset(&sc->sc_aggr_stats, 0,
6763 			    sizeof(sc->sc_aggr_stats));
6764 			memset(&sc->sc_intr_stats, 0,
6765 			    sizeof(sc->sc_intr_stats));
6766 		}
6767 		break;
6768 #ifdef ATH_DIAGAPI
6769 	case SIOCGATHDIAG:
6770 		error = ath_ioctl_diag(sc, (struct ath_diag *) ifr);
6771 		break;
6772 	case SIOCGATHPHYERR:
6773 		error = ath_ioctl_phyerr(sc,(struct ath_diag*) ifr);
6774 		break;
6775 #endif
6776 	case SIOCGATHSPECTRAL:
6777 		error = ath_ioctl_spectral(sc,(struct ath_diag*) ifr);
6778 		break;
6779 	case SIOCGATHNODERATESTATS:
6780 		error = ath_ioctl_ratestats(sc, (struct ath_rateioctl *) ifr);
6781 		break;
6782 	case SIOCGIFADDR:
6783 		error = ether_ioctl(ifp, cmd, data);
6784 		break;
6785 	default:
6786 		error = EINVAL;
6787 		break;
6788 	}
6789 	return error;
6790 #undef IS_RUNNING
6791 }
6792 
6793 /*
6794  * Announce various information on device/driver attach.
6795  */
6796 static void
6797 ath_announce(struct ath_softc *sc)
6798 {
6799 	struct ath_hal *ah = sc->sc_ah;
6800 
6801 	device_printf(sc->sc_dev, "AR%s mac %d.%d RF%s phy %d.%d\n",
6802 		ath_hal_mac_name(ah), ah->ah_macVersion, ah->ah_macRev,
6803 		ath_hal_rf_name(ah), ah->ah_phyRev >> 4, ah->ah_phyRev & 0xf);
6804 	device_printf(sc->sc_dev, "2GHz radio: 0x%.4x; 5GHz radio: 0x%.4x\n",
6805 		ah->ah_analog2GhzRev, ah->ah_analog5GhzRev);
6806 	if (bootverbose) {
6807 		int i;
6808 		for (i = 0; i <= WME_AC_VO; i++) {
6809 			struct ath_txq *txq = sc->sc_ac2q[i];
6810 			device_printf(sc->sc_dev,
6811 			    "Use hw queue %u for %s traffic\n",
6812 			    txq->axq_qnum, ieee80211_wme_acnames[i]);
6813 		}
6814 		device_printf(sc->sc_dev, "Use hw queue %u for CAB traffic\n",
6815 		    sc->sc_cabq->axq_qnum);
6816 		device_printf(sc->sc_dev, "Use hw queue %u for beacons\n",
6817 		    sc->sc_bhalq);
6818 	}
6819 	if (ath_rxbuf != ATH_RXBUF)
6820 		device_printf(sc->sc_dev, "using %u rx buffers\n", ath_rxbuf);
6821 	if (ath_txbuf != ATH_TXBUF)
6822 		device_printf(sc->sc_dev, "using %u tx buffers\n", ath_txbuf);
6823 	if (sc->sc_mcastkey && bootverbose)
6824 		device_printf(sc->sc_dev, "using multicast key search\n");
6825 }
6826 
6827 static void
6828 ath_dfs_tasklet(void *p, int npending)
6829 {
6830 	struct ath_softc *sc = (struct ath_softc *) p;
6831 	struct ifnet *ifp = sc->sc_ifp;
6832 	struct ieee80211com *ic = ifp->if_l2com;
6833 
6834 	/*
6835 	 * If previous processing has found a radar event,
6836 	 * signal this to the net80211 layer to begin DFS
6837 	 * processing.
6838 	 */
6839 	if (ath_dfs_process_radar_event(sc, sc->sc_curchan)) {
6840 		/* DFS event found, initiate channel change */
6841 		/*
6842 		 * XXX doesn't currently tell us whether the event
6843 		 * XXX was found in the primary or extension
6844 		 * XXX channel!
6845 		 */
6846 		IEEE80211_LOCK(ic);
6847 		ieee80211_dfs_notify_radar(ic, sc->sc_curchan);
6848 		IEEE80211_UNLOCK(ic);
6849 	}
6850 }
6851 
6852 /*
6853  * Enable/disable power save.  This must be called with
6854  * no TX driver locks currently held, so it should only
6855  * be called from the RX path (which doesn't hold any
6856  * TX driver locks.)
6857  */
6858 static void
6859 ath_node_powersave(struct ieee80211_node *ni, int enable)
6860 {
6861 #ifdef	ATH_SW_PSQ
6862 	struct ath_node *an = ATH_NODE(ni);
6863 	struct ieee80211com *ic = ni->ni_ic;
6864 	struct ath_softc *sc = ic->ic_ifp->if_softc;
6865 	struct ath_vap *avp = ATH_VAP(ni->ni_vap);
6866 
6867 	/* XXX and no TXQ locks should be held here */
6868 
6869 	DPRINTF(sc, ATH_DEBUG_NODE_PWRSAVE, "%s: %6D: enable=%d\n",
6870 	    __func__,
6871 	    ni->ni_macaddr,
6872 	    ":",
6873 	    !! enable);
6874 
6875 	/* Suspend or resume software queue handling */
6876 	if (enable)
6877 		ath_tx_node_sleep(sc, an);
6878 	else
6879 		ath_tx_node_wakeup(sc, an);
6880 
6881 	/* Update net80211 state */
6882 	avp->av_node_ps(ni, enable);
6883 #else
6884 	struct ath_vap *avp = ATH_VAP(ni->ni_vap);
6885 
6886 	/* Update net80211 state */
6887 	avp->av_node_ps(ni, enable);
6888 #endif/* ATH_SW_PSQ */
6889 }
6890 
6891 /*
6892  * Notification from net80211 that the powersave queue state has
6893  * changed.
6894  *
6895  * Since the software queue also may have some frames:
6896  *
6897  * + if the node software queue has frames and the TID state
6898  *   is 0, we set the TIM;
6899  * + if the node and the stack are both empty, we clear the TIM bit.
6900  * + If the stack tries to set the bit, always set it.
6901  * + If the stack tries to clear the bit, only clear it if the
6902  *   software queue in question is also cleared.
6903  *
6904  * TODO: this is called during node teardown; so let's ensure this
6905  * is all correctly handled and that the TIM bit is cleared.
6906  * It may be that the node flush is called _AFTER_ the net80211
6907  * stack clears the TIM.
6908  *
6909  * Here is the racy part.  Since it's possible >1 concurrent,
6910  * overlapping TXes will appear complete with a TX completion in
6911  * another thread, it's possible that the concurrent TIM calls will
6912  * clash.  We can't hold the node lock here because setting the
6913  * TIM grabs the net80211 comlock and this may cause a LOR.
6914  * The solution is either to totally serialise _everything_ at
6915  * this point (ie, all TX, completion and any reset/flush go into
6916  * one taskqueue) or a new "ath TIM lock" needs to be created that
6917  * just wraps the driver state change and this call to avp->av_set_tim().
6918  *
6919  * The same race exists in the net80211 power save queue handling
6920  * as well.  Since multiple transmitting threads may queue frames
6921  * into the driver, as well as ps-poll and the driver transmitting
6922  * frames (and thus clearing the psq), it's quite possible that
6923  * a packet entering the PSQ and a ps-poll being handled will
6924  * race, causing the TIM to be cleared and not re-set.
6925  */
6926 static int
6927 ath_node_set_tim(struct ieee80211_node *ni, int enable)
6928 {
6929 #ifdef	ATH_SW_PSQ
6930 	struct ieee80211com *ic = ni->ni_ic;
6931 	struct ath_softc *sc = ic->ic_ifp->if_softc;
6932 	struct ath_node *an = ATH_NODE(ni);
6933 	struct ath_vap *avp = ATH_VAP(ni->ni_vap);
6934 	int changed = 0;
6935 
6936 	ATH_TX_LOCK(sc);
6937 	an->an_stack_psq = enable;
6938 
6939 	/*
6940 	 * This will get called for all operating modes,
6941 	 * even if avp->av_set_tim is unset.
6942 	 * It's currently set for hostap/ibss modes; but
6943 	 * the same infrastructure is used for both STA
6944 	 * and AP/IBSS node power save.
6945 	 */
6946 	if (avp->av_set_tim == NULL) {
6947 		ATH_TX_UNLOCK(sc);
6948 		return (0);
6949 	}
6950 
6951 	/*
6952 	 * If setting the bit, always set it here.
6953 	 * If clearing the bit, only clear it if the
6954 	 * software queue is also empty.
6955 	 *
6956 	 * If the node has left power save, just clear the TIM
6957 	 * bit regardless of the state of the power save queue.
6958 	 *
6959 	 * XXX TODO: although atomics are used, it's quite possible
6960 	 * that a race will occur between this and setting/clearing
6961 	 * in another thread.  TX completion will occur always in
6962 	 * one thread, however setting/clearing the TIM bit can come
6963 	 * from a variety of different process contexts!
6964 	 */
6965 	if (enable && an->an_tim_set == 1) {
6966 		DPRINTF(sc, ATH_DEBUG_NODE_PWRSAVE,
6967 		    "%s: %6D: enable=%d, tim_set=1, ignoring\n",
6968 		    __func__,
6969 		    ni->ni_macaddr,
6970 		    ":",
6971 		    enable);
6972 		ATH_TX_UNLOCK(sc);
6973 	} else if (enable) {
6974 		DPRINTF(sc, ATH_DEBUG_NODE_PWRSAVE,
6975 		    "%s: %6D: enable=%d, enabling TIM\n",
6976 		    __func__,
6977 		    ni->ni_macaddr,
6978 		    ":",
6979 		    enable);
6980 		an->an_tim_set = 1;
6981 		ATH_TX_UNLOCK(sc);
6982 		changed = avp->av_set_tim(ni, enable);
6983 	} else if (an->an_swq_depth == 0) {
6984 		/* disable */
6985 		DPRINTF(sc, ATH_DEBUG_NODE_PWRSAVE,
6986 		    "%s: %6D: enable=%d, an_swq_depth == 0, disabling\n",
6987 		    __func__,
6988 		    ni->ni_macaddr,
6989 		    ":",
6990 		    enable);
6991 		an->an_tim_set = 0;
6992 		ATH_TX_UNLOCK(sc);
6993 		changed = avp->av_set_tim(ni, enable);
6994 	} else if (! an->an_is_powersave) {
6995 		/*
6996 		 * disable regardless; the node isn't in powersave now
6997 		 */
6998 		DPRINTF(sc, ATH_DEBUG_NODE_PWRSAVE,
6999 		    "%s: %6D: enable=%d, an_pwrsave=0, disabling\n",
7000 		    __func__,
7001 		    ni->ni_macaddr,
7002 		    ":",
7003 		    enable);
7004 		an->an_tim_set = 0;
7005 		ATH_TX_UNLOCK(sc);
7006 		changed = avp->av_set_tim(ni, enable);
7007 	} else {
7008 		/*
7009 		 * psq disable, node is currently in powersave, node
7010 		 * software queue isn't empty, so don't clear the TIM bit
7011 		 * for now.
7012 		 */
7013 		ATH_TX_UNLOCK(sc);
7014 		DPRINTF(sc, ATH_DEBUG_NODE_PWRSAVE,
7015 		    "%s: %6D: enable=%d, an_swq_depth > 0, ignoring\n",
7016 		    __func__,
7017 		    ni->ni_macaddr,
7018 		    ":",
7019 		    enable);
7020 		changed = 0;
7021 	}
7022 
7023 	return (changed);
7024 #else
7025 	struct ath_vap *avp = ATH_VAP(ni->ni_vap);
7026 
7027 	/*
7028 	 * Some operating modes don't set av_set_tim(), so don't
7029 	 * update it here.
7030 	 */
7031 	if (avp->av_set_tim == NULL)
7032 		return (0);
7033 
7034 	return (avp->av_set_tim(ni, enable));
7035 #endif /* ATH_SW_PSQ */
7036 }
7037 
7038 /*
7039  * Set or update the TIM from the software queue.
7040  *
7041  * Check the software queue depth before attempting to do lock
7042  * anything; that avoids trying to obtain the lock.  Then,
7043  * re-check afterwards to ensure nothing has changed in the
7044  * meantime.
7045  *
7046  * set:   This is designed to be called from the TX path, after
7047  *        a frame has been queued; to see if the swq > 0.
7048  *
7049  * clear: This is designed to be called from the buffer completion point
7050  *        (right now it's ath_tx_default_comp()) where the state of
7051  *        a software queue has changed.
7052  *
7053  * It makes sense to place it at buffer free / completion rather
7054  * than after each software queue operation, as there's no real
7055  * point in churning the TIM bit as the last frames in the software
7056  * queue are transmitted.  If they fail and we retry them, we'd
7057  * just be setting the TIM bit again anyway.
7058  */
7059 void
7060 ath_tx_update_tim(struct ath_softc *sc, struct ieee80211_node *ni,
7061      int enable)
7062 {
7063 #ifdef	ATH_SW_PSQ
7064 	struct ath_node *an;
7065 	struct ath_vap *avp;
7066 
7067 	/* Don't do this for broadcast/etc frames */
7068 	if (ni == NULL)
7069 		return;
7070 
7071 	an = ATH_NODE(ni);
7072 	avp = ATH_VAP(ni->ni_vap);
7073 
7074 	/*
7075 	 * And for operating modes without the TIM handler set, let's
7076 	 * just skip those.
7077 	 */
7078 	if (avp->av_set_tim == NULL)
7079 		return;
7080 
7081 	ATH_TX_LOCK_ASSERT(sc);
7082 
7083 	if (enable) {
7084 		if (an->an_is_powersave &&
7085 		    an->an_tim_set == 0 &&
7086 		    an->an_swq_depth != 0) {
7087 			DPRINTF(sc, ATH_DEBUG_NODE_PWRSAVE,
7088 			    "%s: %6D: swq_depth>0, tim_set=0, set!\n",
7089 			    __func__,
7090 			    ni->ni_macaddr,
7091 			    ":");
7092 			an->an_tim_set = 1;
7093 			(void) avp->av_set_tim(ni, 1);
7094 		}
7095 	} else {
7096 		/*
7097 		 * Don't bother grabbing the lock unless the queue is empty.
7098 		 */
7099 		if (an->an_swq_depth != 0)
7100 			return;
7101 
7102 		if (an->an_is_powersave &&
7103 		    an->an_stack_psq == 0 &&
7104 		    an->an_tim_set == 1 &&
7105 		    an->an_swq_depth == 0) {
7106 			DPRINTF(sc, ATH_DEBUG_NODE_PWRSAVE,
7107 			    "%s: %6D: swq_depth=0, tim_set=1, psq_set=0,"
7108 			    " clear!\n",
7109 			    __func__,
7110 			    ni->ni_macaddr,
7111 			    ":");
7112 			an->an_tim_set = 0;
7113 			(void) avp->av_set_tim(ni, 0);
7114 		}
7115 	}
7116 #else
7117 	return;
7118 #endif	/* ATH_SW_PSQ */
7119 }
7120 
7121 /*
7122  * Received a ps-poll frame from net80211.
7123  *
7124  * Here we get a chance to serve out a software-queued frame ourselves
7125  * before we punt it to net80211 to transmit us one itself - either
7126  * because there's traffic in the net80211 psq, or a NULL frame to
7127  * indicate there's nothing else.
7128  */
7129 static void
7130 ath_node_recv_pspoll(struct ieee80211_node *ni, struct mbuf *m)
7131 {
7132 #ifdef	ATH_SW_PSQ
7133 	struct ath_node *an;
7134 	struct ath_vap *avp;
7135 	struct ieee80211com *ic = ni->ni_ic;
7136 	struct ath_softc *sc = ic->ic_ifp->if_softc;
7137 	int tid;
7138 
7139 	/* Just paranoia */
7140 	if (ni == NULL)
7141 		return;
7142 
7143 	/*
7144 	 * Unassociated (temporary node) station.
7145 	 */
7146 	if (ni->ni_associd == 0)
7147 		return;
7148 
7149 	/*
7150 	 * We do have an active node, so let's begin looking into it.
7151 	 */
7152 	an = ATH_NODE(ni);
7153 	avp = ATH_VAP(ni->ni_vap);
7154 
7155 	/*
7156 	 * For now, we just call the original ps-poll method.
7157 	 * Once we're ready to flip this on:
7158 	 *
7159 	 * + Set leak to 1, as no matter what we're going to have
7160 	 *   to send a frame;
7161 	 * + Check the software queue and if there's something in it,
7162 	 *   schedule the highest TID thas has traffic from this node.
7163 	 *   Then make sure we schedule the software scheduler to
7164 	 *   run so it picks up said frame.
7165 	 *
7166 	 * That way whatever happens, we'll at least send _a_ frame
7167 	 * to the given node.
7168 	 *
7169 	 * Again, yes, it's crappy QoS if the node has multiple
7170 	 * TIDs worth of traffic - but let's get it working first
7171 	 * before we optimise it.
7172 	 *
7173 	 * Also yes, there's definitely latency here - we're not
7174 	 * direct dispatching to the hardware in this path (and
7175 	 * we're likely being called from the packet receive path,
7176 	 * so going back into TX may be a little hairy!) but again
7177 	 * I'd like to get this working first before optimising
7178 	 * turn-around time.
7179 	 */
7180 
7181 	ATH_TX_LOCK(sc);
7182 
7183 	/*
7184 	 * Legacy - we're called and the node isn't asleep.
7185 	 * Immediately punt.
7186 	 */
7187 	if (! an->an_is_powersave) {
7188 		DPRINTF(sc, ATH_DEBUG_NODE_PWRSAVE,
7189 		    "%s: %6D: not in powersave?\n",
7190 		    __func__,
7191 		    ni->ni_macaddr,
7192 		    ":");
7193 		ATH_TX_UNLOCK(sc);
7194 		avp->av_recv_pspoll(ni, m);
7195 		return;
7196 	}
7197 
7198 	/*
7199 	 * We're in powersave.
7200 	 *
7201 	 * Leak a frame.
7202 	 */
7203 	an->an_leak_count = 1;
7204 
7205 	/*
7206 	 * Now, if there's no frames in the node, just punt to
7207 	 * recv_pspoll.
7208 	 *
7209 	 * Don't bother checking if the TIM bit is set, we really
7210 	 * only care if there are any frames here!
7211 	 */
7212 	if (an->an_swq_depth == 0) {
7213 		ATH_TX_UNLOCK(sc);
7214 		DPRINTF(sc, ATH_DEBUG_NODE_PWRSAVE,
7215 		    "%s: %6D: SWQ empty; punting to net80211\n",
7216 		    __func__,
7217 		    ni->ni_macaddr,
7218 		    ":");
7219 		avp->av_recv_pspoll(ni, m);
7220 		return;
7221 	}
7222 
7223 	/*
7224 	 * Ok, let's schedule the highest TID that has traffic
7225 	 * and then schedule something.
7226 	 */
7227 	for (tid = IEEE80211_TID_SIZE - 1; tid >= 0; tid--) {
7228 		struct ath_tid *atid = &an->an_tid[tid];
7229 		/*
7230 		 * No frames? Skip.
7231 		 */
7232 		if (atid->axq_depth == 0)
7233 			continue;
7234 		ath_tx_tid_sched(sc, atid);
7235 		/*
7236 		 * XXX we could do a direct call to the TXQ
7237 		 * scheduler code here to optimise latency
7238 		 * at the expense of a REALLY deep callstack.
7239 		 */
7240 		ATH_TX_UNLOCK(sc);
7241 		taskqueue_enqueue(sc->sc_tq, &sc->sc_txqtask);
7242 		DPRINTF(sc, ATH_DEBUG_NODE_PWRSAVE,
7243 		    "%s: %6D: leaking frame to TID %d\n",
7244 		    __func__,
7245 		    ni->ni_macaddr,
7246 		    ":",
7247 		    tid);
7248 		return;
7249 	}
7250 
7251 	ATH_TX_UNLOCK(sc);
7252 
7253 	/*
7254 	 * XXX nothing in the TIDs at this point? Eek.
7255 	 */
7256 	DPRINTF(sc, ATH_DEBUG_NODE_PWRSAVE,
7257 	    "%s: %6D: TIDs empty, but ath_node showed traffic?!\n",
7258 	    __func__,
7259 	    ni->ni_macaddr,
7260 	    ":");
7261 	avp->av_recv_pspoll(ni, m);
7262 #else
7263 	avp->av_recv_pspoll(ni, m);
7264 #endif	/* ATH_SW_PSQ */
7265 }
7266 
7267 MODULE_VERSION(if_ath, 1);
7268 MODULE_DEPEND(if_ath, wlan, 1, 1, 1);          /* 802.11 media layer */
7269 #if	defined(IEEE80211_ALQ) || defined(AH_DEBUG_ALQ) || defined(ATH_DEBUG_ALQ)
7270 MODULE_DEPEND(if_ath, alq, 1, 1, 1);
7271 #endif
7272