xref: /freebsd/sys/dev/ath/if_ath.c (revision 5608fd23c27fa1e8ee595d7b678cbfd35d657fbe)
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 
4431 	ATH_TX_UNLOCK_ASSERT(sc);
4432 	ATH_TXQ_UNLOCK_ASSERT(txq);
4433 
4434 	/* If unicast frame, update general statistics */
4435 	if (ni != NULL) {
4436 		/* update statistics */
4437 		ath_tx_update_stats(sc, ts, bf);
4438 	}
4439 
4440 	/*
4441 	 * Call the completion handler.
4442 	 * The completion handler is responsible for
4443 	 * calling the rate control code.
4444 	 *
4445 	 * Frames with no completion handler get the
4446 	 * rate control code called here.
4447 	 */
4448 	if (bf->bf_comp == NULL) {
4449 		if ((ts->ts_status & HAL_TXERR_FILT) == 0 &&
4450 		    (bf->bf_state.bfs_txflags & HAL_TXDESC_NOACK) == 0) {
4451 			/*
4452 			 * XXX assume this isn't an aggregate
4453 			 * frame.
4454 			 */
4455 			ath_tx_update_ratectrl(sc, ni,
4456 			     bf->bf_state.bfs_rc, ts,
4457 			    bf->bf_state.bfs_pktlen, 1,
4458 			    (ts->ts_status == 0 ? 0 : 1));
4459 		}
4460 		ath_tx_default_comp(sc, bf, 0);
4461 	} else
4462 		bf->bf_comp(sc, bf, 0);
4463 }
4464 
4465 
4466 
4467 /*
4468  * Process completed xmit descriptors from the specified queue.
4469  * Kick the packet scheduler if needed. This can occur from this
4470  * particular task.
4471  */
4472 static int
4473 ath_tx_processq(struct ath_softc *sc, struct ath_txq *txq, int dosched)
4474 {
4475 	struct ath_hal *ah = sc->sc_ah;
4476 	struct ath_buf *bf;
4477 	struct ath_desc *ds;
4478 	struct ath_tx_status *ts;
4479 	struct ieee80211_node *ni;
4480 #ifdef	IEEE80211_SUPPORT_SUPERG
4481 	struct ieee80211com *ic = sc->sc_ifp->if_l2com;
4482 #endif	/* IEEE80211_SUPPORT_SUPERG */
4483 	int nacked;
4484 	HAL_STATUS status;
4485 
4486 	DPRINTF(sc, ATH_DEBUG_TX_PROC, "%s: tx queue %u head %p link %p\n",
4487 		__func__, txq->axq_qnum,
4488 		(caddr_t)(uintptr_t) ath_hal_gettxbuf(sc->sc_ah, txq->axq_qnum),
4489 		txq->axq_link);
4490 
4491 	ATH_KTR(sc, ATH_KTR_TXCOMP, 4,
4492 	    "ath_tx_processq: txq=%u head %p link %p depth %p",
4493 	    txq->axq_qnum,
4494 	    (caddr_t)(uintptr_t) ath_hal_gettxbuf(sc->sc_ah, txq->axq_qnum),
4495 	    txq->axq_link,
4496 	    txq->axq_depth);
4497 
4498 	nacked = 0;
4499 	for (;;) {
4500 		ATH_TXQ_LOCK(txq);
4501 		txq->axq_intrcnt = 0;	/* reset periodic desc intr count */
4502 		bf = TAILQ_FIRST(&txq->axq_q);
4503 		if (bf == NULL) {
4504 			ATH_TXQ_UNLOCK(txq);
4505 			break;
4506 		}
4507 		ds = bf->bf_lastds;	/* XXX must be setup correctly! */
4508 		ts = &bf->bf_status.ds_txstat;
4509 
4510 		status = ath_hal_txprocdesc(ah, ds, ts);
4511 #ifdef ATH_DEBUG
4512 		if (sc->sc_debug & ATH_DEBUG_XMIT_DESC)
4513 			ath_printtxbuf(sc, bf, txq->axq_qnum, 0,
4514 			    status == HAL_OK);
4515 		else if ((sc->sc_debug & ATH_DEBUG_RESET) && (dosched == 0))
4516 			ath_printtxbuf(sc, bf, txq->axq_qnum, 0,
4517 			    status == HAL_OK);
4518 #endif
4519 #ifdef	ATH_DEBUG_ALQ
4520 		if (if_ath_alq_checkdebug(&sc->sc_alq,
4521 		    ATH_ALQ_EDMA_TXSTATUS)) {
4522 			if_ath_alq_post(&sc->sc_alq, ATH_ALQ_EDMA_TXSTATUS,
4523 			sc->sc_tx_statuslen,
4524 			(char *) ds);
4525 		}
4526 #endif
4527 
4528 		if (status == HAL_EINPROGRESS) {
4529 			ATH_KTR(sc, ATH_KTR_TXCOMP, 3,
4530 			    "ath_tx_processq: txq=%u, bf=%p ds=%p, HAL_EINPROGRESS",
4531 			    txq->axq_qnum, bf, ds);
4532 			ATH_TXQ_UNLOCK(txq);
4533 			break;
4534 		}
4535 		ATH_TXQ_REMOVE(txq, bf, bf_list);
4536 
4537 		/*
4538 		 * Sanity check.
4539 		 */
4540 		if (txq->axq_qnum != bf->bf_state.bfs_tx_queue) {
4541 			device_printf(sc->sc_dev,
4542 			    "%s: TXQ=%d: bf=%p, bfs_tx_queue=%d\n",
4543 			    __func__,
4544 			    txq->axq_qnum,
4545 			    bf,
4546 			    bf->bf_state.bfs_tx_queue);
4547 		}
4548 		if (txq->axq_qnum != bf->bf_last->bf_state.bfs_tx_queue) {
4549 			device_printf(sc->sc_dev,
4550 			    "%s: TXQ=%d: bf_last=%p, bfs_tx_queue=%d\n",
4551 			    __func__,
4552 			    txq->axq_qnum,
4553 			    bf->bf_last,
4554 			    bf->bf_last->bf_state.bfs_tx_queue);
4555 		}
4556 
4557 #if 0
4558 		if (txq->axq_depth > 0) {
4559 			/*
4560 			 * More frames follow.  Mark the buffer busy
4561 			 * so it's not re-used while the hardware may
4562 			 * still re-read the link field in the descriptor.
4563 			 *
4564 			 * Use the last buffer in an aggregate as that
4565 			 * is where the hardware may be - intermediate
4566 			 * descriptors won't be "busy".
4567 			 */
4568 			bf->bf_last->bf_flags |= ATH_BUF_BUSY;
4569 		} else
4570 			txq->axq_link = NULL;
4571 #else
4572 		bf->bf_last->bf_flags |= ATH_BUF_BUSY;
4573 #endif
4574 		if (bf->bf_state.bfs_aggr)
4575 			txq->axq_aggr_depth--;
4576 
4577 		ni = bf->bf_node;
4578 
4579 		ATH_KTR(sc, ATH_KTR_TXCOMP, 5,
4580 		    "ath_tx_processq: txq=%u, bf=%p, ds=%p, ni=%p, ts_status=0x%08x",
4581 		    txq->axq_qnum, bf, ds, ni, ts->ts_status);
4582 		/*
4583 		 * If unicast frame was ack'd update RSSI,
4584 		 * including the last rx time used to
4585 		 * workaround phantom bmiss interrupts.
4586 		 */
4587 		if (ni != NULL && ts->ts_status == 0 &&
4588 		    ((bf->bf_state.bfs_txflags & HAL_TXDESC_NOACK) == 0)) {
4589 			nacked++;
4590 			sc->sc_stats.ast_tx_rssi = ts->ts_rssi;
4591 			ATH_RSSI_LPF(sc->sc_halstats.ns_avgtxrssi,
4592 				ts->ts_rssi);
4593 		}
4594 		ATH_TXQ_UNLOCK(txq);
4595 
4596 		/*
4597 		 * Update statistics and call completion
4598 		 */
4599 		ath_tx_process_buf_completion(sc, txq, ts, bf);
4600 
4601 		/* XXX at this point, bf and ni may be totally invalid */
4602 	}
4603 #ifdef IEEE80211_SUPPORT_SUPERG
4604 	/*
4605 	 * Flush fast-frame staging queue when traffic slows.
4606 	 */
4607 	if (txq->axq_depth <= 1)
4608 		ieee80211_ff_flush(ic, txq->axq_ac);
4609 #endif
4610 
4611 	/* Kick the software TXQ scheduler */
4612 	if (dosched) {
4613 		ATH_TX_LOCK(sc);
4614 		ath_txq_sched(sc, txq);
4615 		ATH_TX_UNLOCK(sc);
4616 	}
4617 
4618 	ATH_KTR(sc, ATH_KTR_TXCOMP, 1,
4619 	    "ath_tx_processq: txq=%u: done",
4620 	    txq->axq_qnum);
4621 
4622 	return nacked;
4623 }
4624 
4625 #define	TXQACTIVE(t, q)		( (t) & (1 << (q)))
4626 
4627 /*
4628  * Deferred processing of transmit interrupt; special-cased
4629  * for a single hardware transmit queue (e.g. 5210 and 5211).
4630  */
4631 static void
4632 ath_tx_proc_q0(void *arg, int npending)
4633 {
4634 	struct ath_softc *sc = arg;
4635 	struct ifnet *ifp = sc->sc_ifp;
4636 	uint32_t txqs;
4637 
4638 	ATH_PCU_LOCK(sc);
4639 	sc->sc_txproc_cnt++;
4640 	txqs = sc->sc_txq_active;
4641 	sc->sc_txq_active &= ~txqs;
4642 	ATH_PCU_UNLOCK(sc);
4643 
4644 	ATH_LOCK(sc);
4645 	ath_power_set_power_state(sc, HAL_PM_AWAKE);
4646 	ATH_UNLOCK(sc);
4647 
4648 	ATH_KTR(sc, ATH_KTR_TXCOMP, 1,
4649 	    "ath_tx_proc_q0: txqs=0x%08x", txqs);
4650 
4651 	if (TXQACTIVE(txqs, 0) && ath_tx_processq(sc, &sc->sc_txq[0], 1))
4652 		/* XXX why is lastrx updated in tx code? */
4653 		sc->sc_lastrx = ath_hal_gettsf64(sc->sc_ah);
4654 	if (TXQACTIVE(txqs, sc->sc_cabq->axq_qnum))
4655 		ath_tx_processq(sc, sc->sc_cabq, 1);
4656 	IF_LOCK(&ifp->if_snd);
4657 	ifp->if_drv_flags &= ~IFF_DRV_OACTIVE;
4658 	IF_UNLOCK(&ifp->if_snd);
4659 	sc->sc_wd_timer = 0;
4660 
4661 	if (sc->sc_softled)
4662 		ath_led_event(sc, sc->sc_txrix);
4663 
4664 	ATH_PCU_LOCK(sc);
4665 	sc->sc_txproc_cnt--;
4666 	ATH_PCU_UNLOCK(sc);
4667 
4668 	ATH_LOCK(sc);
4669 	ath_power_restore_power_state(sc);
4670 	ATH_UNLOCK(sc);
4671 
4672 	ath_tx_kick(sc);
4673 }
4674 
4675 /*
4676  * Deferred processing of transmit interrupt; special-cased
4677  * for four hardware queues, 0-3 (e.g. 5212 w/ WME support).
4678  */
4679 static void
4680 ath_tx_proc_q0123(void *arg, int npending)
4681 {
4682 	struct ath_softc *sc = arg;
4683 	struct ifnet *ifp = sc->sc_ifp;
4684 	int nacked;
4685 	uint32_t txqs;
4686 
4687 	ATH_PCU_LOCK(sc);
4688 	sc->sc_txproc_cnt++;
4689 	txqs = sc->sc_txq_active;
4690 	sc->sc_txq_active &= ~txqs;
4691 	ATH_PCU_UNLOCK(sc);
4692 
4693 	ATH_LOCK(sc);
4694 	ath_power_set_power_state(sc, HAL_PM_AWAKE);
4695 	ATH_UNLOCK(sc);
4696 
4697 	ATH_KTR(sc, ATH_KTR_TXCOMP, 1,
4698 	    "ath_tx_proc_q0123: txqs=0x%08x", txqs);
4699 
4700 	/*
4701 	 * Process each active queue.
4702 	 */
4703 	nacked = 0;
4704 	if (TXQACTIVE(txqs, 0))
4705 		nacked += ath_tx_processq(sc, &sc->sc_txq[0], 1);
4706 	if (TXQACTIVE(txqs, 1))
4707 		nacked += ath_tx_processq(sc, &sc->sc_txq[1], 1);
4708 	if (TXQACTIVE(txqs, 2))
4709 		nacked += ath_tx_processq(sc, &sc->sc_txq[2], 1);
4710 	if (TXQACTIVE(txqs, 3))
4711 		nacked += ath_tx_processq(sc, &sc->sc_txq[3], 1);
4712 	if (TXQACTIVE(txqs, sc->sc_cabq->axq_qnum))
4713 		ath_tx_processq(sc, sc->sc_cabq, 1);
4714 	if (nacked)
4715 		sc->sc_lastrx = ath_hal_gettsf64(sc->sc_ah);
4716 
4717 	IF_LOCK(&ifp->if_snd);
4718 	ifp->if_drv_flags &= ~IFF_DRV_OACTIVE;
4719 	IF_UNLOCK(&ifp->if_snd);
4720 	sc->sc_wd_timer = 0;
4721 
4722 	if (sc->sc_softled)
4723 		ath_led_event(sc, sc->sc_txrix);
4724 
4725 	ATH_PCU_LOCK(sc);
4726 	sc->sc_txproc_cnt--;
4727 	ATH_PCU_UNLOCK(sc);
4728 
4729 	ATH_LOCK(sc);
4730 	ath_power_restore_power_state(sc);
4731 	ATH_UNLOCK(sc);
4732 
4733 	ath_tx_kick(sc);
4734 }
4735 
4736 /*
4737  * Deferred processing of transmit interrupt.
4738  */
4739 static void
4740 ath_tx_proc(void *arg, int npending)
4741 {
4742 	struct ath_softc *sc = arg;
4743 	struct ifnet *ifp = sc->sc_ifp;
4744 	int i, nacked;
4745 	uint32_t txqs;
4746 
4747 	ATH_PCU_LOCK(sc);
4748 	sc->sc_txproc_cnt++;
4749 	txqs = sc->sc_txq_active;
4750 	sc->sc_txq_active &= ~txqs;
4751 	ATH_PCU_UNLOCK(sc);
4752 
4753 	ATH_LOCK(sc);
4754 	ath_power_set_power_state(sc, HAL_PM_AWAKE);
4755 	ATH_UNLOCK(sc);
4756 
4757 	ATH_KTR(sc, ATH_KTR_TXCOMP, 1, "ath_tx_proc: txqs=0x%08x", txqs);
4758 
4759 	/*
4760 	 * Process each active queue.
4761 	 */
4762 	nacked = 0;
4763 	for (i = 0; i < HAL_NUM_TX_QUEUES; i++)
4764 		if (ATH_TXQ_SETUP(sc, i) && TXQACTIVE(txqs, i))
4765 			nacked += ath_tx_processq(sc, &sc->sc_txq[i], 1);
4766 	if (nacked)
4767 		sc->sc_lastrx = ath_hal_gettsf64(sc->sc_ah);
4768 
4769 	/* XXX check this inside of IF_LOCK? */
4770 	IF_LOCK(&ifp->if_snd);
4771 	ifp->if_drv_flags &= ~IFF_DRV_OACTIVE;
4772 	IF_UNLOCK(&ifp->if_snd);
4773 	sc->sc_wd_timer = 0;
4774 
4775 	if (sc->sc_softled)
4776 		ath_led_event(sc, sc->sc_txrix);
4777 
4778 	ATH_PCU_LOCK(sc);
4779 	sc->sc_txproc_cnt--;
4780 	ATH_PCU_UNLOCK(sc);
4781 
4782 	ATH_LOCK(sc);
4783 	ath_power_restore_power_state(sc);
4784 	ATH_UNLOCK(sc);
4785 
4786 	ath_tx_kick(sc);
4787 }
4788 #undef	TXQACTIVE
4789 
4790 /*
4791  * Deferred processing of TXQ rescheduling.
4792  */
4793 static void
4794 ath_txq_sched_tasklet(void *arg, int npending)
4795 {
4796 	struct ath_softc *sc = arg;
4797 	int i;
4798 
4799 	/* XXX is skipping ok? */
4800 	ATH_PCU_LOCK(sc);
4801 #if 0
4802 	if (sc->sc_inreset_cnt > 0) {
4803 		device_printf(sc->sc_dev,
4804 		    "%s: sc_inreset_cnt > 0; skipping\n", __func__);
4805 		ATH_PCU_UNLOCK(sc);
4806 		return;
4807 	}
4808 #endif
4809 	sc->sc_txproc_cnt++;
4810 	ATH_PCU_UNLOCK(sc);
4811 
4812 	ATH_LOCK(sc);
4813 	ath_power_set_power_state(sc, HAL_PM_AWAKE);
4814 	ATH_UNLOCK(sc);
4815 
4816 	ATH_TX_LOCK(sc);
4817 	for (i = 0; i < HAL_NUM_TX_QUEUES; i++) {
4818 		if (ATH_TXQ_SETUP(sc, i)) {
4819 			ath_txq_sched(sc, &sc->sc_txq[i]);
4820 		}
4821 	}
4822 	ATH_TX_UNLOCK(sc);
4823 
4824 	ATH_LOCK(sc);
4825 	ath_power_restore_power_state(sc);
4826 	ATH_UNLOCK(sc);
4827 
4828 	ATH_PCU_LOCK(sc);
4829 	sc->sc_txproc_cnt--;
4830 	ATH_PCU_UNLOCK(sc);
4831 }
4832 
4833 void
4834 ath_returnbuf_tail(struct ath_softc *sc, struct ath_buf *bf)
4835 {
4836 
4837 	ATH_TXBUF_LOCK_ASSERT(sc);
4838 
4839 	if (bf->bf_flags & ATH_BUF_MGMT)
4840 		TAILQ_INSERT_TAIL(&sc->sc_txbuf_mgmt, bf, bf_list);
4841 	else {
4842 		TAILQ_INSERT_TAIL(&sc->sc_txbuf, bf, bf_list);
4843 		sc->sc_txbuf_cnt++;
4844 		if (sc->sc_txbuf_cnt > ath_txbuf) {
4845 			device_printf(sc->sc_dev,
4846 			    "%s: sc_txbuf_cnt > %d?\n",
4847 			    __func__,
4848 			    ath_txbuf);
4849 			sc->sc_txbuf_cnt = ath_txbuf;
4850 		}
4851 	}
4852 }
4853 
4854 void
4855 ath_returnbuf_head(struct ath_softc *sc, struct ath_buf *bf)
4856 {
4857 
4858 	ATH_TXBUF_LOCK_ASSERT(sc);
4859 
4860 	if (bf->bf_flags & ATH_BUF_MGMT)
4861 		TAILQ_INSERT_HEAD(&sc->sc_txbuf_mgmt, bf, bf_list);
4862 	else {
4863 		TAILQ_INSERT_HEAD(&sc->sc_txbuf, bf, bf_list);
4864 		sc->sc_txbuf_cnt++;
4865 		if (sc->sc_txbuf_cnt > ATH_TXBUF) {
4866 			device_printf(sc->sc_dev,
4867 			    "%s: sc_txbuf_cnt > %d?\n",
4868 			    __func__,
4869 			    ATH_TXBUF);
4870 			sc->sc_txbuf_cnt = ATH_TXBUF;
4871 		}
4872 	}
4873 }
4874 
4875 /*
4876  * Free the holding buffer if it exists
4877  */
4878 void
4879 ath_txq_freeholdingbuf(struct ath_softc *sc, struct ath_txq *txq)
4880 {
4881 	ATH_TXBUF_UNLOCK_ASSERT(sc);
4882 	ATH_TXQ_LOCK_ASSERT(txq);
4883 
4884 	if (txq->axq_holdingbf == NULL)
4885 		return;
4886 
4887 	txq->axq_holdingbf->bf_flags &= ~ATH_BUF_BUSY;
4888 
4889 	ATH_TXBUF_LOCK(sc);
4890 	ath_returnbuf_tail(sc, txq->axq_holdingbf);
4891 	ATH_TXBUF_UNLOCK(sc);
4892 
4893 	txq->axq_holdingbf = NULL;
4894 }
4895 
4896 /*
4897  * Add this buffer to the holding queue, freeing the previous
4898  * one if it exists.
4899  */
4900 static void
4901 ath_txq_addholdingbuf(struct ath_softc *sc, struct ath_buf *bf)
4902 {
4903 	struct ath_txq *txq;
4904 
4905 	txq = &sc->sc_txq[bf->bf_state.bfs_tx_queue];
4906 
4907 	ATH_TXBUF_UNLOCK_ASSERT(sc);
4908 	ATH_TXQ_LOCK_ASSERT(txq);
4909 
4910 	/* XXX assert ATH_BUF_BUSY is set */
4911 
4912 	/* XXX assert the tx queue is under the max number */
4913 	if (bf->bf_state.bfs_tx_queue > HAL_NUM_TX_QUEUES) {
4914 		device_printf(sc->sc_dev, "%s: bf=%p: invalid tx queue (%d)\n",
4915 		    __func__,
4916 		    bf,
4917 		    bf->bf_state.bfs_tx_queue);
4918 		bf->bf_flags &= ~ATH_BUF_BUSY;
4919 		ath_returnbuf_tail(sc, bf);
4920 		return;
4921 	}
4922 	ath_txq_freeholdingbuf(sc, txq);
4923 	txq->axq_holdingbf = bf;
4924 }
4925 
4926 /*
4927  * Return a buffer to the pool and update the 'busy' flag on the
4928  * previous 'tail' entry.
4929  *
4930  * This _must_ only be called when the buffer is involved in a completed
4931  * TX. The logic is that if it was part of an active TX, the previous
4932  * buffer on the list is now not involved in a halted TX DMA queue, waiting
4933  * for restart (eg for TDMA.)
4934  *
4935  * The caller must free the mbuf and recycle the node reference.
4936  *
4937  * XXX This method of handling busy / holding buffers is insanely stupid.
4938  * It requires bf_state.bfs_tx_queue to be correctly assigned.  It would
4939  * be much nicer if buffers in the processq() methods would instead be
4940  * always completed there (pushed onto a txq or ath_bufhead) so we knew
4941  * exactly what hardware queue they came from in the first place.
4942  */
4943 void
4944 ath_freebuf(struct ath_softc *sc, struct ath_buf *bf)
4945 {
4946 	struct ath_txq *txq;
4947 
4948 	txq = &sc->sc_txq[bf->bf_state.bfs_tx_queue];
4949 
4950 	KASSERT((bf->bf_node == NULL), ("%s: bf->bf_node != NULL\n", __func__));
4951 	KASSERT((bf->bf_m == NULL), ("%s: bf->bf_m != NULL\n", __func__));
4952 
4953 	/*
4954 	 * If this buffer is busy, push it onto the holding queue.
4955 	 */
4956 	if (bf->bf_flags & ATH_BUF_BUSY) {
4957 		ATH_TXQ_LOCK(txq);
4958 		ath_txq_addholdingbuf(sc, bf);
4959 		ATH_TXQ_UNLOCK(txq);
4960 		return;
4961 	}
4962 
4963 	/*
4964 	 * Not a busy buffer, so free normally
4965 	 */
4966 	ATH_TXBUF_LOCK(sc);
4967 	ath_returnbuf_tail(sc, bf);
4968 	ATH_TXBUF_UNLOCK(sc);
4969 }
4970 
4971 /*
4972  * This is currently used by ath_tx_draintxq() and
4973  * ath_tx_tid_free_pkts().
4974  *
4975  * It recycles a single ath_buf.
4976  */
4977 void
4978 ath_tx_freebuf(struct ath_softc *sc, struct ath_buf *bf, int status)
4979 {
4980 	struct ieee80211_node *ni = bf->bf_node;
4981 	struct mbuf *m0 = bf->bf_m;
4982 
4983 	/*
4984 	 * Make sure that we only sync/unload if there's an mbuf.
4985 	 * If not (eg we cloned a buffer), the unload will have already
4986 	 * occured.
4987 	 */
4988 	if (bf->bf_m != NULL) {
4989 		bus_dmamap_sync(sc->sc_dmat, bf->bf_dmamap,
4990 		    BUS_DMASYNC_POSTWRITE);
4991 		bus_dmamap_unload(sc->sc_dmat, bf->bf_dmamap);
4992 	}
4993 
4994 	bf->bf_node = NULL;
4995 	bf->bf_m = NULL;
4996 
4997 	/* Free the buffer, it's not needed any longer */
4998 	ath_freebuf(sc, bf);
4999 
5000 	/* Pass the buffer back to net80211 - completing it */
5001 	ieee80211_tx_complete(ni, m0, status);
5002 }
5003 
5004 static struct ath_buf *
5005 ath_tx_draintxq_get_one(struct ath_softc *sc, struct ath_txq *txq)
5006 {
5007 	struct ath_buf *bf;
5008 
5009 	ATH_TXQ_LOCK_ASSERT(txq);
5010 
5011 	/*
5012 	 * Drain the FIFO queue first, then if it's
5013 	 * empty, move to the normal frame queue.
5014 	 */
5015 	bf = TAILQ_FIRST(&txq->fifo.axq_q);
5016 	if (bf != NULL) {
5017 		/*
5018 		 * Is it the last buffer in this set?
5019 		 * Decrement the FIFO counter.
5020 		 */
5021 		if (bf->bf_flags & ATH_BUF_FIFOEND) {
5022 			if (txq->axq_fifo_depth == 0) {
5023 				device_printf(sc->sc_dev,
5024 				    "%s: Q%d: fifo_depth=0, fifo.axq_depth=%d?\n",
5025 				    __func__,
5026 				    txq->axq_qnum,
5027 				    txq->fifo.axq_depth);
5028 			} else
5029 				txq->axq_fifo_depth--;
5030 		}
5031 		ATH_TXQ_REMOVE(&txq->fifo, bf, bf_list);
5032 		return (bf);
5033 	}
5034 
5035 	/*
5036 	 * Debugging!
5037 	 */
5038 	if (txq->axq_fifo_depth != 0 || txq->fifo.axq_depth != 0) {
5039 		device_printf(sc->sc_dev,
5040 		    "%s: Q%d: fifo_depth=%d, fifo.axq_depth=%d\n",
5041 		    __func__,
5042 		    txq->axq_qnum,
5043 		    txq->axq_fifo_depth,
5044 		    txq->fifo.axq_depth);
5045 	}
5046 
5047 	/*
5048 	 * Now drain the pending queue.
5049 	 */
5050 	bf = TAILQ_FIRST(&txq->axq_q);
5051 	if (bf == NULL) {
5052 		txq->axq_link = NULL;
5053 		return (NULL);
5054 	}
5055 	ATH_TXQ_REMOVE(txq, bf, bf_list);
5056 	return (bf);
5057 }
5058 
5059 void
5060 ath_tx_draintxq(struct ath_softc *sc, struct ath_txq *txq)
5061 {
5062 #ifdef ATH_DEBUG
5063 	struct ath_hal *ah = sc->sc_ah;
5064 #endif
5065 	struct ath_buf *bf;
5066 	u_int ix;
5067 
5068 	/*
5069 	 * NB: this assumes output has been stopped and
5070 	 *     we do not need to block ath_tx_proc
5071 	 */
5072 	for (ix = 0;; ix++) {
5073 		ATH_TXQ_LOCK(txq);
5074 		bf = ath_tx_draintxq_get_one(sc, txq);
5075 		if (bf == NULL) {
5076 			ATH_TXQ_UNLOCK(txq);
5077 			break;
5078 		}
5079 		if (bf->bf_state.bfs_aggr)
5080 			txq->axq_aggr_depth--;
5081 #ifdef ATH_DEBUG
5082 		if (sc->sc_debug & ATH_DEBUG_RESET) {
5083 			struct ieee80211com *ic = sc->sc_ifp->if_l2com;
5084 			int status = 0;
5085 
5086 			/*
5087 			 * EDMA operation has a TX completion FIFO
5088 			 * separate from the TX descriptor, so this
5089 			 * method of checking the "completion" status
5090 			 * is wrong.
5091 			 */
5092 			if (! sc->sc_isedma) {
5093 				status = (ath_hal_txprocdesc(ah,
5094 				    bf->bf_lastds,
5095 				    &bf->bf_status.ds_txstat) == HAL_OK);
5096 			}
5097 			ath_printtxbuf(sc, bf, txq->axq_qnum, ix, status);
5098 			ieee80211_dump_pkt(ic, mtod(bf->bf_m, const uint8_t *),
5099 			    bf->bf_m->m_len, 0, -1);
5100 		}
5101 #endif /* ATH_DEBUG */
5102 		/*
5103 		 * Since we're now doing magic in the completion
5104 		 * functions, we -must- call it for aggregation
5105 		 * destinations or BAW tracking will get upset.
5106 		 */
5107 		/*
5108 		 * Clear ATH_BUF_BUSY; the completion handler
5109 		 * will free the buffer.
5110 		 */
5111 		ATH_TXQ_UNLOCK(txq);
5112 		bf->bf_flags &= ~ATH_BUF_BUSY;
5113 		if (bf->bf_comp)
5114 			bf->bf_comp(sc, bf, 1);
5115 		else
5116 			ath_tx_default_comp(sc, bf, 1);
5117 	}
5118 
5119 	/*
5120 	 * Free the holding buffer if it exists
5121 	 */
5122 	ATH_TXQ_LOCK(txq);
5123 	ath_txq_freeholdingbuf(sc, txq);
5124 	ATH_TXQ_UNLOCK(txq);
5125 
5126 	/*
5127 	 * Drain software queued frames which are on
5128 	 * active TIDs.
5129 	 */
5130 	ath_tx_txq_drain(sc, txq);
5131 }
5132 
5133 static void
5134 ath_tx_stopdma(struct ath_softc *sc, struct ath_txq *txq)
5135 {
5136 	struct ath_hal *ah = sc->sc_ah;
5137 
5138 	ATH_TXQ_LOCK_ASSERT(txq);
5139 
5140 	DPRINTF(sc, ATH_DEBUG_RESET,
5141 	    "%s: tx queue [%u] %p, active=%d, hwpending=%d, flags 0x%08x, "
5142 	    "link %p, holdingbf=%p\n",
5143 	    __func__,
5144 	    txq->axq_qnum,
5145 	    (caddr_t)(uintptr_t) ath_hal_gettxbuf(ah, txq->axq_qnum),
5146 	    (int) (!! ath_hal_txqenabled(ah, txq->axq_qnum)),
5147 	    (int) ath_hal_numtxpending(ah, txq->axq_qnum),
5148 	    txq->axq_flags,
5149 	    txq->axq_link,
5150 	    txq->axq_holdingbf);
5151 
5152 	(void) ath_hal_stoptxdma(ah, txq->axq_qnum);
5153 	/* We've stopped TX DMA, so mark this as stopped. */
5154 	txq->axq_flags &= ~ATH_TXQ_PUTRUNNING;
5155 
5156 #ifdef	ATH_DEBUG
5157 	if ((sc->sc_debug & ATH_DEBUG_RESET)
5158 	    && (txq->axq_holdingbf != NULL)) {
5159 		ath_printtxbuf(sc, txq->axq_holdingbf, txq->axq_qnum, 0, 0);
5160 	}
5161 #endif
5162 }
5163 
5164 int
5165 ath_stoptxdma(struct ath_softc *sc)
5166 {
5167 	struct ath_hal *ah = sc->sc_ah;
5168 	int i;
5169 
5170 	/* XXX return value */
5171 	if (sc->sc_invalid)
5172 		return 0;
5173 
5174 	if (!sc->sc_invalid) {
5175 		/* don't touch the hardware if marked invalid */
5176 		DPRINTF(sc, ATH_DEBUG_RESET, "%s: tx queue [%u] %p, link %p\n",
5177 		    __func__, sc->sc_bhalq,
5178 		    (caddr_t)(uintptr_t) ath_hal_gettxbuf(ah, sc->sc_bhalq),
5179 		    NULL);
5180 
5181 		/* stop the beacon queue */
5182 		(void) ath_hal_stoptxdma(ah, sc->sc_bhalq);
5183 
5184 		/* Stop the data queues */
5185 		for (i = 0; i < HAL_NUM_TX_QUEUES; i++) {
5186 			if (ATH_TXQ_SETUP(sc, i)) {
5187 				ATH_TXQ_LOCK(&sc->sc_txq[i]);
5188 				ath_tx_stopdma(sc, &sc->sc_txq[i]);
5189 				ATH_TXQ_UNLOCK(&sc->sc_txq[i]);
5190 			}
5191 		}
5192 	}
5193 
5194 	return 1;
5195 }
5196 
5197 #ifdef	ATH_DEBUG
5198 void
5199 ath_tx_dump(struct ath_softc *sc, struct ath_txq *txq)
5200 {
5201 	struct ath_hal *ah = sc->sc_ah;
5202 	struct ath_buf *bf;
5203 	int i = 0;
5204 
5205 	if (! (sc->sc_debug & ATH_DEBUG_RESET))
5206 		return;
5207 
5208 	device_printf(sc->sc_dev, "%s: Q%d: begin\n",
5209 	    __func__, txq->axq_qnum);
5210 	TAILQ_FOREACH(bf, &txq->axq_q, bf_list) {
5211 		ath_printtxbuf(sc, bf, txq->axq_qnum, i,
5212 			ath_hal_txprocdesc(ah, bf->bf_lastds,
5213 			    &bf->bf_status.ds_txstat) == HAL_OK);
5214 		i++;
5215 	}
5216 	device_printf(sc->sc_dev, "%s: Q%d: end\n",
5217 	    __func__, txq->axq_qnum);
5218 }
5219 #endif /* ATH_DEBUG */
5220 
5221 /*
5222  * Drain the transmit queues and reclaim resources.
5223  */
5224 void
5225 ath_legacy_tx_drain(struct ath_softc *sc, ATH_RESET_TYPE reset_type)
5226 {
5227 	struct ath_hal *ah = sc->sc_ah;
5228 	struct ifnet *ifp = sc->sc_ifp;
5229 	int i;
5230 	struct ath_buf *bf_last;
5231 
5232 	(void) ath_stoptxdma(sc);
5233 
5234 	/*
5235 	 * Dump the queue contents
5236 	 */
5237 	for (i = 0; i < HAL_NUM_TX_QUEUES; i++) {
5238 		/*
5239 		 * XXX TODO: should we just handle the completed TX frames
5240 		 * here, whether or not the reset is a full one or not?
5241 		 */
5242 		if (ATH_TXQ_SETUP(sc, i)) {
5243 #ifdef	ATH_DEBUG
5244 			if (sc->sc_debug & ATH_DEBUG_RESET)
5245 				ath_tx_dump(sc, &sc->sc_txq[i]);
5246 #endif	/* ATH_DEBUG */
5247 			if (reset_type == ATH_RESET_NOLOSS) {
5248 				ath_tx_processq(sc, &sc->sc_txq[i], 0);
5249 				ATH_TXQ_LOCK(&sc->sc_txq[i]);
5250 				/*
5251 				 * Free the holding buffer; DMA is now
5252 				 * stopped.
5253 				 */
5254 				ath_txq_freeholdingbuf(sc, &sc->sc_txq[i]);
5255 				/*
5256 				 * Setup the link pointer to be the
5257 				 * _last_ buffer/descriptor in the list.
5258 				 * If there's nothing in the list, set it
5259 				 * to NULL.
5260 				 */
5261 				bf_last = ATH_TXQ_LAST(&sc->sc_txq[i],
5262 				    axq_q_s);
5263 				if (bf_last != NULL) {
5264 					ath_hal_gettxdesclinkptr(ah,
5265 					    bf_last->bf_lastds,
5266 					    &sc->sc_txq[i].axq_link);
5267 				} else {
5268 					sc->sc_txq[i].axq_link = NULL;
5269 				}
5270 				ATH_TXQ_UNLOCK(&sc->sc_txq[i]);
5271 			} else
5272 				ath_tx_draintxq(sc, &sc->sc_txq[i]);
5273 		}
5274 	}
5275 #ifdef ATH_DEBUG
5276 	if (sc->sc_debug & ATH_DEBUG_RESET) {
5277 		struct ath_buf *bf = TAILQ_FIRST(&sc->sc_bbuf);
5278 		if (bf != NULL && bf->bf_m != NULL) {
5279 			ath_printtxbuf(sc, bf, sc->sc_bhalq, 0,
5280 				ath_hal_txprocdesc(ah, bf->bf_lastds,
5281 				    &bf->bf_status.ds_txstat) == HAL_OK);
5282 			ieee80211_dump_pkt(ifp->if_l2com,
5283 			    mtod(bf->bf_m, const uint8_t *), bf->bf_m->m_len,
5284 			    0, -1);
5285 		}
5286 	}
5287 #endif /* ATH_DEBUG */
5288 	IF_LOCK(&ifp->if_snd);
5289 	ifp->if_drv_flags &= ~IFF_DRV_OACTIVE;
5290 	IF_UNLOCK(&ifp->if_snd);
5291 	sc->sc_wd_timer = 0;
5292 }
5293 
5294 /*
5295  * Update internal state after a channel change.
5296  */
5297 static void
5298 ath_chan_change(struct ath_softc *sc, struct ieee80211_channel *chan)
5299 {
5300 	enum ieee80211_phymode mode;
5301 
5302 	/*
5303 	 * Change channels and update the h/w rate map
5304 	 * if we're switching; e.g. 11a to 11b/g.
5305 	 */
5306 	mode = ieee80211_chan2mode(chan);
5307 	if (mode != sc->sc_curmode)
5308 		ath_setcurmode(sc, mode);
5309 	sc->sc_curchan = chan;
5310 }
5311 
5312 /*
5313  * Set/change channels.  If the channel is really being changed,
5314  * it's done by resetting the chip.  To accomplish this we must
5315  * first cleanup any pending DMA, then restart stuff after a la
5316  * ath_init.
5317  */
5318 static int
5319 ath_chan_set(struct ath_softc *sc, struct ieee80211_channel *chan)
5320 {
5321 	struct ifnet *ifp = sc->sc_ifp;
5322 	struct ieee80211com *ic = ifp->if_l2com;
5323 	struct ath_hal *ah = sc->sc_ah;
5324 	int ret = 0;
5325 
5326 	/* Treat this as an interface reset */
5327 	ATH_PCU_UNLOCK_ASSERT(sc);
5328 	ATH_UNLOCK_ASSERT(sc);
5329 
5330 	/* (Try to) stop TX/RX from occuring */
5331 	taskqueue_block(sc->sc_tq);
5332 
5333 	ATH_PCU_LOCK(sc);
5334 
5335 	/* Stop new RX/TX/interrupt completion */
5336 	if (ath_reset_grablock(sc, 1) == 0) {
5337 		device_printf(sc->sc_dev, "%s: concurrent reset! Danger!\n",
5338 		    __func__);
5339 	}
5340 
5341 	ath_hal_intrset(ah, 0);
5342 
5343 	/* Stop pending RX/TX completion */
5344 	ath_txrx_stop_locked(sc);
5345 
5346 	ATH_PCU_UNLOCK(sc);
5347 
5348 	DPRINTF(sc, ATH_DEBUG_RESET, "%s: %u (%u MHz, flags 0x%x)\n",
5349 	    __func__, ieee80211_chan2ieee(ic, chan),
5350 	    chan->ic_freq, chan->ic_flags);
5351 	if (chan != sc->sc_curchan) {
5352 		HAL_STATUS status;
5353 		/*
5354 		 * To switch channels clear any pending DMA operations;
5355 		 * wait long enough for the RX fifo to drain, reset the
5356 		 * hardware at the new frequency, and then re-enable
5357 		 * the relevant bits of the h/w.
5358 		 */
5359 #if 0
5360 		ath_hal_intrset(ah, 0);		/* disable interrupts */
5361 #endif
5362 		ath_stoprecv(sc, 1);		/* turn off frame recv */
5363 		/*
5364 		 * First, handle completed TX/RX frames.
5365 		 */
5366 		ath_rx_flush(sc);
5367 		ath_draintxq(sc, ATH_RESET_NOLOSS);
5368 		/*
5369 		 * Next, flush the non-scheduled frames.
5370 		 */
5371 		ath_draintxq(sc, ATH_RESET_FULL);	/* clear pending tx frames */
5372 
5373 		ath_update_chainmasks(sc, chan);
5374 		ath_hal_setchainmasks(sc->sc_ah, sc->sc_cur_txchainmask,
5375 		    sc->sc_cur_rxchainmask);
5376 		if (!ath_hal_reset(ah, sc->sc_opmode, chan, AH_TRUE, &status)) {
5377 			if_printf(ifp, "%s: unable to reset "
5378 			    "channel %u (%u MHz, flags 0x%x), hal status %u\n",
5379 			    __func__, ieee80211_chan2ieee(ic, chan),
5380 			    chan->ic_freq, chan->ic_flags, status);
5381 			ret = EIO;
5382 			goto finish;
5383 		}
5384 		sc->sc_diversity = ath_hal_getdiversity(ah);
5385 
5386 		/* Let DFS at it in case it's a DFS channel */
5387 		ath_dfs_radar_enable(sc, chan);
5388 
5389 		/* Let spectral at in case spectral is enabled */
5390 		ath_spectral_enable(sc, chan);
5391 
5392 		/*
5393 		 * Let bluetooth coexistence at in case it's needed for this
5394 		 * channel
5395 		 */
5396 		ath_btcoex_enable(sc, ic->ic_curchan);
5397 
5398 		/*
5399 		 * If we're doing TDMA, enforce the TXOP limitation for chips
5400 		 * that support it.
5401 		 */
5402 		if (sc->sc_hasenforcetxop && sc->sc_tdma)
5403 			ath_hal_setenforcetxop(sc->sc_ah, 1);
5404 		else
5405 			ath_hal_setenforcetxop(sc->sc_ah, 0);
5406 
5407 		/*
5408 		 * Re-enable rx framework.
5409 		 */
5410 		if (ath_startrecv(sc) != 0) {
5411 			if_printf(ifp, "%s: unable to restart recv logic\n",
5412 			    __func__);
5413 			ret = EIO;
5414 			goto finish;
5415 		}
5416 
5417 		/*
5418 		 * Change channels and update the h/w rate map
5419 		 * if we're switching; e.g. 11a to 11b/g.
5420 		 */
5421 		ath_chan_change(sc, chan);
5422 
5423 		/*
5424 		 * Reset clears the beacon timers; reset them
5425 		 * here if needed.
5426 		 */
5427 		if (sc->sc_beacons) {		/* restart beacons */
5428 #ifdef IEEE80211_SUPPORT_TDMA
5429 			if (sc->sc_tdma)
5430 				ath_tdma_config(sc, NULL);
5431 			else
5432 #endif
5433 			ath_beacon_config(sc, NULL);
5434 		}
5435 
5436 		/*
5437 		 * Re-enable interrupts.
5438 		 */
5439 #if 0
5440 		ath_hal_intrset(ah, sc->sc_imask);
5441 #endif
5442 	}
5443 
5444 finish:
5445 	ATH_PCU_LOCK(sc);
5446 	sc->sc_inreset_cnt--;
5447 	/* XXX only do this if sc_inreset_cnt == 0? */
5448 	ath_hal_intrset(ah, sc->sc_imask);
5449 	ATH_PCU_UNLOCK(sc);
5450 
5451 	IF_LOCK(&ifp->if_snd);
5452 	ifp->if_drv_flags &= ~IFF_DRV_OACTIVE;
5453 	IF_UNLOCK(&ifp->if_snd);
5454 	ath_txrx_start(sc);
5455 	/* XXX ath_start? */
5456 
5457 	return ret;
5458 }
5459 
5460 /*
5461  * Periodically recalibrate the PHY to account
5462  * for temperature/environment changes.
5463  */
5464 static void
5465 ath_calibrate(void *arg)
5466 {
5467 	struct ath_softc *sc = arg;
5468 	struct ath_hal *ah = sc->sc_ah;
5469 	struct ifnet *ifp = sc->sc_ifp;
5470 	struct ieee80211com *ic = ifp->if_l2com;
5471 	HAL_BOOL longCal, isCalDone = AH_TRUE;
5472 	HAL_BOOL aniCal, shortCal = AH_FALSE;
5473 	int nextcal;
5474 
5475 	/*
5476 	 * Force the hardware awake for ANI work.
5477 	 */
5478 	ath_power_set_power_state(sc, HAL_PM_AWAKE);
5479 
5480 	/* Skip trying to do this if we're in reset */
5481 	if (sc->sc_inreset_cnt)
5482 		goto restart;
5483 
5484 	if (ic->ic_flags & IEEE80211_F_SCAN)	/* defer, off channel */
5485 		goto restart;
5486 	longCal = (ticks - sc->sc_lastlongcal >= ath_longcalinterval*hz);
5487 	aniCal = (ticks - sc->sc_lastani >= ath_anicalinterval*hz/1000);
5488 	if (sc->sc_doresetcal)
5489 		shortCal = (ticks - sc->sc_lastshortcal >= ath_shortcalinterval*hz/1000);
5490 
5491 	DPRINTF(sc, ATH_DEBUG_CALIBRATE, "%s: shortCal=%d; longCal=%d; aniCal=%d\n", __func__, shortCal, longCal, aniCal);
5492 	if (aniCal) {
5493 		sc->sc_stats.ast_ani_cal++;
5494 		sc->sc_lastani = ticks;
5495 		ath_hal_ani_poll(ah, sc->sc_curchan);
5496 	}
5497 
5498 	if (longCal) {
5499 		sc->sc_stats.ast_per_cal++;
5500 		sc->sc_lastlongcal = ticks;
5501 		if (ath_hal_getrfgain(ah) == HAL_RFGAIN_NEED_CHANGE) {
5502 			/*
5503 			 * Rfgain is out of bounds, reset the chip
5504 			 * to load new gain values.
5505 			 */
5506 			DPRINTF(sc, ATH_DEBUG_CALIBRATE,
5507 				"%s: rfgain change\n", __func__);
5508 			sc->sc_stats.ast_per_rfgain++;
5509 			sc->sc_resetcal = 0;
5510 			sc->sc_doresetcal = AH_TRUE;
5511 			taskqueue_enqueue(sc->sc_tq, &sc->sc_resettask);
5512 			callout_reset(&sc->sc_cal_ch, 1, ath_calibrate, sc);
5513 			ath_power_restore_power_state(sc);
5514 			return;
5515 		}
5516 		/*
5517 		 * If this long cal is after an idle period, then
5518 		 * reset the data collection state so we start fresh.
5519 		 */
5520 		if (sc->sc_resetcal) {
5521 			(void) ath_hal_calreset(ah, sc->sc_curchan);
5522 			sc->sc_lastcalreset = ticks;
5523 			sc->sc_lastshortcal = ticks;
5524 			sc->sc_resetcal = 0;
5525 			sc->sc_doresetcal = AH_TRUE;
5526 		}
5527 	}
5528 
5529 	/* Only call if we're doing a short/long cal, not for ANI calibration */
5530 	if (shortCal || longCal) {
5531 		isCalDone = AH_FALSE;
5532 		if (ath_hal_calibrateN(ah, sc->sc_curchan, longCal, &isCalDone)) {
5533 			if (longCal) {
5534 				/*
5535 				 * Calibrate noise floor data again in case of change.
5536 				 */
5537 				ath_hal_process_noisefloor(ah);
5538 			}
5539 		} else {
5540 			DPRINTF(sc, ATH_DEBUG_ANY,
5541 				"%s: calibration of channel %u failed\n",
5542 				__func__, sc->sc_curchan->ic_freq);
5543 			sc->sc_stats.ast_per_calfail++;
5544 		}
5545 		if (shortCal)
5546 			sc->sc_lastshortcal = ticks;
5547 	}
5548 	if (!isCalDone) {
5549 restart:
5550 		/*
5551 		 * Use a shorter interval to potentially collect multiple
5552 		 * data samples required to complete calibration.  Once
5553 		 * we're told the work is done we drop back to a longer
5554 		 * interval between requests.  We're more aggressive doing
5555 		 * work when operating as an AP to improve operation right
5556 		 * after startup.
5557 		 */
5558 		sc->sc_lastshortcal = ticks;
5559 		nextcal = ath_shortcalinterval*hz/1000;
5560 		if (sc->sc_opmode != HAL_M_HOSTAP)
5561 			nextcal *= 10;
5562 		sc->sc_doresetcal = AH_TRUE;
5563 	} else {
5564 		/* nextcal should be the shortest time for next event */
5565 		nextcal = ath_longcalinterval*hz;
5566 		if (sc->sc_lastcalreset == 0)
5567 			sc->sc_lastcalreset = sc->sc_lastlongcal;
5568 		else if (ticks - sc->sc_lastcalreset >= ath_resetcalinterval*hz)
5569 			sc->sc_resetcal = 1;	/* setup reset next trip */
5570 		sc->sc_doresetcal = AH_FALSE;
5571 	}
5572 	/* ANI calibration may occur more often than short/long/resetcal */
5573 	if (ath_anicalinterval > 0)
5574 		nextcal = MIN(nextcal, ath_anicalinterval*hz/1000);
5575 
5576 	if (nextcal != 0) {
5577 		DPRINTF(sc, ATH_DEBUG_CALIBRATE, "%s: next +%u (%sisCalDone)\n",
5578 		    __func__, nextcal, isCalDone ? "" : "!");
5579 		callout_reset(&sc->sc_cal_ch, nextcal, ath_calibrate, sc);
5580 	} else {
5581 		DPRINTF(sc, ATH_DEBUG_CALIBRATE, "%s: calibration disabled\n",
5582 		    __func__);
5583 		/* NB: don't rearm timer */
5584 	}
5585 	/*
5586 	 * Restore power state now that we're done.
5587 	 */
5588 	ath_power_restore_power_state(sc);
5589 }
5590 
5591 static void
5592 ath_scan_start(struct ieee80211com *ic)
5593 {
5594 	struct ifnet *ifp = ic->ic_ifp;
5595 	struct ath_softc *sc = ifp->if_softc;
5596 	struct ath_hal *ah = sc->sc_ah;
5597 	u_int32_t rfilt;
5598 
5599 	/* XXX calibration timer? */
5600 
5601 	ATH_LOCK(sc);
5602 	sc->sc_scanning = 1;
5603 	sc->sc_syncbeacon = 0;
5604 	rfilt = ath_calcrxfilter(sc);
5605 	ATH_UNLOCK(sc);
5606 
5607 	ATH_PCU_LOCK(sc);
5608 	ath_hal_setrxfilter(ah, rfilt);
5609 	ath_hal_setassocid(ah, ifp->if_broadcastaddr, 0);
5610 	ATH_PCU_UNLOCK(sc);
5611 
5612 	DPRINTF(sc, ATH_DEBUG_STATE, "%s: RX filter 0x%x bssid %s aid 0\n",
5613 		 __func__, rfilt, ether_sprintf(ifp->if_broadcastaddr));
5614 }
5615 
5616 static void
5617 ath_scan_end(struct ieee80211com *ic)
5618 {
5619 	struct ifnet *ifp = ic->ic_ifp;
5620 	struct ath_softc *sc = ifp->if_softc;
5621 	struct ath_hal *ah = sc->sc_ah;
5622 	u_int32_t rfilt;
5623 
5624 	ATH_LOCK(sc);
5625 	sc->sc_scanning = 0;
5626 	rfilt = ath_calcrxfilter(sc);
5627 	ATH_UNLOCK(sc);
5628 
5629 	ATH_PCU_LOCK(sc);
5630 	ath_hal_setrxfilter(ah, rfilt);
5631 	ath_hal_setassocid(ah, sc->sc_curbssid, sc->sc_curaid);
5632 
5633 	ath_hal_process_noisefloor(ah);
5634 	ATH_PCU_UNLOCK(sc);
5635 
5636 	DPRINTF(sc, ATH_DEBUG_STATE, "%s: RX filter 0x%x bssid %s aid 0x%x\n",
5637 		 __func__, rfilt, ether_sprintf(sc->sc_curbssid),
5638 		 sc->sc_curaid);
5639 }
5640 
5641 #ifdef	ATH_ENABLE_11N
5642 /*
5643  * For now, just do a channel change.
5644  *
5645  * Later, we'll go through the hard slog of suspending tx/rx, changing rate
5646  * control state and resetting the hardware without dropping frames out
5647  * of the queue.
5648  *
5649  * The unfortunate trouble here is making absolutely sure that the
5650  * channel width change has propagated enough so the hardware
5651  * absolutely isn't handed bogus frames for it's current operating
5652  * mode. (Eg, 40MHz frames in 20MHz mode.) Since TX and RX can and
5653  * does occur in parallel, we need to make certain we've blocked
5654  * any further ongoing TX (and RX, that can cause raw TX)
5655  * before we do this.
5656  */
5657 static void
5658 ath_update_chw(struct ieee80211com *ic)
5659 {
5660 	struct ifnet *ifp = ic->ic_ifp;
5661 	struct ath_softc *sc = ifp->if_softc;
5662 
5663 	DPRINTF(sc, ATH_DEBUG_STATE, "%s: called\n", __func__);
5664 	ath_set_channel(ic);
5665 }
5666 #endif	/* ATH_ENABLE_11N */
5667 
5668 static void
5669 ath_set_channel(struct ieee80211com *ic)
5670 {
5671 	struct ifnet *ifp = ic->ic_ifp;
5672 	struct ath_softc *sc = ifp->if_softc;
5673 
5674 	ATH_LOCK(sc);
5675 	ath_power_set_power_state(sc, HAL_PM_AWAKE);
5676 	ATH_UNLOCK(sc);
5677 
5678 	(void) ath_chan_set(sc, ic->ic_curchan);
5679 	/*
5680 	 * If we are returning to our bss channel then mark state
5681 	 * so the next recv'd beacon's tsf will be used to sync the
5682 	 * beacon timers.  Note that since we only hear beacons in
5683 	 * sta/ibss mode this has no effect in other operating modes.
5684 	 */
5685 	ATH_LOCK(sc);
5686 	if (!sc->sc_scanning && ic->ic_curchan == ic->ic_bsschan)
5687 		sc->sc_syncbeacon = 1;
5688 	ath_power_restore_power_state(sc);
5689 	ATH_UNLOCK(sc);
5690 }
5691 
5692 /*
5693  * Walk the vap list and check if there any vap's in RUN state.
5694  */
5695 static int
5696 ath_isanyrunningvaps(struct ieee80211vap *this)
5697 {
5698 	struct ieee80211com *ic = this->iv_ic;
5699 	struct ieee80211vap *vap;
5700 
5701 	IEEE80211_LOCK_ASSERT(ic);
5702 
5703 	TAILQ_FOREACH(vap, &ic->ic_vaps, iv_next) {
5704 		if (vap != this && vap->iv_state >= IEEE80211_S_RUN)
5705 			return 1;
5706 	}
5707 	return 0;
5708 }
5709 
5710 static int
5711 ath_newstate(struct ieee80211vap *vap, enum ieee80211_state nstate, int arg)
5712 {
5713 	struct ieee80211com *ic = vap->iv_ic;
5714 	struct ath_softc *sc = ic->ic_ifp->if_softc;
5715 	struct ath_vap *avp = ATH_VAP(vap);
5716 	struct ath_hal *ah = sc->sc_ah;
5717 	struct ieee80211_node *ni = NULL;
5718 	int i, error, stamode;
5719 	u_int32_t rfilt;
5720 	int csa_run_transition = 0;
5721 	enum ieee80211_state ostate = vap->iv_state;
5722 
5723 	static const HAL_LED_STATE leds[] = {
5724 	    HAL_LED_INIT,	/* IEEE80211_S_INIT */
5725 	    HAL_LED_SCAN,	/* IEEE80211_S_SCAN */
5726 	    HAL_LED_AUTH,	/* IEEE80211_S_AUTH */
5727 	    HAL_LED_ASSOC, 	/* IEEE80211_S_ASSOC */
5728 	    HAL_LED_RUN, 	/* IEEE80211_S_CAC */
5729 	    HAL_LED_RUN, 	/* IEEE80211_S_RUN */
5730 	    HAL_LED_RUN, 	/* IEEE80211_S_CSA */
5731 	    HAL_LED_RUN, 	/* IEEE80211_S_SLEEP */
5732 	};
5733 
5734 	DPRINTF(sc, ATH_DEBUG_STATE, "%s: %s -> %s\n", __func__,
5735 		ieee80211_state_name[ostate],
5736 		ieee80211_state_name[nstate]);
5737 
5738 	/*
5739 	 * net80211 _should_ have the comlock asserted at this point.
5740 	 * There are some comments around the calls to vap->iv_newstate
5741 	 * which indicate that it (newstate) may end up dropping the
5742 	 * lock.  This and the subsequent lock assert check after newstate
5743 	 * are an attempt to catch these and figure out how/why.
5744 	 */
5745 	IEEE80211_LOCK_ASSERT(ic);
5746 
5747 	/* Before we touch the hardware - wake it up */
5748 	ATH_LOCK(sc);
5749 	/*
5750 	 * If the NIC is in anything other than SLEEP state,
5751 	 * we need to ensure that self-generated frames are
5752 	 * set for PWRMGT=0.  Otherwise we may end up with
5753 	 * strange situations.
5754 	 *
5755 	 * XXX TODO: is this actually the case? :-)
5756 	 */
5757 	if (nstate != IEEE80211_S_SLEEP)
5758 		ath_power_setselfgen(sc, HAL_PM_AWAKE);
5759 
5760 	/*
5761 	 * Now, wake the thing up.
5762 	 */
5763 	ath_power_set_power_state(sc, HAL_PM_AWAKE);
5764 	ATH_UNLOCK(sc);
5765 
5766 	if (ostate == IEEE80211_S_CSA && nstate == IEEE80211_S_RUN)
5767 		csa_run_transition = 1;
5768 
5769 	callout_drain(&sc->sc_cal_ch);
5770 	ath_hal_setledstate(ah, leds[nstate]);	/* set LED */
5771 
5772 	if (nstate == IEEE80211_S_SCAN) {
5773 		/*
5774 		 * Scanning: turn off beacon miss and don't beacon.
5775 		 * Mark beacon state so when we reach RUN state we'll
5776 		 * [re]setup beacons.  Unblock the task q thread so
5777 		 * deferred interrupt processing is done.
5778 		 */
5779 
5780 		/* Ensure we stay awake during scan */
5781 		ATH_LOCK(sc);
5782 		ath_power_setselfgen(sc, HAL_PM_AWAKE);
5783 		ath_power_setpower(sc, HAL_PM_AWAKE);
5784 		ATH_UNLOCK(sc);
5785 
5786 		ath_hal_intrset(ah,
5787 		    sc->sc_imask &~ (HAL_INT_SWBA | HAL_INT_BMISS));
5788 		sc->sc_imask &= ~(HAL_INT_SWBA | HAL_INT_BMISS);
5789 		sc->sc_beacons = 0;
5790 		taskqueue_unblock(sc->sc_tq);
5791 	}
5792 
5793 	ni = ieee80211_ref_node(vap->iv_bss);
5794 	rfilt = ath_calcrxfilter(sc);
5795 	stamode = (vap->iv_opmode == IEEE80211_M_STA ||
5796 		   vap->iv_opmode == IEEE80211_M_AHDEMO ||
5797 		   vap->iv_opmode == IEEE80211_M_IBSS);
5798 
5799 	/*
5800 	 * XXX Dont need to do this (and others) if we've transitioned
5801 	 * from SLEEP->RUN.
5802 	 */
5803 	if (stamode && nstate == IEEE80211_S_RUN) {
5804 		sc->sc_curaid = ni->ni_associd;
5805 		IEEE80211_ADDR_COPY(sc->sc_curbssid, ni->ni_bssid);
5806 		ath_hal_setassocid(ah, sc->sc_curbssid, sc->sc_curaid);
5807 	}
5808 	DPRINTF(sc, ATH_DEBUG_STATE, "%s: RX filter 0x%x bssid %s aid 0x%x\n",
5809 	   __func__, rfilt, ether_sprintf(sc->sc_curbssid), sc->sc_curaid);
5810 	ath_hal_setrxfilter(ah, rfilt);
5811 
5812 	/* XXX is this to restore keycache on resume? */
5813 	if (vap->iv_opmode != IEEE80211_M_STA &&
5814 	    (vap->iv_flags & IEEE80211_F_PRIVACY)) {
5815 		for (i = 0; i < IEEE80211_WEP_NKID; i++)
5816 			if (ath_hal_keyisvalid(ah, i))
5817 				ath_hal_keysetmac(ah, i, ni->ni_bssid);
5818 	}
5819 
5820 	/*
5821 	 * Invoke the parent method to do net80211 work.
5822 	 */
5823 	error = avp->av_newstate(vap, nstate, arg);
5824 	if (error != 0)
5825 		goto bad;
5826 
5827 	/*
5828 	 * See above: ensure av_newstate() doesn't drop the lock
5829 	 * on us.
5830 	 */
5831 	IEEE80211_LOCK_ASSERT(ic);
5832 
5833 	if (nstate == IEEE80211_S_RUN) {
5834 		/* NB: collect bss node again, it may have changed */
5835 		ieee80211_free_node(ni);
5836 		ni = ieee80211_ref_node(vap->iv_bss);
5837 
5838 		DPRINTF(sc, ATH_DEBUG_STATE,
5839 		    "%s(RUN): iv_flags 0x%08x bintvl %d bssid %s "
5840 		    "capinfo 0x%04x chan %d\n", __func__,
5841 		    vap->iv_flags, ni->ni_intval, ether_sprintf(ni->ni_bssid),
5842 		    ni->ni_capinfo, ieee80211_chan2ieee(ic, ic->ic_curchan));
5843 
5844 		switch (vap->iv_opmode) {
5845 #ifdef IEEE80211_SUPPORT_TDMA
5846 		case IEEE80211_M_AHDEMO:
5847 			if ((vap->iv_caps & IEEE80211_C_TDMA) == 0)
5848 				break;
5849 			/* fall thru... */
5850 #endif
5851 		case IEEE80211_M_HOSTAP:
5852 		case IEEE80211_M_IBSS:
5853 		case IEEE80211_M_MBSS:
5854 			/*
5855 			 * Allocate and setup the beacon frame.
5856 			 *
5857 			 * Stop any previous beacon DMA.  This may be
5858 			 * necessary, for example, when an ibss merge
5859 			 * causes reconfiguration; there will be a state
5860 			 * transition from RUN->RUN that means we may
5861 			 * be called with beacon transmission active.
5862 			 */
5863 			ath_hal_stoptxdma(ah, sc->sc_bhalq);
5864 
5865 			error = ath_beacon_alloc(sc, ni);
5866 			if (error != 0)
5867 				goto bad;
5868 			/*
5869 			 * If joining an adhoc network defer beacon timer
5870 			 * configuration to the next beacon frame so we
5871 			 * have a current TSF to use.  Otherwise we're
5872 			 * starting an ibss/bss so there's no need to delay;
5873 			 * if this is the first vap moving to RUN state, then
5874 			 * beacon state needs to be [re]configured.
5875 			 */
5876 			if (vap->iv_opmode == IEEE80211_M_IBSS &&
5877 			    ni->ni_tstamp.tsf != 0) {
5878 				sc->sc_syncbeacon = 1;
5879 			} else if (!sc->sc_beacons) {
5880 #ifdef IEEE80211_SUPPORT_TDMA
5881 				if (vap->iv_caps & IEEE80211_C_TDMA)
5882 					ath_tdma_config(sc, vap);
5883 				else
5884 #endif
5885 					ath_beacon_config(sc, vap);
5886 				sc->sc_beacons = 1;
5887 			}
5888 			break;
5889 		case IEEE80211_M_STA:
5890 			/*
5891 			 * Defer beacon timer configuration to the next
5892 			 * beacon frame so we have a current TSF to use
5893 			 * (any TSF collected when scanning is likely old).
5894 			 * However if it's due to a CSA -> RUN transition,
5895 			 * force a beacon update so we pick up a lack of
5896 			 * beacons from an AP in CAC and thus force a
5897 			 * scan.
5898 			 *
5899 			 * And, there's also corner cases here where
5900 			 * after a scan, the AP may have disappeared.
5901 			 * In that case, we may not receive an actual
5902 			 * beacon to update the beacon timer and thus we
5903 			 * won't get notified of the missing beacons.
5904 			 */
5905 			if (ostate != IEEE80211_S_RUN &&
5906 			    ostate != IEEE80211_S_SLEEP) {
5907 				DPRINTF(sc, ATH_DEBUG_BEACON,
5908 				    "%s: STA; syncbeacon=1\n", __func__);
5909 				sc->sc_syncbeacon = 1;
5910 
5911 				if (csa_run_transition)
5912 					ath_beacon_config(sc, vap);
5913 
5914 			/*
5915 			 * PR: kern/175227
5916 			 *
5917 			 * Reconfigure beacons during reset; as otherwise
5918 			 * we won't get the beacon timers reprogrammed
5919 			 * after a reset and thus we won't pick up a
5920 			 * beacon miss interrupt.
5921 			 *
5922 			 * Hopefully we'll see a beacon before the BMISS
5923 			 * timer fires (too often), leading to a STA
5924 			 * disassociation.
5925 			 */
5926 				sc->sc_beacons = 1;
5927 			}
5928 			break;
5929 		case IEEE80211_M_MONITOR:
5930 			/*
5931 			 * Monitor mode vaps have only INIT->RUN and RUN->RUN
5932 			 * transitions so we must re-enable interrupts here to
5933 			 * handle the case of a single monitor mode vap.
5934 			 */
5935 			ath_hal_intrset(ah, sc->sc_imask);
5936 			break;
5937 		case IEEE80211_M_WDS:
5938 			break;
5939 		default:
5940 			break;
5941 		}
5942 		/*
5943 		 * Let the hal process statistics collected during a
5944 		 * scan so it can provide calibrated noise floor data.
5945 		 */
5946 		ath_hal_process_noisefloor(ah);
5947 		/*
5948 		 * Reset rssi stats; maybe not the best place...
5949 		 */
5950 		sc->sc_halstats.ns_avgbrssi = ATH_RSSI_DUMMY_MARKER;
5951 		sc->sc_halstats.ns_avgrssi = ATH_RSSI_DUMMY_MARKER;
5952 		sc->sc_halstats.ns_avgtxrssi = ATH_RSSI_DUMMY_MARKER;
5953 
5954 		/*
5955 		 * Force awake for RUN mode.
5956 		 */
5957 		ATH_LOCK(sc);
5958 		ath_power_setselfgen(sc, HAL_PM_AWAKE);
5959 		ath_power_setpower(sc, HAL_PM_AWAKE);
5960 		ATH_UNLOCK(sc);
5961 
5962 		/*
5963 		 * Finally, start any timers and the task q thread
5964 		 * (in case we didn't go through SCAN state).
5965 		 */
5966 		if (ath_longcalinterval != 0) {
5967 			/* start periodic recalibration timer */
5968 			callout_reset(&sc->sc_cal_ch, 1, ath_calibrate, sc);
5969 		} else {
5970 			DPRINTF(sc, ATH_DEBUG_CALIBRATE,
5971 			    "%s: calibration disabled\n", __func__);
5972 		}
5973 
5974 		taskqueue_unblock(sc->sc_tq);
5975 	} else if (nstate == IEEE80211_S_INIT) {
5976 		/*
5977 		 * If there are no vaps left in RUN state then
5978 		 * shutdown host/driver operation:
5979 		 * o disable interrupts
5980 		 * o disable the task queue thread
5981 		 * o mark beacon processing as stopped
5982 		 */
5983 		if (!ath_isanyrunningvaps(vap)) {
5984 			sc->sc_imask &= ~(HAL_INT_SWBA | HAL_INT_BMISS);
5985 			/* disable interrupts  */
5986 			ath_hal_intrset(ah, sc->sc_imask &~ HAL_INT_GLOBAL);
5987 			taskqueue_block(sc->sc_tq);
5988 			sc->sc_beacons = 0;
5989 		}
5990 #ifdef IEEE80211_SUPPORT_TDMA
5991 		ath_hal_setcca(ah, AH_TRUE);
5992 #endif
5993 	} else if (nstate == IEEE80211_S_SLEEP) {
5994 		/* We're going to sleep, so transition appropriately */
5995 		/* For now, only do this if we're a single STA vap */
5996 		if (sc->sc_nvaps == 1 &&
5997 		    vap->iv_opmode == IEEE80211_M_STA) {
5998 			DPRINTF(sc, ATH_DEBUG_BEACON, "%s: syncbeacon=%d\n", __func__, sc->sc_syncbeacon);
5999 			ATH_LOCK(sc);
6000 			/*
6001 			 * Always at least set the self-generated
6002 			 * frame config to set PWRMGT=1.
6003 			 */
6004 			ath_power_setselfgen(sc, HAL_PM_NETWORK_SLEEP);
6005 
6006 			/*
6007 			 * If we're not syncing beacons, transition
6008 			 * to NETWORK_SLEEP.
6009 			 *
6010 			 * We stay awake if syncbeacon > 0 in case
6011 			 * we need to listen for some beacons otherwise
6012 			 * our beacon timer config may be wrong.
6013 			 */
6014 			if (sc->sc_syncbeacon == 0) {
6015 				ath_power_setpower(sc, HAL_PM_NETWORK_SLEEP);
6016 			}
6017 			ATH_UNLOCK(sc);
6018 		}
6019 	}
6020 bad:
6021 	ieee80211_free_node(ni);
6022 
6023 	/*
6024 	 * Restore the power state - either to what it was, or
6025 	 * to network_sleep if it's alright.
6026 	 */
6027 	ATH_LOCK(sc);
6028 	ath_power_restore_power_state(sc);
6029 	ATH_UNLOCK(sc);
6030 	return error;
6031 }
6032 
6033 /*
6034  * Allocate a key cache slot to the station so we can
6035  * setup a mapping from key index to node. The key cache
6036  * slot is needed for managing antenna state and for
6037  * compression when stations do not use crypto.  We do
6038  * it uniliaterally here; if crypto is employed this slot
6039  * will be reassigned.
6040  */
6041 static void
6042 ath_setup_stationkey(struct ieee80211_node *ni)
6043 {
6044 	struct ieee80211vap *vap = ni->ni_vap;
6045 	struct ath_softc *sc = vap->iv_ic->ic_ifp->if_softc;
6046 	ieee80211_keyix keyix, rxkeyix;
6047 
6048 	/* XXX should take a locked ref to vap->iv_bss */
6049 	if (!ath_key_alloc(vap, &ni->ni_ucastkey, &keyix, &rxkeyix)) {
6050 		/*
6051 		 * Key cache is full; we'll fall back to doing
6052 		 * the more expensive lookup in software.  Note
6053 		 * this also means no h/w compression.
6054 		 */
6055 		/* XXX msg+statistic */
6056 	} else {
6057 		/* XXX locking? */
6058 		ni->ni_ucastkey.wk_keyix = keyix;
6059 		ni->ni_ucastkey.wk_rxkeyix = rxkeyix;
6060 		/* NB: must mark device key to get called back on delete */
6061 		ni->ni_ucastkey.wk_flags |= IEEE80211_KEY_DEVKEY;
6062 		IEEE80211_ADDR_COPY(ni->ni_ucastkey.wk_macaddr, ni->ni_macaddr);
6063 		/* NB: this will create a pass-thru key entry */
6064 		ath_keyset(sc, vap, &ni->ni_ucastkey, vap->iv_bss);
6065 	}
6066 }
6067 
6068 /*
6069  * Setup driver-specific state for a newly associated node.
6070  * Note that we're called also on a re-associate, the isnew
6071  * param tells us if this is the first time or not.
6072  */
6073 static void
6074 ath_newassoc(struct ieee80211_node *ni, int isnew)
6075 {
6076 	struct ath_node *an = ATH_NODE(ni);
6077 	struct ieee80211vap *vap = ni->ni_vap;
6078 	struct ath_softc *sc = vap->iv_ic->ic_ifp->if_softc;
6079 	const struct ieee80211_txparam *tp = ni->ni_txparms;
6080 
6081 	an->an_mcastrix = ath_tx_findrix(sc, tp->mcastrate);
6082 	an->an_mgmtrix = ath_tx_findrix(sc, tp->mgmtrate);
6083 
6084 	DPRINTF(sc, ATH_DEBUG_NODE, "%s: %6D: reassoc; isnew=%d, is_powersave=%d\n",
6085 	    __func__,
6086 	    ni->ni_macaddr,
6087 	    ":",
6088 	    isnew,
6089 	    an->an_is_powersave);
6090 
6091 	ATH_NODE_LOCK(an);
6092 	ath_rate_newassoc(sc, an, isnew);
6093 	ATH_NODE_UNLOCK(an);
6094 
6095 	if (isnew &&
6096 	    (vap->iv_flags & IEEE80211_F_PRIVACY) == 0 && sc->sc_hasclrkey &&
6097 	    ni->ni_ucastkey.wk_keyix == IEEE80211_KEYIX_NONE)
6098 		ath_setup_stationkey(ni);
6099 
6100 	/*
6101 	 * If we're reassociating, make sure that any paused queues
6102 	 * get unpaused.
6103 	 *
6104 	 * Now, we may hvae frames in the hardware queue for this node.
6105 	 * So if we are reassociating and there are frames in the queue,
6106 	 * we need to go through the cleanup path to ensure that they're
6107 	 * marked as non-aggregate.
6108 	 */
6109 	if (! isnew) {
6110 		DPRINTF(sc, ATH_DEBUG_NODE,
6111 		    "%s: %6D: reassoc; is_powersave=%d\n",
6112 		    __func__,
6113 		    ni->ni_macaddr,
6114 		    ":",
6115 		    an->an_is_powersave);
6116 
6117 		/* XXX for now, we can't hold the lock across assoc */
6118 		ath_tx_node_reassoc(sc, an);
6119 
6120 		/* XXX for now, we can't hold the lock across wakeup */
6121 		if (an->an_is_powersave)
6122 			ath_tx_node_wakeup(sc, an);
6123 	}
6124 }
6125 
6126 static int
6127 ath_setregdomain(struct ieee80211com *ic, struct ieee80211_regdomain *reg,
6128 	int nchans, struct ieee80211_channel chans[])
6129 {
6130 	struct ath_softc *sc = ic->ic_ifp->if_softc;
6131 	struct ath_hal *ah = sc->sc_ah;
6132 	HAL_STATUS status;
6133 
6134 	DPRINTF(sc, ATH_DEBUG_REGDOMAIN,
6135 	    "%s: rd %u cc %u location %c%s\n",
6136 	    __func__, reg->regdomain, reg->country, reg->location,
6137 	    reg->ecm ? " ecm" : "");
6138 
6139 	status = ath_hal_set_channels(ah, chans, nchans,
6140 	    reg->country, reg->regdomain);
6141 	if (status != HAL_OK) {
6142 		DPRINTF(sc, ATH_DEBUG_REGDOMAIN, "%s: failed, status %u\n",
6143 		    __func__, status);
6144 		return EINVAL;		/* XXX */
6145 	}
6146 
6147 	return 0;
6148 }
6149 
6150 static void
6151 ath_getradiocaps(struct ieee80211com *ic,
6152 	int maxchans, int *nchans, struct ieee80211_channel chans[])
6153 {
6154 	struct ath_softc *sc = ic->ic_ifp->if_softc;
6155 	struct ath_hal *ah = sc->sc_ah;
6156 
6157 	DPRINTF(sc, ATH_DEBUG_REGDOMAIN, "%s: use rd %u cc %d\n",
6158 	    __func__, SKU_DEBUG, CTRY_DEFAULT);
6159 
6160 	/* XXX check return */
6161 	(void) ath_hal_getchannels(ah, chans, maxchans, nchans,
6162 	    HAL_MODE_ALL, CTRY_DEFAULT, SKU_DEBUG, AH_TRUE);
6163 
6164 }
6165 
6166 static int
6167 ath_getchannels(struct ath_softc *sc)
6168 {
6169 	struct ifnet *ifp = sc->sc_ifp;
6170 	struct ieee80211com *ic = ifp->if_l2com;
6171 	struct ath_hal *ah = sc->sc_ah;
6172 	HAL_STATUS status;
6173 
6174 	/*
6175 	 * Collect channel set based on EEPROM contents.
6176 	 */
6177 	status = ath_hal_init_channels(ah, ic->ic_channels, IEEE80211_CHAN_MAX,
6178 	    &ic->ic_nchans, HAL_MODE_ALL, CTRY_DEFAULT, SKU_NONE, AH_TRUE);
6179 	if (status != HAL_OK) {
6180 		if_printf(ifp, "%s: unable to collect channel list from hal, "
6181 		    "status %d\n", __func__, status);
6182 		return EINVAL;
6183 	}
6184 	(void) ath_hal_getregdomain(ah, &sc->sc_eerd);
6185 	ath_hal_getcountrycode(ah, &sc->sc_eecc);	/* NB: cannot fail */
6186 	/* XXX map Atheros sku's to net80211 SKU's */
6187 	/* XXX net80211 types too small */
6188 	ic->ic_regdomain.regdomain = (uint16_t) sc->sc_eerd;
6189 	ic->ic_regdomain.country = (uint16_t) sc->sc_eecc;
6190 	ic->ic_regdomain.isocc[0] = ' ';	/* XXX don't know */
6191 	ic->ic_regdomain.isocc[1] = ' ';
6192 
6193 	ic->ic_regdomain.ecm = 1;
6194 	ic->ic_regdomain.location = 'I';
6195 
6196 	DPRINTF(sc, ATH_DEBUG_REGDOMAIN,
6197 	    "%s: eeprom rd %u cc %u (mapped rd %u cc %u) location %c%s\n",
6198 	    __func__, sc->sc_eerd, sc->sc_eecc,
6199 	    ic->ic_regdomain.regdomain, ic->ic_regdomain.country,
6200 	    ic->ic_regdomain.location, ic->ic_regdomain.ecm ? " ecm" : "");
6201 	return 0;
6202 }
6203 
6204 static int
6205 ath_rate_setup(struct ath_softc *sc, u_int mode)
6206 {
6207 	struct ath_hal *ah = sc->sc_ah;
6208 	const HAL_RATE_TABLE *rt;
6209 
6210 	switch (mode) {
6211 	case IEEE80211_MODE_11A:
6212 		rt = ath_hal_getratetable(ah, HAL_MODE_11A);
6213 		break;
6214 	case IEEE80211_MODE_HALF:
6215 		rt = ath_hal_getratetable(ah, HAL_MODE_11A_HALF_RATE);
6216 		break;
6217 	case IEEE80211_MODE_QUARTER:
6218 		rt = ath_hal_getratetable(ah, HAL_MODE_11A_QUARTER_RATE);
6219 		break;
6220 	case IEEE80211_MODE_11B:
6221 		rt = ath_hal_getratetable(ah, HAL_MODE_11B);
6222 		break;
6223 	case IEEE80211_MODE_11G:
6224 		rt = ath_hal_getratetable(ah, HAL_MODE_11G);
6225 		break;
6226 	case IEEE80211_MODE_TURBO_A:
6227 		rt = ath_hal_getratetable(ah, HAL_MODE_108A);
6228 		break;
6229 	case IEEE80211_MODE_TURBO_G:
6230 		rt = ath_hal_getratetable(ah, HAL_MODE_108G);
6231 		break;
6232 	case IEEE80211_MODE_STURBO_A:
6233 		rt = ath_hal_getratetable(ah, HAL_MODE_TURBO);
6234 		break;
6235 	case IEEE80211_MODE_11NA:
6236 		rt = ath_hal_getratetable(ah, HAL_MODE_11NA_HT20);
6237 		break;
6238 	case IEEE80211_MODE_11NG:
6239 		rt = ath_hal_getratetable(ah, HAL_MODE_11NG_HT20);
6240 		break;
6241 	default:
6242 		DPRINTF(sc, ATH_DEBUG_ANY, "%s: invalid mode %u\n",
6243 			__func__, mode);
6244 		return 0;
6245 	}
6246 	sc->sc_rates[mode] = rt;
6247 	return (rt != NULL);
6248 }
6249 
6250 static void
6251 ath_setcurmode(struct ath_softc *sc, enum ieee80211_phymode mode)
6252 {
6253 #define	N(a)	(sizeof(a)/sizeof(a[0]))
6254 	/* NB: on/off times from the Atheros NDIS driver, w/ permission */
6255 	static const struct {
6256 		u_int		rate;		/* tx/rx 802.11 rate */
6257 		u_int16_t	timeOn;		/* LED on time (ms) */
6258 		u_int16_t	timeOff;	/* LED off time (ms) */
6259 	} blinkrates[] = {
6260 		{ 108,  40,  10 },
6261 		{  96,  44,  11 },
6262 		{  72,  50,  13 },
6263 		{  48,  57,  14 },
6264 		{  36,  67,  16 },
6265 		{  24,  80,  20 },
6266 		{  22, 100,  25 },
6267 		{  18, 133,  34 },
6268 		{  12, 160,  40 },
6269 		{  10, 200,  50 },
6270 		{   6, 240,  58 },
6271 		{   4, 267,  66 },
6272 		{   2, 400, 100 },
6273 		{   0, 500, 130 },
6274 		/* XXX half/quarter rates */
6275 	};
6276 	const HAL_RATE_TABLE *rt;
6277 	int i, j;
6278 
6279 	memset(sc->sc_rixmap, 0xff, sizeof(sc->sc_rixmap));
6280 	rt = sc->sc_rates[mode];
6281 	KASSERT(rt != NULL, ("no h/w rate set for phy mode %u", mode));
6282 	for (i = 0; i < rt->rateCount; i++) {
6283 		uint8_t ieeerate = rt->info[i].dot11Rate & IEEE80211_RATE_VAL;
6284 		if (rt->info[i].phy != IEEE80211_T_HT)
6285 			sc->sc_rixmap[ieeerate] = i;
6286 		else
6287 			sc->sc_rixmap[ieeerate | IEEE80211_RATE_MCS] = i;
6288 	}
6289 	memset(sc->sc_hwmap, 0, sizeof(sc->sc_hwmap));
6290 	for (i = 0; i < N(sc->sc_hwmap); i++) {
6291 		if (i >= rt->rateCount) {
6292 			sc->sc_hwmap[i].ledon = (500 * hz) / 1000;
6293 			sc->sc_hwmap[i].ledoff = (130 * hz) / 1000;
6294 			continue;
6295 		}
6296 		sc->sc_hwmap[i].ieeerate =
6297 			rt->info[i].dot11Rate & IEEE80211_RATE_VAL;
6298 		if (rt->info[i].phy == IEEE80211_T_HT)
6299 			sc->sc_hwmap[i].ieeerate |= IEEE80211_RATE_MCS;
6300 		sc->sc_hwmap[i].txflags = IEEE80211_RADIOTAP_F_DATAPAD;
6301 		if (rt->info[i].shortPreamble ||
6302 		    rt->info[i].phy == IEEE80211_T_OFDM)
6303 			sc->sc_hwmap[i].txflags |= IEEE80211_RADIOTAP_F_SHORTPRE;
6304 		sc->sc_hwmap[i].rxflags = sc->sc_hwmap[i].txflags;
6305 		for (j = 0; j < N(blinkrates)-1; j++)
6306 			if (blinkrates[j].rate == sc->sc_hwmap[i].ieeerate)
6307 				break;
6308 		/* NB: this uses the last entry if the rate isn't found */
6309 		/* XXX beware of overlow */
6310 		sc->sc_hwmap[i].ledon = (blinkrates[j].timeOn * hz) / 1000;
6311 		sc->sc_hwmap[i].ledoff = (blinkrates[j].timeOff * hz) / 1000;
6312 	}
6313 	sc->sc_currates = rt;
6314 	sc->sc_curmode = mode;
6315 	/*
6316 	 * All protection frames are transmited at 2Mb/s for
6317 	 * 11g, otherwise at 1Mb/s.
6318 	 */
6319 	if (mode == IEEE80211_MODE_11G)
6320 		sc->sc_protrix = ath_tx_findrix(sc, 2*2);
6321 	else
6322 		sc->sc_protrix = ath_tx_findrix(sc, 2*1);
6323 	/* NB: caller is responsible for resetting rate control state */
6324 #undef N
6325 }
6326 
6327 static void
6328 ath_watchdog(void *arg)
6329 {
6330 	struct ath_softc *sc = arg;
6331 	int do_reset = 0;
6332 
6333 	if (sc->sc_wd_timer != 0 && --sc->sc_wd_timer == 0) {
6334 		struct ifnet *ifp = sc->sc_ifp;
6335 		uint32_t hangs;
6336 
6337 		ATH_LOCK(sc);
6338 		ath_power_set_power_state(sc, HAL_PM_AWAKE);
6339 		ATH_UNLOCK(sc);
6340 
6341 		if (ath_hal_gethangstate(sc->sc_ah, 0xffff, &hangs) &&
6342 		    hangs != 0) {
6343 			if_printf(ifp, "%s hang detected (0x%x)\n",
6344 			    hangs & 0xff ? "bb" : "mac", hangs);
6345 		} else
6346 			if_printf(ifp, "device timeout\n");
6347 		do_reset = 1;
6348 		ifp->if_oerrors++;
6349 		sc->sc_stats.ast_watchdog++;
6350 
6351 		ATH_LOCK(sc);
6352 		ath_power_restore_power_state(sc);
6353 		ATH_UNLOCK(sc);
6354 	}
6355 
6356 	/*
6357 	 * We can't hold the lock across the ath_reset() call.
6358 	 *
6359 	 * And since this routine can't hold a lock and sleep,
6360 	 * do the reset deferred.
6361 	 */
6362 	if (do_reset) {
6363 		taskqueue_enqueue(sc->sc_tq, &sc->sc_resettask);
6364 	}
6365 
6366 	callout_schedule(&sc->sc_wd_ch, hz);
6367 }
6368 
6369 /*
6370  * Fetch the rate control statistics for the given node.
6371  */
6372 static int
6373 ath_ioctl_ratestats(struct ath_softc *sc, struct ath_rateioctl *rs)
6374 {
6375 	struct ath_node *an;
6376 	struct ieee80211com *ic = sc->sc_ifp->if_l2com;
6377 	struct ieee80211_node *ni;
6378 	int error = 0;
6379 
6380 	/* Perform a lookup on the given node */
6381 	ni = ieee80211_find_node(&ic->ic_sta, rs->is_u.macaddr);
6382 	if (ni == NULL) {
6383 		error = EINVAL;
6384 		goto bad;
6385 	}
6386 
6387 	/* Lock the ath_node */
6388 	an = ATH_NODE(ni);
6389 	ATH_NODE_LOCK(an);
6390 
6391 	/* Fetch the rate control stats for this node */
6392 	error = ath_rate_fetch_node_stats(sc, an, rs);
6393 
6394 	/* No matter what happens here, just drop through */
6395 
6396 	/* Unlock the ath_node */
6397 	ATH_NODE_UNLOCK(an);
6398 
6399 	/* Unref the node */
6400 	ieee80211_node_decref(ni);
6401 
6402 bad:
6403 	return (error);
6404 }
6405 
6406 #ifdef ATH_DIAGAPI
6407 /*
6408  * Diagnostic interface to the HAL.  This is used by various
6409  * tools to do things like retrieve register contents for
6410  * debugging.  The mechanism is intentionally opaque so that
6411  * it can change frequently w/o concern for compatiblity.
6412  */
6413 static int
6414 ath_ioctl_diag(struct ath_softc *sc, struct ath_diag *ad)
6415 {
6416 	struct ath_hal *ah = sc->sc_ah;
6417 	u_int id = ad->ad_id & ATH_DIAG_ID;
6418 	void *indata = NULL;
6419 	void *outdata = NULL;
6420 	u_int32_t insize = ad->ad_in_size;
6421 	u_int32_t outsize = ad->ad_out_size;
6422 	int error = 0;
6423 
6424 	if (ad->ad_id & ATH_DIAG_IN) {
6425 		/*
6426 		 * Copy in data.
6427 		 */
6428 		indata = malloc(insize, M_TEMP, M_NOWAIT);
6429 		if (indata == NULL) {
6430 			error = ENOMEM;
6431 			goto bad;
6432 		}
6433 		error = copyin(ad->ad_in_data, indata, insize);
6434 		if (error)
6435 			goto bad;
6436 	}
6437 	if (ad->ad_id & ATH_DIAG_DYN) {
6438 		/*
6439 		 * Allocate a buffer for the results (otherwise the HAL
6440 		 * returns a pointer to a buffer where we can read the
6441 		 * results).  Note that we depend on the HAL leaving this
6442 		 * pointer for us to use below in reclaiming the buffer;
6443 		 * may want to be more defensive.
6444 		 */
6445 		outdata = malloc(outsize, M_TEMP, M_NOWAIT);
6446 		if (outdata == NULL) {
6447 			error = ENOMEM;
6448 			goto bad;
6449 		}
6450 	}
6451 
6452 
6453 	ATH_LOCK(sc);
6454 	if (id != HAL_DIAG_REGS)
6455 		ath_power_set_power_state(sc, HAL_PM_AWAKE);
6456 	ATH_UNLOCK(sc);
6457 
6458 	if (ath_hal_getdiagstate(ah, id, indata, insize, &outdata, &outsize)) {
6459 		if (outsize < ad->ad_out_size)
6460 			ad->ad_out_size = outsize;
6461 		if (outdata != NULL)
6462 			error = copyout(outdata, ad->ad_out_data,
6463 					ad->ad_out_size);
6464 	} else {
6465 		error = EINVAL;
6466 	}
6467 
6468 	ATH_LOCK(sc);
6469 	if (id != HAL_DIAG_REGS)
6470 		ath_power_restore_power_state(sc);
6471 	ATH_UNLOCK(sc);
6472 
6473 bad:
6474 	if ((ad->ad_id & ATH_DIAG_IN) && indata != NULL)
6475 		free(indata, M_TEMP);
6476 	if ((ad->ad_id & ATH_DIAG_DYN) && outdata != NULL)
6477 		free(outdata, M_TEMP);
6478 	return error;
6479 }
6480 #endif /* ATH_DIAGAPI */
6481 
6482 static int
6483 ath_ioctl(struct ifnet *ifp, u_long cmd, caddr_t data)
6484 {
6485 #define	IS_RUNNING(ifp) \
6486 	((ifp->if_flags & IFF_UP) && (ifp->if_drv_flags & IFF_DRV_RUNNING))
6487 	struct ath_softc *sc = ifp->if_softc;
6488 	struct ieee80211com *ic = ifp->if_l2com;
6489 	struct ifreq *ifr = (struct ifreq *)data;
6490 	const HAL_RATE_TABLE *rt;
6491 	int error = 0;
6492 
6493 	switch (cmd) {
6494 	case SIOCSIFFLAGS:
6495 		if (IS_RUNNING(ifp)) {
6496 			/*
6497 			 * To avoid rescanning another access point,
6498 			 * do not call ath_init() here.  Instead,
6499 			 * only reflect promisc mode settings.
6500 			 */
6501 			ATH_LOCK(sc);
6502 			ath_power_set_power_state(sc, HAL_PM_AWAKE);
6503 			ath_mode_init(sc);
6504 			ath_power_restore_power_state(sc);
6505 			ATH_UNLOCK(sc);
6506 		} else if (ifp->if_flags & IFF_UP) {
6507 			/*
6508 			 * Beware of being called during attach/detach
6509 			 * to reset promiscuous mode.  In that case we
6510 			 * will still be marked UP but not RUNNING.
6511 			 * However trying to re-init the interface
6512 			 * is the wrong thing to do as we've already
6513 			 * torn down much of our state.  There's
6514 			 * probably a better way to deal with this.
6515 			 */
6516 			if (!sc->sc_invalid)
6517 				ath_init(sc);	/* XXX lose error */
6518 		} else {
6519 			ATH_LOCK(sc);
6520 			ath_stop_locked(ifp);
6521 			if (!sc->sc_invalid)
6522 				ath_power_setpower(sc, HAL_PM_FULL_SLEEP);
6523 			ATH_UNLOCK(sc);
6524 		}
6525 		break;
6526 	case SIOCGIFMEDIA:
6527 	case SIOCSIFMEDIA:
6528 		error = ifmedia_ioctl(ifp, ifr, &ic->ic_media, cmd);
6529 		break;
6530 	case SIOCGATHSTATS:
6531 		/* NB: embed these numbers to get a consistent view */
6532 		sc->sc_stats.ast_tx_packets = ifp->if_opackets;
6533 		sc->sc_stats.ast_rx_packets = ifp->if_ipackets;
6534 		sc->sc_stats.ast_tx_rssi = ATH_RSSI(sc->sc_halstats.ns_avgtxrssi);
6535 		sc->sc_stats.ast_rx_rssi = ATH_RSSI(sc->sc_halstats.ns_avgrssi);
6536 #ifdef IEEE80211_SUPPORT_TDMA
6537 		sc->sc_stats.ast_tdma_tsfadjp = TDMA_AVG(sc->sc_avgtsfdeltap);
6538 		sc->sc_stats.ast_tdma_tsfadjm = TDMA_AVG(sc->sc_avgtsfdeltam);
6539 #endif
6540 		rt = sc->sc_currates;
6541 		sc->sc_stats.ast_tx_rate =
6542 		    rt->info[sc->sc_txrix].dot11Rate &~ IEEE80211_RATE_BASIC;
6543 		if (rt->info[sc->sc_txrix].phy & IEEE80211_T_HT)
6544 			sc->sc_stats.ast_tx_rate |= IEEE80211_RATE_MCS;
6545 		return copyout(&sc->sc_stats,
6546 		    ifr->ifr_data, sizeof (sc->sc_stats));
6547 	case SIOCGATHAGSTATS:
6548 		return copyout(&sc->sc_aggr_stats,
6549 		    ifr->ifr_data, sizeof (sc->sc_aggr_stats));
6550 	case SIOCZATHSTATS:
6551 		error = priv_check(curthread, PRIV_DRIVER);
6552 		if (error == 0) {
6553 			memset(&sc->sc_stats, 0, sizeof(sc->sc_stats));
6554 			memset(&sc->sc_aggr_stats, 0,
6555 			    sizeof(sc->sc_aggr_stats));
6556 			memset(&sc->sc_intr_stats, 0,
6557 			    sizeof(sc->sc_intr_stats));
6558 		}
6559 		break;
6560 #ifdef ATH_DIAGAPI
6561 	case SIOCGATHDIAG:
6562 		error = ath_ioctl_diag(sc, (struct ath_diag *) ifr);
6563 		break;
6564 	case SIOCGATHPHYERR:
6565 		error = ath_ioctl_phyerr(sc,(struct ath_diag*) ifr);
6566 		break;
6567 #endif
6568 	case SIOCGATHSPECTRAL:
6569 		error = ath_ioctl_spectral(sc,(struct ath_diag*) ifr);
6570 		break;
6571 	case SIOCGATHNODERATESTATS:
6572 		error = ath_ioctl_ratestats(sc, (struct ath_rateioctl *) ifr);
6573 		break;
6574 	case SIOCGIFADDR:
6575 		error = ether_ioctl(ifp, cmd, data);
6576 		break;
6577 	default:
6578 		error = EINVAL;
6579 		break;
6580 	}
6581 	return error;
6582 #undef IS_RUNNING
6583 }
6584 
6585 /*
6586  * Announce various information on device/driver attach.
6587  */
6588 static void
6589 ath_announce(struct ath_softc *sc)
6590 {
6591 	struct ifnet *ifp = sc->sc_ifp;
6592 	struct ath_hal *ah = sc->sc_ah;
6593 
6594 	if_printf(ifp, "AR%s mac %d.%d RF%s phy %d.%d\n",
6595 		ath_hal_mac_name(ah), ah->ah_macVersion, ah->ah_macRev,
6596 		ath_hal_rf_name(ah), ah->ah_phyRev >> 4, ah->ah_phyRev & 0xf);
6597 	if_printf(ifp, "2GHz radio: 0x%.4x; 5GHz radio: 0x%.4x\n",
6598 		ah->ah_analog2GhzRev, ah->ah_analog5GhzRev);
6599 	if (bootverbose) {
6600 		int i;
6601 		for (i = 0; i <= WME_AC_VO; i++) {
6602 			struct ath_txq *txq = sc->sc_ac2q[i];
6603 			if_printf(ifp, "Use hw queue %u for %s traffic\n",
6604 				txq->axq_qnum, ieee80211_wme_acnames[i]);
6605 		}
6606 		if_printf(ifp, "Use hw queue %u for CAB traffic\n",
6607 			sc->sc_cabq->axq_qnum);
6608 		if_printf(ifp, "Use hw queue %u for beacons\n", sc->sc_bhalq);
6609 	}
6610 	if (ath_rxbuf != ATH_RXBUF)
6611 		if_printf(ifp, "using %u rx buffers\n", ath_rxbuf);
6612 	if (ath_txbuf != ATH_TXBUF)
6613 		if_printf(ifp, "using %u tx buffers\n", ath_txbuf);
6614 	if (sc->sc_mcastkey && bootverbose)
6615 		if_printf(ifp, "using multicast key search\n");
6616 }
6617 
6618 static void
6619 ath_dfs_tasklet(void *p, int npending)
6620 {
6621 	struct ath_softc *sc = (struct ath_softc *) p;
6622 	struct ifnet *ifp = sc->sc_ifp;
6623 	struct ieee80211com *ic = ifp->if_l2com;
6624 
6625 	/*
6626 	 * If previous processing has found a radar event,
6627 	 * signal this to the net80211 layer to begin DFS
6628 	 * processing.
6629 	 */
6630 	if (ath_dfs_process_radar_event(sc, sc->sc_curchan)) {
6631 		/* DFS event found, initiate channel change */
6632 		/*
6633 		 * XXX doesn't currently tell us whether the event
6634 		 * XXX was found in the primary or extension
6635 		 * XXX channel!
6636 		 */
6637 		IEEE80211_LOCK(ic);
6638 		ieee80211_dfs_notify_radar(ic, sc->sc_curchan);
6639 		IEEE80211_UNLOCK(ic);
6640 	}
6641 }
6642 
6643 /*
6644  * Enable/disable power save.  This must be called with
6645  * no TX driver locks currently held, so it should only
6646  * be called from the RX path (which doesn't hold any
6647  * TX driver locks.)
6648  */
6649 static void
6650 ath_node_powersave(struct ieee80211_node *ni, int enable)
6651 {
6652 #ifdef	ATH_SW_PSQ
6653 	struct ath_node *an = ATH_NODE(ni);
6654 	struct ieee80211com *ic = ni->ni_ic;
6655 	struct ath_softc *sc = ic->ic_ifp->if_softc;
6656 	struct ath_vap *avp = ATH_VAP(ni->ni_vap);
6657 
6658 	/* XXX and no TXQ locks should be held here */
6659 
6660 	DPRINTF(sc, ATH_DEBUG_NODE_PWRSAVE, "%s: %6D: enable=%d\n",
6661 	    __func__,
6662 	    ni->ni_macaddr,
6663 	    ":",
6664 	    !! enable);
6665 
6666 	/* Suspend or resume software queue handling */
6667 	if (enable)
6668 		ath_tx_node_sleep(sc, an);
6669 	else
6670 		ath_tx_node_wakeup(sc, an);
6671 
6672 	/* Update net80211 state */
6673 	avp->av_node_ps(ni, enable);
6674 #else
6675 	struct ath_vap *avp = ATH_VAP(ni->ni_vap);
6676 
6677 	/* Update net80211 state */
6678 	avp->av_node_ps(ni, enable);
6679 #endif/* ATH_SW_PSQ */
6680 }
6681 
6682 /*
6683  * Notification from net80211 that the powersave queue state has
6684  * changed.
6685  *
6686  * Since the software queue also may have some frames:
6687  *
6688  * + if the node software queue has frames and the TID state
6689  *   is 0, we set the TIM;
6690  * + if the node and the stack are both empty, we clear the TIM bit.
6691  * + If the stack tries to set the bit, always set it.
6692  * + If the stack tries to clear the bit, only clear it if the
6693  *   software queue in question is also cleared.
6694  *
6695  * TODO: this is called during node teardown; so let's ensure this
6696  * is all correctly handled and that the TIM bit is cleared.
6697  * It may be that the node flush is called _AFTER_ the net80211
6698  * stack clears the TIM.
6699  *
6700  * Here is the racy part.  Since it's possible >1 concurrent,
6701  * overlapping TXes will appear complete with a TX completion in
6702  * another thread, it's possible that the concurrent TIM calls will
6703  * clash.  We can't hold the node lock here because setting the
6704  * TIM grabs the net80211 comlock and this may cause a LOR.
6705  * The solution is either to totally serialise _everything_ at
6706  * this point (ie, all TX, completion and any reset/flush go into
6707  * one taskqueue) or a new "ath TIM lock" needs to be created that
6708  * just wraps the driver state change and this call to avp->av_set_tim().
6709  *
6710  * The same race exists in the net80211 power save queue handling
6711  * as well.  Since multiple transmitting threads may queue frames
6712  * into the driver, as well as ps-poll and the driver transmitting
6713  * frames (and thus clearing the psq), it's quite possible that
6714  * a packet entering the PSQ and a ps-poll being handled will
6715  * race, causing the TIM to be cleared and not re-set.
6716  */
6717 static int
6718 ath_node_set_tim(struct ieee80211_node *ni, int enable)
6719 {
6720 #ifdef	ATH_SW_PSQ
6721 	struct ieee80211com *ic = ni->ni_ic;
6722 	struct ath_softc *sc = ic->ic_ifp->if_softc;
6723 	struct ath_node *an = ATH_NODE(ni);
6724 	struct ath_vap *avp = ATH_VAP(ni->ni_vap);
6725 	int changed = 0;
6726 
6727 	ATH_TX_LOCK(sc);
6728 	an->an_stack_psq = enable;
6729 
6730 	/*
6731 	 * This will get called for all operating modes,
6732 	 * even if avp->av_set_tim is unset.
6733 	 * It's currently set for hostap/ibss modes; but
6734 	 * the same infrastructure is used for both STA
6735 	 * and AP/IBSS node power save.
6736 	 */
6737 	if (avp->av_set_tim == NULL) {
6738 		ATH_TX_UNLOCK(sc);
6739 		return (0);
6740 	}
6741 
6742 	/*
6743 	 * If setting the bit, always set it here.
6744 	 * If clearing the bit, only clear it if the
6745 	 * software queue is also empty.
6746 	 *
6747 	 * If the node has left power save, just clear the TIM
6748 	 * bit regardless of the state of the power save queue.
6749 	 *
6750 	 * XXX TODO: although atomics are used, it's quite possible
6751 	 * that a race will occur between this and setting/clearing
6752 	 * in another thread.  TX completion will occur always in
6753 	 * one thread, however setting/clearing the TIM bit can come
6754 	 * from a variety of different process contexts!
6755 	 */
6756 	if (enable && an->an_tim_set == 1) {
6757 		DPRINTF(sc, ATH_DEBUG_NODE_PWRSAVE,
6758 		    "%s: %6D: enable=%d, tim_set=1, ignoring\n",
6759 		    __func__,
6760 		    ni->ni_macaddr,
6761 		    ":",
6762 		    enable);
6763 		ATH_TX_UNLOCK(sc);
6764 	} else if (enable) {
6765 		DPRINTF(sc, ATH_DEBUG_NODE_PWRSAVE,
6766 		    "%s: %6D: enable=%d, enabling TIM\n",
6767 		    __func__,
6768 		    ni->ni_macaddr,
6769 		    ":",
6770 		    enable);
6771 		an->an_tim_set = 1;
6772 		ATH_TX_UNLOCK(sc);
6773 		changed = avp->av_set_tim(ni, enable);
6774 	} else if (an->an_swq_depth == 0) {
6775 		/* disable */
6776 		DPRINTF(sc, ATH_DEBUG_NODE_PWRSAVE,
6777 		    "%s: %6D: enable=%d, an_swq_depth == 0, disabling\n",
6778 		    __func__,
6779 		    ni->ni_macaddr,
6780 		    ":",
6781 		    enable);
6782 		an->an_tim_set = 0;
6783 		ATH_TX_UNLOCK(sc);
6784 		changed = avp->av_set_tim(ni, enable);
6785 	} else if (! an->an_is_powersave) {
6786 		/*
6787 		 * disable regardless; the node isn't in powersave now
6788 		 */
6789 		DPRINTF(sc, ATH_DEBUG_NODE_PWRSAVE,
6790 		    "%s: %6D: enable=%d, an_pwrsave=0, disabling\n",
6791 		    __func__,
6792 		    ni->ni_macaddr,
6793 		    ":",
6794 		    enable);
6795 		an->an_tim_set = 0;
6796 		ATH_TX_UNLOCK(sc);
6797 		changed = avp->av_set_tim(ni, enable);
6798 	} else {
6799 		/*
6800 		 * psq disable, node is currently in powersave, node
6801 		 * software queue isn't empty, so don't clear the TIM bit
6802 		 * for now.
6803 		 */
6804 		ATH_TX_UNLOCK(sc);
6805 		DPRINTF(sc, ATH_DEBUG_NODE_PWRSAVE,
6806 		    "%s: %6D: enable=%d, an_swq_depth > 0, ignoring\n",
6807 		    __func__,
6808 		    ni->ni_macaddr,
6809 		    ":",
6810 		    enable);
6811 		changed = 0;
6812 	}
6813 
6814 	return (changed);
6815 #else
6816 	struct ath_vap *avp = ATH_VAP(ni->ni_vap);
6817 
6818 	/*
6819 	 * Some operating modes don't set av_set_tim(), so don't
6820 	 * update it here.
6821 	 */
6822 	if (avp->av_set_tim == NULL)
6823 		return (0);
6824 
6825 	return (avp->av_set_tim(ni, enable));
6826 #endif /* ATH_SW_PSQ */
6827 }
6828 
6829 /*
6830  * Set or update the TIM from the software queue.
6831  *
6832  * Check the software queue depth before attempting to do lock
6833  * anything; that avoids trying to obtain the lock.  Then,
6834  * re-check afterwards to ensure nothing has changed in the
6835  * meantime.
6836  *
6837  * set:   This is designed to be called from the TX path, after
6838  *        a frame has been queued; to see if the swq > 0.
6839  *
6840  * clear: This is designed to be called from the buffer completion point
6841  *        (right now it's ath_tx_default_comp()) where the state of
6842  *        a software queue has changed.
6843  *
6844  * It makes sense to place it at buffer free / completion rather
6845  * than after each software queue operation, as there's no real
6846  * point in churning the TIM bit as the last frames in the software
6847  * queue are transmitted.  If they fail and we retry them, we'd
6848  * just be setting the TIM bit again anyway.
6849  */
6850 void
6851 ath_tx_update_tim(struct ath_softc *sc, struct ieee80211_node *ni,
6852      int enable)
6853 {
6854 #ifdef	ATH_SW_PSQ
6855 	struct ath_node *an;
6856 	struct ath_vap *avp;
6857 
6858 	/* Don't do this for broadcast/etc frames */
6859 	if (ni == NULL)
6860 		return;
6861 
6862 	an = ATH_NODE(ni);
6863 	avp = ATH_VAP(ni->ni_vap);
6864 
6865 	/*
6866 	 * And for operating modes without the TIM handler set, let's
6867 	 * just skip those.
6868 	 */
6869 	if (avp->av_set_tim == NULL)
6870 		return;
6871 
6872 	ATH_TX_LOCK_ASSERT(sc);
6873 
6874 	if (enable) {
6875 		if (an->an_is_powersave &&
6876 		    an->an_tim_set == 0 &&
6877 		    an->an_swq_depth != 0) {
6878 			DPRINTF(sc, ATH_DEBUG_NODE_PWRSAVE,
6879 			    "%s: %6D: swq_depth>0, tim_set=0, set!\n",
6880 			    __func__,
6881 			    ni->ni_macaddr,
6882 			    ":");
6883 			an->an_tim_set = 1;
6884 			(void) avp->av_set_tim(ni, 1);
6885 		}
6886 	} else {
6887 		/*
6888 		 * Don't bother grabbing the lock unless the queue is empty.
6889 		 */
6890 		if (&an->an_swq_depth != 0)
6891 			return;
6892 
6893 		if (an->an_is_powersave &&
6894 		    an->an_stack_psq == 0 &&
6895 		    an->an_tim_set == 1 &&
6896 		    an->an_swq_depth == 0) {
6897 			DPRINTF(sc, ATH_DEBUG_NODE_PWRSAVE,
6898 			    "%s: %6D: swq_depth=0, tim_set=1, psq_set=0,"
6899 			    " clear!\n",
6900 			    __func__,
6901 			    ni->ni_macaddr,
6902 			    ":");
6903 			an->an_tim_set = 0;
6904 			(void) avp->av_set_tim(ni, 0);
6905 		}
6906 	}
6907 #else
6908 	return;
6909 #endif	/* ATH_SW_PSQ */
6910 }
6911 
6912 /*
6913  * Received a ps-poll frame from net80211.
6914  *
6915  * Here we get a chance to serve out a software-queued frame ourselves
6916  * before we punt it to net80211 to transmit us one itself - either
6917  * because there's traffic in the net80211 psq, or a NULL frame to
6918  * indicate there's nothing else.
6919  */
6920 static void
6921 ath_node_recv_pspoll(struct ieee80211_node *ni, struct mbuf *m)
6922 {
6923 #ifdef	ATH_SW_PSQ
6924 	struct ath_node *an;
6925 	struct ath_vap *avp;
6926 	struct ieee80211com *ic = ni->ni_ic;
6927 	struct ath_softc *sc = ic->ic_ifp->if_softc;
6928 	int tid;
6929 
6930 	/* Just paranoia */
6931 	if (ni == NULL)
6932 		return;
6933 
6934 	/*
6935 	 * Unassociated (temporary node) station.
6936 	 */
6937 	if (ni->ni_associd == 0)
6938 		return;
6939 
6940 	/*
6941 	 * We do have an active node, so let's begin looking into it.
6942 	 */
6943 	an = ATH_NODE(ni);
6944 	avp = ATH_VAP(ni->ni_vap);
6945 
6946 	/*
6947 	 * For now, we just call the original ps-poll method.
6948 	 * Once we're ready to flip this on:
6949 	 *
6950 	 * + Set leak to 1, as no matter what we're going to have
6951 	 *   to send a frame;
6952 	 * + Check the software queue and if there's something in it,
6953 	 *   schedule the highest TID thas has traffic from this node.
6954 	 *   Then make sure we schedule the software scheduler to
6955 	 *   run so it picks up said frame.
6956 	 *
6957 	 * That way whatever happens, we'll at least send _a_ frame
6958 	 * to the given node.
6959 	 *
6960 	 * Again, yes, it's crappy QoS if the node has multiple
6961 	 * TIDs worth of traffic - but let's get it working first
6962 	 * before we optimise it.
6963 	 *
6964 	 * Also yes, there's definitely latency here - we're not
6965 	 * direct dispatching to the hardware in this path (and
6966 	 * we're likely being called from the packet receive path,
6967 	 * so going back into TX may be a little hairy!) but again
6968 	 * I'd like to get this working first before optimising
6969 	 * turn-around time.
6970 	 */
6971 
6972 	ATH_TX_LOCK(sc);
6973 
6974 	/*
6975 	 * Legacy - we're called and the node isn't asleep.
6976 	 * Immediately punt.
6977 	 */
6978 	if (! an->an_is_powersave) {
6979 		DPRINTF(sc, ATH_DEBUG_NODE_PWRSAVE,
6980 		    "%s: %6D: not in powersave?\n",
6981 		    __func__,
6982 		    ni->ni_macaddr,
6983 		    ":");
6984 		ATH_TX_UNLOCK(sc);
6985 		avp->av_recv_pspoll(ni, m);
6986 		return;
6987 	}
6988 
6989 	/*
6990 	 * We're in powersave.
6991 	 *
6992 	 * Leak a frame.
6993 	 */
6994 	an->an_leak_count = 1;
6995 
6996 	/*
6997 	 * Now, if there's no frames in the node, just punt to
6998 	 * recv_pspoll.
6999 	 *
7000 	 * Don't bother checking if the TIM bit is set, we really
7001 	 * only care if there are any frames here!
7002 	 */
7003 	if (an->an_swq_depth == 0) {
7004 		ATH_TX_UNLOCK(sc);
7005 		DPRINTF(sc, ATH_DEBUG_NODE_PWRSAVE,
7006 		    "%s: %6D: SWQ empty; punting to net80211\n",
7007 		    __func__,
7008 		    ni->ni_macaddr,
7009 		    ":");
7010 		avp->av_recv_pspoll(ni, m);
7011 		return;
7012 	}
7013 
7014 	/*
7015 	 * Ok, let's schedule the highest TID that has traffic
7016 	 * and then schedule something.
7017 	 */
7018 	for (tid = IEEE80211_TID_SIZE - 1; tid >= 0; tid--) {
7019 		struct ath_tid *atid = &an->an_tid[tid];
7020 		/*
7021 		 * No frames? Skip.
7022 		 */
7023 		if (atid->axq_depth == 0)
7024 			continue;
7025 		ath_tx_tid_sched(sc, atid);
7026 		/*
7027 		 * XXX we could do a direct call to the TXQ
7028 		 * scheduler code here to optimise latency
7029 		 * at the expense of a REALLY deep callstack.
7030 		 */
7031 		ATH_TX_UNLOCK(sc);
7032 		taskqueue_enqueue(sc->sc_tq, &sc->sc_txqtask);
7033 		DPRINTF(sc, ATH_DEBUG_NODE_PWRSAVE,
7034 		    "%s: %6D: leaking frame to TID %d\n",
7035 		    __func__,
7036 		    ni->ni_macaddr,
7037 		    ":",
7038 		    tid);
7039 		return;
7040 	}
7041 
7042 	ATH_TX_UNLOCK(sc);
7043 
7044 	/*
7045 	 * XXX nothing in the TIDs at this point? Eek.
7046 	 */
7047 	DPRINTF(sc, ATH_DEBUG_NODE_PWRSAVE,
7048 	    "%s: %6D: TIDs empty, but ath_node showed traffic?!\n",
7049 	    __func__,
7050 	    ni->ni_macaddr,
7051 	    ":");
7052 	avp->av_recv_pspoll(ni, m);
7053 #else
7054 	avp->av_recv_pspoll(ni, m);
7055 #endif	/* ATH_SW_PSQ */
7056 }
7057 
7058 MODULE_VERSION(if_ath, 1);
7059 MODULE_DEPEND(if_ath, wlan, 1, 1, 1);          /* 802.11 media layer */
7060 #if	defined(IEEE80211_ALQ) || defined(AH_DEBUG_ALQ)
7061 MODULE_DEPEND(if_ath, alq, 1, 1, 1);
7062 #endif
7063