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