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