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