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