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