xref: /freebsd/sys/dev/ath/if_ath.c (revision e72055b7feba695a760d45f01f0f8268b1cb4a74)
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 		/* XXX Do all frames from all vaps/nodes need draining here? */
1603 		ath_stoprecv(sc, 1);		/* stop recv side */
1604 		ath_draintxq(sc, ATH_RESET_DEFAULT);		/* stop hw xmit 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 		/* XXX we should stop RX regardless of whether it's valid */
2507 		if (!sc->sc_invalid) {
2508 			ath_stoprecv(sc, 1);
2509 			ath_hal_phydisable(ah);
2510 		} else
2511 			sc->sc_rxlink = NULL;
2512 		ath_draintxq(sc, ATH_RESET_DEFAULT);
2513 		ath_beacon_free(sc);	/* XXX not needed */
2514 	}
2515 
2516 	/* And now, restore the current power state */
2517 	ath_power_restore_power_state(sc);
2518 }
2519 
2520 /*
2521  * Wait until all pending TX/RX has completed.
2522  *
2523  * This waits until all existing transmit, receive and interrupts
2524  * have completed.  It's assumed that the caller has first
2525  * grabbed the reset lock so it doesn't try to do overlapping
2526  * chip resets.
2527  */
2528 #define	MAX_TXRX_ITERATIONS	100
2529 static void
2530 ath_txrx_stop_locked(struct ath_softc *sc)
2531 {
2532 	int i = MAX_TXRX_ITERATIONS;
2533 
2534 	ATH_UNLOCK_ASSERT(sc);
2535 	ATH_PCU_LOCK_ASSERT(sc);
2536 
2537 	/*
2538 	 * Sleep until all the pending operations have completed.
2539 	 *
2540 	 * The caller must ensure that reset has been incremented
2541 	 * or the pending operations may continue being queued.
2542 	 */
2543 	while (sc->sc_rxproc_cnt || sc->sc_txproc_cnt ||
2544 	    sc->sc_txstart_cnt || sc->sc_intr_cnt) {
2545 		if (i <= 0)
2546 			break;
2547 		msleep(sc, &sc->sc_pcu_mtx, 0, "ath_txrx_stop",
2548 		    msecs_to_ticks(10));
2549 		i--;
2550 	}
2551 
2552 	if (i <= 0)
2553 		device_printf(sc->sc_dev,
2554 		    "%s: didn't finish after %d iterations\n",
2555 		    __func__, MAX_TXRX_ITERATIONS);
2556 }
2557 #undef	MAX_TXRX_ITERATIONS
2558 
2559 #if 0
2560 static void
2561 ath_txrx_stop(struct ath_softc *sc)
2562 {
2563 	ATH_UNLOCK_ASSERT(sc);
2564 	ATH_PCU_UNLOCK_ASSERT(sc);
2565 
2566 	ATH_PCU_LOCK(sc);
2567 	ath_txrx_stop_locked(sc);
2568 	ATH_PCU_UNLOCK(sc);
2569 }
2570 #endif
2571 
2572 static void
2573 ath_txrx_start(struct ath_softc *sc)
2574 {
2575 
2576 	taskqueue_unblock(sc->sc_tq);
2577 }
2578 
2579 /*
2580  * Grab the reset lock, and wait around until noone else
2581  * is trying to do anything with it.
2582  *
2583  * This is totally horrible but we can't hold this lock for
2584  * long enough to do TX/RX or we end up with net80211/ip stack
2585  * LORs and eventual deadlock.
2586  *
2587  * "dowait" signals whether to spin, waiting for the reset
2588  * lock count to reach 0. This should (for now) only be used
2589  * during the reset path, as the rest of the code may not
2590  * be locking-reentrant enough to behave correctly.
2591  *
2592  * Another, cleaner way should be found to serialise all of
2593  * these operations.
2594  */
2595 #define	MAX_RESET_ITERATIONS	25
2596 static int
2597 ath_reset_grablock(struct ath_softc *sc, int dowait)
2598 {
2599 	int w = 0;
2600 	int i = MAX_RESET_ITERATIONS;
2601 
2602 	ATH_PCU_LOCK_ASSERT(sc);
2603 	do {
2604 		if (sc->sc_inreset_cnt == 0) {
2605 			w = 1;
2606 			break;
2607 		}
2608 		if (dowait == 0) {
2609 			w = 0;
2610 			break;
2611 		}
2612 		ATH_PCU_UNLOCK(sc);
2613 		/*
2614 		 * 1 tick is likely not enough time for long calibrations
2615 		 * to complete.  So we should wait quite a while.
2616 		 */
2617 		pause("ath_reset_grablock", msecs_to_ticks(100));
2618 		i--;
2619 		ATH_PCU_LOCK(sc);
2620 	} while (i > 0);
2621 
2622 	/*
2623 	 * We always increment the refcounter, regardless
2624 	 * of whether we succeeded to get it in an exclusive
2625 	 * way.
2626 	 */
2627 	sc->sc_inreset_cnt++;
2628 
2629 	if (i <= 0)
2630 		device_printf(sc->sc_dev,
2631 		    "%s: didn't finish after %d iterations\n",
2632 		    __func__, MAX_RESET_ITERATIONS);
2633 
2634 	if (w == 0)
2635 		device_printf(sc->sc_dev,
2636 		    "%s: warning, recursive reset path!\n",
2637 		    __func__);
2638 
2639 	return w;
2640 }
2641 #undef MAX_RESET_ITERATIONS
2642 
2643 /*
2644  * XXX TODO: write ath_reset_releaselock
2645  */
2646 
2647 static void
2648 ath_stop(struct ifnet *ifp)
2649 {
2650 	struct ath_softc *sc = ifp->if_softc;
2651 
2652 	ATH_LOCK(sc);
2653 	ath_stop_locked(ifp);
2654 	ATH_UNLOCK(sc);
2655 }
2656 
2657 /*
2658  * Reset the hardware w/o losing operational state.  This is
2659  * basically a more efficient way of doing ath_stop, ath_init,
2660  * followed by state transitions to the current 802.11
2661  * operational state.  Used to recover from various errors and
2662  * to reset or reload hardware state.
2663  */
2664 int
2665 ath_reset(struct ifnet *ifp, ATH_RESET_TYPE reset_type)
2666 {
2667 	struct ath_softc *sc = ifp->if_softc;
2668 	struct ieee80211com *ic = ifp->if_l2com;
2669 	struct ath_hal *ah = sc->sc_ah;
2670 	HAL_STATUS status;
2671 	int i;
2672 
2673 	DPRINTF(sc, ATH_DEBUG_RESET, "%s: called\n", __func__);
2674 
2675 	/* Ensure ATH_LOCK isn't held; ath_rx_proc can't be locked */
2676 	ATH_PCU_UNLOCK_ASSERT(sc);
2677 	ATH_UNLOCK_ASSERT(sc);
2678 
2679 	/* Try to (stop any further TX/RX from occuring */
2680 	taskqueue_block(sc->sc_tq);
2681 
2682 	/*
2683 	 * Wake the hardware up.
2684 	 */
2685 	ATH_LOCK(sc);
2686 	ath_power_set_power_state(sc, HAL_PM_AWAKE);
2687 	ATH_UNLOCK(sc);
2688 
2689 	ATH_PCU_LOCK(sc);
2690 
2691 	/*
2692 	 * Grab the reset lock before TX/RX is stopped.
2693 	 *
2694 	 * This is needed to ensure that when the TX/RX actually does finish,
2695 	 * no further TX/RX/reset runs in parallel with this.
2696 	 */
2697 	if (ath_reset_grablock(sc, 1) == 0) {
2698 		device_printf(sc->sc_dev, "%s: concurrent reset! Danger!\n",
2699 		    __func__);
2700 	}
2701 
2702 	/* disable interrupts */
2703 	ath_hal_intrset(ah, 0);
2704 
2705 	/*
2706 	 * Now, ensure that any in progress TX/RX completes before we
2707 	 * continue.
2708 	 */
2709 	ath_txrx_stop_locked(sc);
2710 
2711 	ATH_PCU_UNLOCK(sc);
2712 
2713 	/*
2714 	 * Regardless of whether we're doing a no-loss flush or
2715 	 * not, stop the PCU and handle what's in the RX queue.
2716 	 * That way frames aren't dropped which shouldn't be.
2717 	 */
2718 	ath_stoprecv(sc, (reset_type != ATH_RESET_NOLOSS));
2719 	ath_rx_flush(sc);
2720 
2721 	/*
2722 	 * Should now wait for pending TX/RX to complete
2723 	 * and block future ones from occuring. This needs to be
2724 	 * done before the TX queue is drained.
2725 	 */
2726 	ath_draintxq(sc, reset_type);	/* stop xmit side */
2727 
2728 	ath_settkipmic(sc);		/* configure TKIP MIC handling */
2729 	/* NB: indicate channel change so we do a full reset */
2730 	ath_update_chainmasks(sc, ic->ic_curchan);
2731 	ath_hal_setchainmasks(sc->sc_ah, sc->sc_cur_txchainmask,
2732 	    sc->sc_cur_rxchainmask);
2733 	if (!ath_hal_reset(ah, sc->sc_opmode, ic->ic_curchan, AH_TRUE, &status))
2734 		if_printf(ifp, "%s: unable to reset hardware; hal status %u\n",
2735 			__func__, status);
2736 	sc->sc_diversity = ath_hal_getdiversity(ah);
2737 
2738 	/* Let DFS at it in case it's a DFS channel */
2739 	ath_dfs_radar_enable(sc, ic->ic_curchan);
2740 
2741 	/* Let spectral at in case spectral is enabled */
2742 	ath_spectral_enable(sc, ic->ic_curchan);
2743 
2744 	/*
2745 	 * Let bluetooth coexistence at in case it's needed for this channel
2746 	 */
2747 	ath_btcoex_enable(sc, ic->ic_curchan);
2748 
2749 	/*
2750 	 * If we're doing TDMA, enforce the TXOP limitation for chips that
2751 	 * support it.
2752 	 */
2753 	if (sc->sc_hasenforcetxop && sc->sc_tdma)
2754 		ath_hal_setenforcetxop(sc->sc_ah, 1);
2755 	else
2756 		ath_hal_setenforcetxop(sc->sc_ah, 0);
2757 
2758 	if (ath_startrecv(sc) != 0)	/* restart recv */
2759 		if_printf(ifp, "%s: unable to start recv logic\n", __func__);
2760 	/*
2761 	 * We may be doing a reset in response to an ioctl
2762 	 * that changes the channel so update any state that
2763 	 * might change as a result.
2764 	 */
2765 	ath_chan_change(sc, ic->ic_curchan);
2766 	if (sc->sc_beacons) {		/* restart beacons */
2767 #ifdef IEEE80211_SUPPORT_TDMA
2768 		if (sc->sc_tdma)
2769 			ath_tdma_config(sc, NULL);
2770 		else
2771 #endif
2772 			ath_beacon_config(sc, NULL);
2773 	}
2774 
2775 	/*
2776 	 * Release the reset lock and re-enable interrupts here.
2777 	 * If an interrupt was being processed in ath_intr(),
2778 	 * it would disable interrupts at this point. So we have
2779 	 * to atomically enable interrupts and decrement the
2780 	 * reset counter - this way ath_intr() doesn't end up
2781 	 * disabling interrupts without a corresponding enable
2782 	 * in the rest or channel change path.
2783 	 *
2784 	 * Grab the TX reference in case we need to transmit.
2785 	 * That way a parallel transmit doesn't.
2786 	 */
2787 	ATH_PCU_LOCK(sc);
2788 	sc->sc_inreset_cnt--;
2789 	sc->sc_txstart_cnt++;
2790 	/* XXX only do this if sc_inreset_cnt == 0? */
2791 	ath_hal_intrset(ah, sc->sc_imask);
2792 	ATH_PCU_UNLOCK(sc);
2793 
2794 	/*
2795 	 * TX and RX can be started here. If it were started with
2796 	 * sc_inreset_cnt > 0, the TX and RX path would abort.
2797 	 * Thus if this is a nested call through the reset or
2798 	 * channel change code, TX completion will occur but
2799 	 * RX completion and ath_start / ath_tx_start will not
2800 	 * run.
2801 	 */
2802 
2803 	/* Restart TX/RX as needed */
2804 	ath_txrx_start(sc);
2805 
2806 	/* XXX TODO: we need to hold the tx refcount here! */
2807 
2808 	/* Restart TX completion and pending TX */
2809 	if (reset_type == ATH_RESET_NOLOSS) {
2810 		for (i = 0; i < HAL_NUM_TX_QUEUES; i++) {
2811 			if (ATH_TXQ_SETUP(sc, i)) {
2812 				ATH_TXQ_LOCK(&sc->sc_txq[i]);
2813 				ath_txq_restart_dma(sc, &sc->sc_txq[i]);
2814 				ATH_TXQ_UNLOCK(&sc->sc_txq[i]);
2815 
2816 				ATH_TX_LOCK(sc);
2817 				ath_txq_sched(sc, &sc->sc_txq[i]);
2818 				ATH_TX_UNLOCK(sc);
2819 			}
2820 		}
2821 	}
2822 
2823 	/*
2824 	 * This may have been set during an ath_start() call which
2825 	 * set this once it detected a concurrent TX was going on.
2826 	 * So, clear it.
2827 	 */
2828 	IF_LOCK(&ifp->if_snd);
2829 	ifp->if_drv_flags &= ~IFF_DRV_OACTIVE;
2830 	IF_UNLOCK(&ifp->if_snd);
2831 
2832 	ATH_LOCK(sc);
2833 	ath_power_restore_power_state(sc);
2834 	ATH_UNLOCK(sc);
2835 
2836 	ATH_PCU_LOCK(sc);
2837 	sc->sc_txstart_cnt--;
2838 	ATH_PCU_UNLOCK(sc);
2839 
2840 	/* Handle any frames in the TX queue */
2841 	/*
2842 	 * XXX should this be done by the caller, rather than
2843 	 * ath_reset() ?
2844 	 */
2845 	ath_tx_kick(sc);		/* restart xmit */
2846 	return 0;
2847 }
2848 
2849 static int
2850 ath_reset_vap(struct ieee80211vap *vap, u_long cmd)
2851 {
2852 	struct ieee80211com *ic = vap->iv_ic;
2853 	struct ifnet *ifp = ic->ic_ifp;
2854 	struct ath_softc *sc = ifp->if_softc;
2855 	struct ath_hal *ah = sc->sc_ah;
2856 
2857 	switch (cmd) {
2858 	case IEEE80211_IOC_TXPOWER:
2859 		/*
2860 		 * If per-packet TPC is enabled, then we have nothing
2861 		 * to do; otherwise we need to force the global limit.
2862 		 * All this can happen directly; no need to reset.
2863 		 */
2864 		if (!ath_hal_gettpc(ah))
2865 			ath_hal_settxpowlimit(ah, ic->ic_txpowlimit);
2866 		return 0;
2867 	}
2868 	/* XXX? Full or NOLOSS? */
2869 	return ath_reset(ifp, ATH_RESET_FULL);
2870 }
2871 
2872 struct ath_buf *
2873 _ath_getbuf_locked(struct ath_softc *sc, ath_buf_type_t btype)
2874 {
2875 	struct ath_buf *bf;
2876 
2877 	ATH_TXBUF_LOCK_ASSERT(sc);
2878 
2879 	if (btype == ATH_BUFTYPE_MGMT)
2880 		bf = TAILQ_FIRST(&sc->sc_txbuf_mgmt);
2881 	else
2882 		bf = TAILQ_FIRST(&sc->sc_txbuf);
2883 
2884 	if (bf == NULL) {
2885 		sc->sc_stats.ast_tx_getnobuf++;
2886 	} else {
2887 		if (bf->bf_flags & ATH_BUF_BUSY) {
2888 			sc->sc_stats.ast_tx_getbusybuf++;
2889 			bf = NULL;
2890 		}
2891 	}
2892 
2893 	if (bf != NULL && (bf->bf_flags & ATH_BUF_BUSY) == 0) {
2894 		if (btype == ATH_BUFTYPE_MGMT)
2895 			TAILQ_REMOVE(&sc->sc_txbuf_mgmt, bf, bf_list);
2896 		else {
2897 			TAILQ_REMOVE(&sc->sc_txbuf, bf, bf_list);
2898 			sc->sc_txbuf_cnt--;
2899 
2900 			/*
2901 			 * This shuldn't happen; however just to be
2902 			 * safe print a warning and fudge the txbuf
2903 			 * count.
2904 			 */
2905 			if (sc->sc_txbuf_cnt < 0) {
2906 				device_printf(sc->sc_dev,
2907 				    "%s: sc_txbuf_cnt < 0?\n",
2908 				    __func__);
2909 				sc->sc_txbuf_cnt = 0;
2910 			}
2911 		}
2912 	} else
2913 		bf = NULL;
2914 
2915 	if (bf == NULL) {
2916 		/* XXX should check which list, mgmt or otherwise */
2917 		DPRINTF(sc, ATH_DEBUG_XMIT, "%s: %s\n", __func__,
2918 		    TAILQ_FIRST(&sc->sc_txbuf) == NULL ?
2919 			"out of xmit buffers" : "xmit buffer busy");
2920 		return NULL;
2921 	}
2922 
2923 	/* XXX TODO: should do this at buffer list initialisation */
2924 	/* XXX (then, ensure the buffer has the right flag set) */
2925 	bf->bf_flags = 0;
2926 	if (btype == ATH_BUFTYPE_MGMT)
2927 		bf->bf_flags |= ATH_BUF_MGMT;
2928 	else
2929 		bf->bf_flags &= (~ATH_BUF_MGMT);
2930 
2931 	/* Valid bf here; clear some basic fields */
2932 	bf->bf_next = NULL;	/* XXX just to be sure */
2933 	bf->bf_last = NULL;	/* XXX again, just to be sure */
2934 	bf->bf_comp = NULL;	/* XXX again, just to be sure */
2935 	bzero(&bf->bf_state, sizeof(bf->bf_state));
2936 
2937 	/*
2938 	 * Track the descriptor ID only if doing EDMA
2939 	 */
2940 	if (sc->sc_isedma) {
2941 		bf->bf_descid = sc->sc_txbuf_descid;
2942 		sc->sc_txbuf_descid++;
2943 	}
2944 
2945 	return bf;
2946 }
2947 
2948 /*
2949  * When retrying a software frame, buffers marked ATH_BUF_BUSY
2950  * can't be thrown back on the queue as they could still be
2951  * in use by the hardware.
2952  *
2953  * This duplicates the buffer, or returns NULL.
2954  *
2955  * The descriptor is also copied but the link pointers and
2956  * the DMA segments aren't copied; this frame should thus
2957  * be again passed through the descriptor setup/chain routines
2958  * so the link is correct.
2959  *
2960  * The caller must free the buffer using ath_freebuf().
2961  */
2962 struct ath_buf *
2963 ath_buf_clone(struct ath_softc *sc, struct ath_buf *bf)
2964 {
2965 	struct ath_buf *tbf;
2966 
2967 	tbf = ath_getbuf(sc,
2968 	    (bf->bf_flags & ATH_BUF_MGMT) ?
2969 	     ATH_BUFTYPE_MGMT : ATH_BUFTYPE_NORMAL);
2970 	if (tbf == NULL)
2971 		return NULL;	/* XXX failure? Why? */
2972 
2973 	/* Copy basics */
2974 	tbf->bf_next = NULL;
2975 	tbf->bf_nseg = bf->bf_nseg;
2976 	tbf->bf_flags = bf->bf_flags & ATH_BUF_FLAGS_CLONE;
2977 	tbf->bf_status = bf->bf_status;
2978 	tbf->bf_m = bf->bf_m;
2979 	tbf->bf_node = bf->bf_node;
2980 	KASSERT((bf->bf_node != NULL), ("%s: bf_node=NULL!", __func__));
2981 	/* will be setup by the chain/setup function */
2982 	tbf->bf_lastds = NULL;
2983 	/* for now, last == self */
2984 	tbf->bf_last = tbf;
2985 	tbf->bf_comp = bf->bf_comp;
2986 
2987 	/* NOTE: DMA segments will be setup by the setup/chain functions */
2988 
2989 	/* The caller has to re-init the descriptor + links */
2990 
2991 	/*
2992 	 * Free the DMA mapping here, before we NULL the mbuf.
2993 	 * We must only call bus_dmamap_unload() once per mbuf chain
2994 	 * or behaviour is undefined.
2995 	 */
2996 	if (bf->bf_m != NULL) {
2997 		/*
2998 		 * XXX is this POSTWRITE call required?
2999 		 */
3000 		bus_dmamap_sync(sc->sc_dmat, bf->bf_dmamap,
3001 		    BUS_DMASYNC_POSTWRITE);
3002 		bus_dmamap_unload(sc->sc_dmat, bf->bf_dmamap);
3003 	}
3004 
3005 	bf->bf_m = NULL;
3006 	bf->bf_node = NULL;
3007 
3008 	/* Copy state */
3009 	memcpy(&tbf->bf_state, &bf->bf_state, sizeof(bf->bf_state));
3010 
3011 	return tbf;
3012 }
3013 
3014 struct ath_buf *
3015 ath_getbuf(struct ath_softc *sc, ath_buf_type_t btype)
3016 {
3017 	struct ath_buf *bf;
3018 
3019 	ATH_TXBUF_LOCK(sc);
3020 	bf = _ath_getbuf_locked(sc, btype);
3021 	/*
3022 	 * If a mgmt buffer was requested but we're out of those,
3023 	 * try requesting a normal one.
3024 	 */
3025 	if (bf == NULL && btype == ATH_BUFTYPE_MGMT)
3026 		bf = _ath_getbuf_locked(sc, ATH_BUFTYPE_NORMAL);
3027 	ATH_TXBUF_UNLOCK(sc);
3028 	if (bf == NULL) {
3029 		struct ifnet *ifp = sc->sc_ifp;
3030 
3031 		DPRINTF(sc, ATH_DEBUG_XMIT, "%s: stop queue\n", __func__);
3032 		sc->sc_stats.ast_tx_qstop++;
3033 		IF_LOCK(&ifp->if_snd);
3034 		ifp->if_drv_flags |= IFF_DRV_OACTIVE;
3035 		IF_UNLOCK(&ifp->if_snd);
3036 	}
3037 	return bf;
3038 }
3039 
3040 static void
3041 ath_qflush(struct ifnet *ifp)
3042 {
3043 
3044 	/* XXX TODO */
3045 }
3046 
3047 /*
3048  * Transmit a single frame.
3049  *
3050  * net80211 will free the node reference if the transmit
3051  * fails, so don't free the node reference here.
3052  */
3053 static int
3054 ath_transmit(struct ifnet *ifp, struct mbuf *m)
3055 {
3056 	struct ieee80211com *ic = ifp->if_l2com;
3057 	struct ath_softc *sc = ic->ic_ifp->if_softc;
3058 	struct ieee80211_node *ni;
3059 	struct mbuf *next;
3060 	struct ath_buf *bf;
3061 	ath_bufhead frags;
3062 	int retval = 0;
3063 
3064 	/*
3065 	 * Tell the reset path that we're currently transmitting.
3066 	 */
3067 	ATH_PCU_LOCK(sc);
3068 	if (sc->sc_inreset_cnt > 0) {
3069 		DPRINTF(sc, ATH_DEBUG_XMIT,
3070 		    "%s: sc_inreset_cnt > 0; bailing\n", __func__);
3071 		ATH_PCU_UNLOCK(sc);
3072 		IF_LOCK(&ifp->if_snd);
3073 		sc->sc_stats.ast_tx_qstop++;
3074 		ifp->if_drv_flags |= IFF_DRV_OACTIVE;
3075 		IF_UNLOCK(&ifp->if_snd);
3076 		ATH_KTR(sc, ATH_KTR_TX, 0, "ath_start_task: OACTIVE, finish");
3077 		return (ENOBUFS);	/* XXX should be EINVAL or? */
3078 	}
3079 	sc->sc_txstart_cnt++;
3080 	ATH_PCU_UNLOCK(sc);
3081 
3082 	/* Wake the hardware up already */
3083 	ATH_LOCK(sc);
3084 	ath_power_set_power_state(sc, HAL_PM_AWAKE);
3085 	ATH_UNLOCK(sc);
3086 
3087 	ATH_KTR(sc, ATH_KTR_TX, 0, "ath_transmit: start");
3088 	/*
3089 	 * Grab the TX lock - it's ok to do this here; we haven't
3090 	 * yet started transmitting.
3091 	 */
3092 	ATH_TX_LOCK(sc);
3093 
3094 	/*
3095 	 * Node reference, if there's one.
3096 	 */
3097 	ni = (struct ieee80211_node *) m->m_pkthdr.rcvif;
3098 
3099 	/*
3100 	 * Enforce how deep a node queue can get.
3101 	 *
3102 	 * XXX it would be nicer if we kept an mbuf queue per
3103 	 * node and only whacked them into ath_bufs when we
3104 	 * are ready to schedule some traffic from them.
3105 	 * .. that may come later.
3106 	 *
3107 	 * XXX we should also track the per-node hardware queue
3108 	 * depth so it is easy to limit the _SUM_ of the swq and
3109 	 * hwq frames.  Since we only schedule two HWQ frames
3110 	 * at a time, this should be OK for now.
3111 	 */
3112 	if ((!(m->m_flags & M_EAPOL)) &&
3113 	    (ATH_NODE(ni)->an_swq_depth > sc->sc_txq_node_maxdepth)) {
3114 		sc->sc_stats.ast_tx_nodeq_overflow++;
3115 		m_freem(m);
3116 		m = NULL;
3117 		retval = ENOBUFS;
3118 		goto finish;
3119 	}
3120 
3121 	/*
3122 	 * Check how many TX buffers are available.
3123 	 *
3124 	 * If this is for non-EAPOL traffic, just leave some
3125 	 * space free in order for buffer cloning and raw
3126 	 * frame transmission to occur.
3127 	 *
3128 	 * If it's for EAPOL traffic, ignore this for now.
3129 	 * Management traffic will be sent via the raw transmit
3130 	 * method which bypasses this check.
3131 	 *
3132 	 * This is needed to ensure that EAPOL frames during
3133 	 * (re) keying have a chance to go out.
3134 	 *
3135 	 * See kern/138379 for more information.
3136 	 */
3137 	if ((!(m->m_flags & M_EAPOL)) &&
3138 	    (sc->sc_txbuf_cnt <= sc->sc_txq_data_minfree)) {
3139 		sc->sc_stats.ast_tx_nobuf++;
3140 		m_freem(m);
3141 		m = NULL;
3142 		retval = ENOBUFS;
3143 		goto finish;
3144 	}
3145 
3146 	/*
3147 	 * Grab a TX buffer and associated resources.
3148 	 *
3149 	 * If it's an EAPOL frame, allocate a MGMT ath_buf.
3150 	 * That way even with temporary buffer exhaustion due to
3151 	 * the data path doesn't leave us without the ability
3152 	 * to transmit management frames.
3153 	 *
3154 	 * Otherwise allocate a normal buffer.
3155 	 */
3156 	if (m->m_flags & M_EAPOL)
3157 		bf = ath_getbuf(sc, ATH_BUFTYPE_MGMT);
3158 	else
3159 		bf = ath_getbuf(sc, ATH_BUFTYPE_NORMAL);
3160 
3161 	if (bf == NULL) {
3162 		/*
3163 		 * If we failed to allocate a buffer, fail.
3164 		 *
3165 		 * We shouldn't fail normally, due to the check
3166 		 * above.
3167 		 */
3168 		sc->sc_stats.ast_tx_nobuf++;
3169 		IF_LOCK(&ifp->if_snd);
3170 		ifp->if_drv_flags |= IFF_DRV_OACTIVE;
3171 		IF_UNLOCK(&ifp->if_snd);
3172 		m_freem(m);
3173 		m = NULL;
3174 		retval = ENOBUFS;
3175 		goto finish;
3176 	}
3177 
3178 	/*
3179 	 * At this point we have a buffer; so we need to free it
3180 	 * if we hit any error conditions.
3181 	 */
3182 
3183 	/*
3184 	 * Check for fragmentation.  If this frame
3185 	 * has been broken up verify we have enough
3186 	 * buffers to send all the fragments so all
3187 	 * go out or none...
3188 	 */
3189 	TAILQ_INIT(&frags);
3190 	if ((m->m_flags & M_FRAG) &&
3191 	    !ath_txfrag_setup(sc, &frags, m, ni)) {
3192 		DPRINTF(sc, ATH_DEBUG_XMIT,
3193 		    "%s: out of txfrag buffers\n", __func__);
3194 		sc->sc_stats.ast_tx_nofrag++;
3195 		ifp->if_oerrors++;
3196 		ath_freetx(m);
3197 		goto bad;
3198 	}
3199 
3200 	/*
3201 	 * At this point if we have any TX fragments, then we will
3202 	 * have bumped the node reference once for each of those.
3203 	 */
3204 
3205 	/*
3206 	 * XXX Is there anything actually _enforcing_ that the
3207 	 * fragments are being transmitted in one hit, rather than
3208 	 * being interleaved with other transmissions on that
3209 	 * hardware queue?
3210 	 *
3211 	 * The ATH TX output lock is the only thing serialising this
3212 	 * right now.
3213 	 */
3214 
3215 	/*
3216 	 * Calculate the "next fragment" length field in ath_buf
3217 	 * in order to let the transmit path know enough about
3218 	 * what to next write to the hardware.
3219 	 */
3220 	if (m->m_flags & M_FRAG) {
3221 		struct ath_buf *fbf = bf;
3222 		struct ath_buf *n_fbf = NULL;
3223 		struct mbuf *fm = m->m_nextpkt;
3224 
3225 		/*
3226 		 * We need to walk the list of fragments and set
3227 		 * the next size to the following buffer.
3228 		 * However, the first buffer isn't in the frag
3229 		 * list, so we have to do some gymnastics here.
3230 		 */
3231 		TAILQ_FOREACH(n_fbf, &frags, bf_list) {
3232 			fbf->bf_nextfraglen = fm->m_pkthdr.len;
3233 			fbf = n_fbf;
3234 			fm = fm->m_nextpkt;
3235 		}
3236 	}
3237 
3238 	/*
3239 	 * Bump the ifp output counter.
3240 	 *
3241 	 * XXX should use atomics?
3242 	 */
3243 	ifp->if_opackets++;
3244 nextfrag:
3245 	/*
3246 	 * Pass the frame to the h/w for transmission.
3247 	 * Fragmented frames have each frag chained together
3248 	 * with m_nextpkt.  We know there are sufficient ath_buf's
3249 	 * to send all the frags because of work done by
3250 	 * ath_txfrag_setup.  We leave m_nextpkt set while
3251 	 * calling ath_tx_start so it can use it to extend the
3252 	 * the tx duration to cover the subsequent frag and
3253 	 * so it can reclaim all the mbufs in case of an error;
3254 	 * ath_tx_start clears m_nextpkt once it commits to
3255 	 * handing the frame to the hardware.
3256 	 *
3257 	 * Note: if this fails, then the mbufs are freed but
3258 	 * not the node reference.
3259 	 */
3260 	next = m->m_nextpkt;
3261 	if (ath_tx_start(sc, ni, bf, m)) {
3262 bad:
3263 		ifp->if_oerrors++;
3264 reclaim:
3265 		bf->bf_m = NULL;
3266 		bf->bf_node = NULL;
3267 		ATH_TXBUF_LOCK(sc);
3268 		ath_returnbuf_head(sc, bf);
3269 		/*
3270 		 * Free the rest of the node references and
3271 		 * buffers for the fragment list.
3272 		 */
3273 		ath_txfrag_cleanup(sc, &frags, ni);
3274 		ATH_TXBUF_UNLOCK(sc);
3275 		retval = ENOBUFS;
3276 		goto finish;
3277 	}
3278 
3279 	/*
3280 	 * Check here if the node is in power save state.
3281 	 */
3282 	ath_tx_update_tim(sc, ni, 1);
3283 
3284 	if (next != NULL) {
3285 		/*
3286 		 * Beware of state changing between frags.
3287 		 * XXX check sta power-save state?
3288 		 */
3289 		if (ni->ni_vap->iv_state != IEEE80211_S_RUN) {
3290 			DPRINTF(sc, ATH_DEBUG_XMIT,
3291 			    "%s: flush fragmented packet, state %s\n",
3292 			    __func__,
3293 			    ieee80211_state_name[ni->ni_vap->iv_state]);
3294 			/* XXX dmamap */
3295 			ath_freetx(next);
3296 			goto reclaim;
3297 		}
3298 		m = next;
3299 		bf = TAILQ_FIRST(&frags);
3300 		KASSERT(bf != NULL, ("no buf for txfrag"));
3301 		TAILQ_REMOVE(&frags, bf, bf_list);
3302 		goto nextfrag;
3303 	}
3304 
3305 	/*
3306 	 * Bump watchdog timer.
3307 	 */
3308 	sc->sc_wd_timer = 5;
3309 
3310 finish:
3311 	ATH_TX_UNLOCK(sc);
3312 
3313 	/*
3314 	 * Finished transmitting!
3315 	 */
3316 	ATH_PCU_LOCK(sc);
3317 	sc->sc_txstart_cnt--;
3318 	ATH_PCU_UNLOCK(sc);
3319 
3320 	/* Sleep the hardware if required */
3321 	ATH_LOCK(sc);
3322 	ath_power_restore_power_state(sc);
3323 	ATH_UNLOCK(sc);
3324 
3325 	ATH_KTR(sc, ATH_KTR_TX, 0, "ath_transmit: finished");
3326 
3327 	return (retval);
3328 }
3329 
3330 static int
3331 ath_media_change(struct ifnet *ifp)
3332 {
3333 	int error = ieee80211_media_change(ifp);
3334 	/* NB: only the fixed rate can change and that doesn't need a reset */
3335 	return (error == ENETRESET ? 0 : error);
3336 }
3337 
3338 /*
3339  * Block/unblock tx+rx processing while a key change is done.
3340  * We assume the caller serializes key management operations
3341  * so we only need to worry about synchronization with other
3342  * uses that originate in the driver.
3343  */
3344 static void
3345 ath_key_update_begin(struct ieee80211vap *vap)
3346 {
3347 	struct ifnet *ifp = vap->iv_ic->ic_ifp;
3348 	struct ath_softc *sc = ifp->if_softc;
3349 
3350 	DPRINTF(sc, ATH_DEBUG_KEYCACHE, "%s:\n", __func__);
3351 	taskqueue_block(sc->sc_tq);
3352 }
3353 
3354 static void
3355 ath_key_update_end(struct ieee80211vap *vap)
3356 {
3357 	struct ifnet *ifp = vap->iv_ic->ic_ifp;
3358 	struct ath_softc *sc = ifp->if_softc;
3359 
3360 	DPRINTF(sc, ATH_DEBUG_KEYCACHE, "%s:\n", __func__);
3361 	taskqueue_unblock(sc->sc_tq);
3362 }
3363 
3364 static void
3365 ath_update_promisc(struct ifnet *ifp)
3366 {
3367 	struct ath_softc *sc = ifp->if_softc;
3368 	u_int32_t rfilt;
3369 
3370 	/* configure rx filter */
3371 	ATH_LOCK(sc);
3372 	ath_power_set_power_state(sc, HAL_PM_AWAKE);
3373 	rfilt = ath_calcrxfilter(sc);
3374 	ath_hal_setrxfilter(sc->sc_ah, rfilt);
3375 	ath_power_restore_power_state(sc);
3376 	ATH_UNLOCK(sc);
3377 
3378 	DPRINTF(sc, ATH_DEBUG_MODE, "%s: RX filter 0x%x\n", __func__, rfilt);
3379 }
3380 
3381 /*
3382  * Driver-internal mcast update call.
3383  *
3384  * Assumes the hardware is already awake.
3385  */
3386 static void
3387 ath_update_mcast_hw(struct ath_softc *sc)
3388 {
3389 	struct ifnet *ifp = sc->sc_ifp;
3390 	u_int32_t mfilt[2];
3391 
3392 	/* calculate and install multicast filter */
3393 	if ((ifp->if_flags & IFF_ALLMULTI) == 0) {
3394 		struct ifmultiaddr *ifma;
3395 		/*
3396 		 * Merge multicast addresses to form the hardware filter.
3397 		 */
3398 		mfilt[0] = mfilt[1] = 0;
3399 		if_maddr_rlock(ifp);	/* XXX need some fiddling to remove? */
3400 		TAILQ_FOREACH(ifma, &ifp->if_multiaddrs, ifma_link) {
3401 			caddr_t dl;
3402 			u_int32_t val;
3403 			u_int8_t pos;
3404 
3405 			/* calculate XOR of eight 6bit values */
3406 			dl = LLADDR((struct sockaddr_dl *) ifma->ifma_addr);
3407 			val = LE_READ_4(dl + 0);
3408 			pos = (val >> 18) ^ (val >> 12) ^ (val >> 6) ^ val;
3409 			val = LE_READ_4(dl + 3);
3410 			pos ^= (val >> 18) ^ (val >> 12) ^ (val >> 6) ^ val;
3411 			pos &= 0x3f;
3412 			mfilt[pos / 32] |= (1 << (pos % 32));
3413 		}
3414 		if_maddr_runlock(ifp);
3415 	} else
3416 		mfilt[0] = mfilt[1] = ~0;
3417 
3418 	ath_hal_setmcastfilter(sc->sc_ah, mfilt[0], mfilt[1]);
3419 
3420 	DPRINTF(sc, ATH_DEBUG_MODE, "%s: MC filter %08x:%08x\n",
3421 		__func__, mfilt[0], mfilt[1]);
3422 }
3423 
3424 /*
3425  * Called from the net80211 layer - force the hardware
3426  * awake before operating.
3427  */
3428 static void
3429 ath_update_mcast(struct ifnet *ifp)
3430 {
3431 	struct ath_softc *sc = ifp->if_softc;
3432 
3433 	ATH_LOCK(sc);
3434 	ath_power_set_power_state(sc, HAL_PM_AWAKE);
3435 	ATH_UNLOCK(sc);
3436 
3437 	ath_update_mcast_hw(sc);
3438 
3439 	ATH_LOCK(sc);
3440 	ath_power_restore_power_state(sc);
3441 	ATH_UNLOCK(sc);
3442 }
3443 
3444 void
3445 ath_mode_init(struct ath_softc *sc)
3446 {
3447 	struct ifnet *ifp = sc->sc_ifp;
3448 	struct ath_hal *ah = sc->sc_ah;
3449 	u_int32_t rfilt;
3450 
3451 	/* configure rx filter */
3452 	rfilt = ath_calcrxfilter(sc);
3453 	ath_hal_setrxfilter(ah, rfilt);
3454 
3455 	/* configure operational mode */
3456 	ath_hal_setopmode(ah);
3457 
3458 	DPRINTF(sc, ATH_DEBUG_STATE | ATH_DEBUG_MODE,
3459 	    "%s: ah=%p, ifp=%p, if_addr=%p\n",
3460 	    __func__,
3461 	    ah,
3462 	    ifp,
3463 	    (ifp == NULL) ? NULL : ifp->if_addr);
3464 
3465 	/* handle any link-level address change */
3466 	ath_hal_setmac(ah, IF_LLADDR(ifp));
3467 
3468 	/* calculate and install multicast filter */
3469 	ath_update_mcast_hw(sc);
3470 }
3471 
3472 /*
3473  * Set the slot time based on the current setting.
3474  */
3475 void
3476 ath_setslottime(struct ath_softc *sc)
3477 {
3478 	struct ieee80211com *ic = sc->sc_ifp->if_l2com;
3479 	struct ath_hal *ah = sc->sc_ah;
3480 	u_int usec;
3481 
3482 	if (IEEE80211_IS_CHAN_HALF(ic->ic_curchan))
3483 		usec = 13;
3484 	else if (IEEE80211_IS_CHAN_QUARTER(ic->ic_curchan))
3485 		usec = 21;
3486 	else if (IEEE80211_IS_CHAN_ANYG(ic->ic_curchan)) {
3487 		/* honor short/long slot time only in 11g */
3488 		/* XXX shouldn't honor on pure g or turbo g channel */
3489 		if (ic->ic_flags & IEEE80211_F_SHSLOT)
3490 			usec = HAL_SLOT_TIME_9;
3491 		else
3492 			usec = HAL_SLOT_TIME_20;
3493 	} else
3494 		usec = HAL_SLOT_TIME_9;
3495 
3496 	DPRINTF(sc, ATH_DEBUG_RESET,
3497 	    "%s: chan %u MHz flags 0x%x %s slot, %u usec\n",
3498 	    __func__, ic->ic_curchan->ic_freq, ic->ic_curchan->ic_flags,
3499 	    ic->ic_flags & IEEE80211_F_SHSLOT ? "short" : "long", usec);
3500 
3501 	/* Wake up the hardware first before updating the slot time */
3502 	ATH_LOCK(sc);
3503 	ath_power_set_power_state(sc, HAL_PM_AWAKE);
3504 	ath_hal_setslottime(ah, usec);
3505 	ath_power_restore_power_state(sc);
3506 	sc->sc_updateslot = OK;
3507 	ATH_UNLOCK(sc);
3508 }
3509 
3510 /*
3511  * Callback from the 802.11 layer to update the
3512  * slot time based on the current setting.
3513  */
3514 static void
3515 ath_updateslot(struct ifnet *ifp)
3516 {
3517 	struct ath_softc *sc = ifp->if_softc;
3518 	struct ieee80211com *ic = ifp->if_l2com;
3519 
3520 	/*
3521 	 * When not coordinating the BSS, change the hardware
3522 	 * immediately.  For other operation we defer the change
3523 	 * until beacon updates have propagated to the stations.
3524 	 *
3525 	 * XXX sc_updateslot isn't changed behind a lock?
3526 	 */
3527 	if (ic->ic_opmode == IEEE80211_M_HOSTAP ||
3528 	    ic->ic_opmode == IEEE80211_M_MBSS)
3529 		sc->sc_updateslot = UPDATE;
3530 	else
3531 		ath_setslottime(sc);
3532 }
3533 
3534 /*
3535  * Append the contents of src to dst; both queues
3536  * are assumed to be locked.
3537  */
3538 void
3539 ath_txqmove(struct ath_txq *dst, struct ath_txq *src)
3540 {
3541 
3542 	ATH_TXQ_LOCK_ASSERT(src);
3543 	ATH_TXQ_LOCK_ASSERT(dst);
3544 
3545 	TAILQ_CONCAT(&dst->axq_q, &src->axq_q, bf_list);
3546 	dst->axq_link = src->axq_link;
3547 	src->axq_link = NULL;
3548 	dst->axq_depth += src->axq_depth;
3549 	dst->axq_aggr_depth += src->axq_aggr_depth;
3550 	src->axq_depth = 0;
3551 	src->axq_aggr_depth = 0;
3552 }
3553 
3554 /*
3555  * Reset the hardware, with no loss.
3556  *
3557  * This can't be used for a general case reset.
3558  */
3559 static void
3560 ath_reset_proc(void *arg, int pending)
3561 {
3562 	struct ath_softc *sc = arg;
3563 	struct ifnet *ifp = sc->sc_ifp;
3564 
3565 #if 0
3566 	if_printf(ifp, "%s: resetting\n", __func__);
3567 #endif
3568 	ath_reset(ifp, ATH_RESET_NOLOSS);
3569 }
3570 
3571 /*
3572  * Reset the hardware after detecting beacons have stopped.
3573  */
3574 static void
3575 ath_bstuck_proc(void *arg, int pending)
3576 {
3577 	struct ath_softc *sc = arg;
3578 	struct ifnet *ifp = sc->sc_ifp;
3579 	uint32_t hangs = 0;
3580 
3581 	if (ath_hal_gethangstate(sc->sc_ah, 0xff, &hangs) && hangs != 0)
3582 		if_printf(ifp, "bb hang detected (0x%x)\n", hangs);
3583 
3584 #ifdef	ATH_DEBUG_ALQ
3585 	if (if_ath_alq_checkdebug(&sc->sc_alq, ATH_ALQ_STUCK_BEACON))
3586 		if_ath_alq_post(&sc->sc_alq, ATH_ALQ_STUCK_BEACON, 0, NULL);
3587 #endif
3588 
3589 	if_printf(ifp, "stuck beacon; resetting (bmiss count %u)\n",
3590 		sc->sc_bmisscount);
3591 	sc->sc_stats.ast_bstuck++;
3592 	/*
3593 	 * This assumes that there's no simultaneous channel mode change
3594 	 * occuring.
3595 	 */
3596 	ath_reset(ifp, ATH_RESET_NOLOSS);
3597 }
3598 
3599 static void
3600 ath_load_cb(void *arg, bus_dma_segment_t *segs, int nsegs, int error)
3601 {
3602 	bus_addr_t *paddr = (bus_addr_t*) arg;
3603 	KASSERT(error == 0, ("error %u on bus_dma callback", error));
3604 	*paddr = segs->ds_addr;
3605 }
3606 
3607 /*
3608  * Allocate the descriptors and appropriate DMA tag/setup.
3609  *
3610  * For some situations (eg EDMA TX completion), there isn't a requirement
3611  * for the ath_buf entries to be allocated.
3612  */
3613 int
3614 ath_descdma_alloc_desc(struct ath_softc *sc,
3615 	struct ath_descdma *dd, ath_bufhead *head,
3616 	const char *name, int ds_size, int ndesc)
3617 {
3618 #define	DS2PHYS(_dd, _ds) \
3619 	((_dd)->dd_desc_paddr + ((caddr_t)(_ds) - (caddr_t)(_dd)->dd_desc))
3620 #define	ATH_DESC_4KB_BOUND_CHECK(_daddr, _len) \
3621 	((((u_int32_t)(_daddr) & 0xFFF) > (0x1000 - (_len))) ? 1 : 0)
3622 	struct ifnet *ifp = sc->sc_ifp;
3623 	int error;
3624 
3625 	dd->dd_descsize = ds_size;
3626 
3627 	DPRINTF(sc, ATH_DEBUG_RESET,
3628 	    "%s: %s DMA: %u desc, %d bytes per descriptor\n",
3629 	    __func__, name, ndesc, dd->dd_descsize);
3630 
3631 	dd->dd_name = name;
3632 	dd->dd_desc_len = dd->dd_descsize * ndesc;
3633 
3634 	/*
3635 	 * Merlin work-around:
3636 	 * Descriptors that cross the 4KB boundary can't be used.
3637 	 * Assume one skipped descriptor per 4KB page.
3638 	 */
3639 	if (! ath_hal_split4ktrans(sc->sc_ah)) {
3640 		int numpages = dd->dd_desc_len / 4096;
3641 		dd->dd_desc_len += ds_size * numpages;
3642 	}
3643 
3644 	/*
3645 	 * Setup DMA descriptor area.
3646 	 *
3647 	 * BUS_DMA_ALLOCNOW is not used; we never use bounce
3648 	 * buffers for the descriptors themselves.
3649 	 */
3650 	error = bus_dma_tag_create(bus_get_dma_tag(sc->sc_dev),	/* parent */
3651 		       PAGE_SIZE, 0,		/* alignment, bounds */
3652 		       BUS_SPACE_MAXADDR_32BIT,	/* lowaddr */
3653 		       BUS_SPACE_MAXADDR,	/* highaddr */
3654 		       NULL, NULL,		/* filter, filterarg */
3655 		       dd->dd_desc_len,		/* maxsize */
3656 		       1,			/* nsegments */
3657 		       dd->dd_desc_len,		/* maxsegsize */
3658 		       0,			/* flags */
3659 		       NULL,			/* lockfunc */
3660 		       NULL,			/* lockarg */
3661 		       &dd->dd_dmat);
3662 	if (error != 0) {
3663 		if_printf(ifp, "cannot allocate %s DMA tag\n", dd->dd_name);
3664 		return error;
3665 	}
3666 
3667 	/* allocate descriptors */
3668 	error = bus_dmamem_alloc(dd->dd_dmat, (void**) &dd->dd_desc,
3669 				 BUS_DMA_NOWAIT | BUS_DMA_COHERENT,
3670 				 &dd->dd_dmamap);
3671 	if (error != 0) {
3672 		if_printf(ifp, "unable to alloc memory for %u %s descriptors, "
3673 			"error %u\n", ndesc, dd->dd_name, error);
3674 		goto fail1;
3675 	}
3676 
3677 	error = bus_dmamap_load(dd->dd_dmat, dd->dd_dmamap,
3678 				dd->dd_desc, dd->dd_desc_len,
3679 				ath_load_cb, &dd->dd_desc_paddr,
3680 				BUS_DMA_NOWAIT);
3681 	if (error != 0) {
3682 		if_printf(ifp, "unable to map %s descriptors, error %u\n",
3683 			dd->dd_name, error);
3684 		goto fail2;
3685 	}
3686 
3687 	DPRINTF(sc, ATH_DEBUG_RESET, "%s: %s DMA map: %p (%lu) -> %p (%lu)\n",
3688 	    __func__, dd->dd_name, (uint8_t *) dd->dd_desc,
3689 	    (u_long) dd->dd_desc_len, (caddr_t) dd->dd_desc_paddr,
3690 	    /*XXX*/ (u_long) dd->dd_desc_len);
3691 
3692 	return (0);
3693 
3694 fail2:
3695 	bus_dmamem_free(dd->dd_dmat, dd->dd_desc, dd->dd_dmamap);
3696 fail1:
3697 	bus_dma_tag_destroy(dd->dd_dmat);
3698 	memset(dd, 0, sizeof(*dd));
3699 	return error;
3700 #undef DS2PHYS
3701 #undef ATH_DESC_4KB_BOUND_CHECK
3702 }
3703 
3704 int
3705 ath_descdma_setup(struct ath_softc *sc,
3706 	struct ath_descdma *dd, ath_bufhead *head,
3707 	const char *name, int ds_size, int nbuf, int ndesc)
3708 {
3709 #define	DS2PHYS(_dd, _ds) \
3710 	((_dd)->dd_desc_paddr + ((caddr_t)(_ds) - (caddr_t)(_dd)->dd_desc))
3711 #define	ATH_DESC_4KB_BOUND_CHECK(_daddr, _len) \
3712 	((((u_int32_t)(_daddr) & 0xFFF) > (0x1000 - (_len))) ? 1 : 0)
3713 	struct ifnet *ifp = sc->sc_ifp;
3714 	uint8_t *ds;
3715 	struct ath_buf *bf;
3716 	int i, bsize, error;
3717 
3718 	/* Allocate descriptors */
3719 	error = ath_descdma_alloc_desc(sc, dd, head, name, ds_size,
3720 	    nbuf * ndesc);
3721 
3722 	/* Assume any errors during allocation were dealt with */
3723 	if (error != 0) {
3724 		return (error);
3725 	}
3726 
3727 	ds = (uint8_t *) dd->dd_desc;
3728 
3729 	/* allocate rx buffers */
3730 	bsize = sizeof(struct ath_buf) * nbuf;
3731 	bf = malloc(bsize, M_ATHDEV, M_NOWAIT | M_ZERO);
3732 	if (bf == NULL) {
3733 		if_printf(ifp, "malloc of %s buffers failed, size %u\n",
3734 			dd->dd_name, bsize);
3735 		goto fail3;
3736 	}
3737 	dd->dd_bufptr = bf;
3738 
3739 	TAILQ_INIT(head);
3740 	for (i = 0; i < nbuf; i++, bf++, ds += (ndesc * dd->dd_descsize)) {
3741 		bf->bf_desc = (struct ath_desc *) ds;
3742 		bf->bf_daddr = DS2PHYS(dd, ds);
3743 		if (! ath_hal_split4ktrans(sc->sc_ah)) {
3744 			/*
3745 			 * Merlin WAR: Skip descriptor addresses which
3746 			 * cause 4KB boundary crossing along any point
3747 			 * in the descriptor.
3748 			 */
3749 			 if (ATH_DESC_4KB_BOUND_CHECK(bf->bf_daddr,
3750 			     dd->dd_descsize)) {
3751 				/* Start at the next page */
3752 				ds += 0x1000 - (bf->bf_daddr & 0xFFF);
3753 				bf->bf_desc = (struct ath_desc *) ds;
3754 				bf->bf_daddr = DS2PHYS(dd, ds);
3755 			}
3756 		}
3757 		error = bus_dmamap_create(sc->sc_dmat, BUS_DMA_NOWAIT,
3758 				&bf->bf_dmamap);
3759 		if (error != 0) {
3760 			if_printf(ifp, "unable to create dmamap for %s "
3761 				"buffer %u, error %u\n", dd->dd_name, i, error);
3762 			ath_descdma_cleanup(sc, dd, head);
3763 			return error;
3764 		}
3765 		bf->bf_lastds = bf->bf_desc;	/* Just an initial value */
3766 		TAILQ_INSERT_TAIL(head, bf, bf_list);
3767 	}
3768 
3769 	/*
3770 	 * XXX TODO: ensure that ds doesn't overflow the descriptor
3771 	 * allocation otherwise weird stuff will occur and crash your
3772 	 * machine.
3773 	 */
3774 	return 0;
3775 	/* XXX this should likely just call ath_descdma_cleanup() */
3776 fail3:
3777 	bus_dmamap_unload(dd->dd_dmat, dd->dd_dmamap);
3778 	bus_dmamem_free(dd->dd_dmat, dd->dd_desc, dd->dd_dmamap);
3779 	bus_dma_tag_destroy(dd->dd_dmat);
3780 	memset(dd, 0, sizeof(*dd));
3781 	return error;
3782 #undef DS2PHYS
3783 #undef ATH_DESC_4KB_BOUND_CHECK
3784 }
3785 
3786 /*
3787  * Allocate ath_buf entries but no descriptor contents.
3788  *
3789  * This is for RX EDMA where the descriptors are the header part of
3790  * the RX buffer.
3791  */
3792 int
3793 ath_descdma_setup_rx_edma(struct ath_softc *sc,
3794 	struct ath_descdma *dd, ath_bufhead *head,
3795 	const char *name, int nbuf, int rx_status_len)
3796 {
3797 	struct ifnet *ifp = sc->sc_ifp;
3798 	struct ath_buf *bf;
3799 	int i, bsize, error;
3800 
3801 	DPRINTF(sc, ATH_DEBUG_RESET, "%s: %s DMA: %u buffers\n",
3802 	    __func__, name, nbuf);
3803 
3804 	dd->dd_name = name;
3805 	/*
3806 	 * This is (mostly) purely for show.  We're not allocating any actual
3807 	 * descriptors here as EDMA RX has the descriptor be part
3808 	 * of the RX buffer.
3809 	 *
3810 	 * However, dd_desc_len is used by ath_descdma_free() to determine
3811 	 * whether we have already freed this DMA mapping.
3812 	 */
3813 	dd->dd_desc_len = rx_status_len * nbuf;
3814 	dd->dd_descsize = rx_status_len;
3815 
3816 	/* allocate rx buffers */
3817 	bsize = sizeof(struct ath_buf) * nbuf;
3818 	bf = malloc(bsize, M_ATHDEV, M_NOWAIT | M_ZERO);
3819 	if (bf == NULL) {
3820 		if_printf(ifp, "malloc of %s buffers failed, size %u\n",
3821 			dd->dd_name, bsize);
3822 		error = ENOMEM;
3823 		goto fail3;
3824 	}
3825 	dd->dd_bufptr = bf;
3826 
3827 	TAILQ_INIT(head);
3828 	for (i = 0; i < nbuf; i++, bf++) {
3829 		bf->bf_desc = NULL;
3830 		bf->bf_daddr = 0;
3831 		bf->bf_lastds = NULL;	/* Just an initial value */
3832 
3833 		error = bus_dmamap_create(sc->sc_dmat, BUS_DMA_NOWAIT,
3834 				&bf->bf_dmamap);
3835 		if (error != 0) {
3836 			if_printf(ifp, "unable to create dmamap for %s "
3837 				"buffer %u, error %u\n", dd->dd_name, i, error);
3838 			ath_descdma_cleanup(sc, dd, head);
3839 			return error;
3840 		}
3841 		TAILQ_INSERT_TAIL(head, bf, bf_list);
3842 	}
3843 	return 0;
3844 fail3:
3845 	memset(dd, 0, sizeof(*dd));
3846 	return error;
3847 }
3848 
3849 void
3850 ath_descdma_cleanup(struct ath_softc *sc,
3851 	struct ath_descdma *dd, ath_bufhead *head)
3852 {
3853 	struct ath_buf *bf;
3854 	struct ieee80211_node *ni;
3855 	int do_warning = 0;
3856 
3857 	if (dd->dd_dmamap != 0) {
3858 		bus_dmamap_unload(dd->dd_dmat, dd->dd_dmamap);
3859 		bus_dmamem_free(dd->dd_dmat, dd->dd_desc, dd->dd_dmamap);
3860 		bus_dma_tag_destroy(dd->dd_dmat);
3861 	}
3862 
3863 	if (head != NULL) {
3864 		TAILQ_FOREACH(bf, head, bf_list) {
3865 			if (bf->bf_m) {
3866 				/*
3867 				 * XXX warn if there's buffers here.
3868 				 * XXX it should have been freed by the
3869 				 * owner!
3870 				 */
3871 
3872 				if (do_warning == 0) {
3873 					do_warning = 1;
3874 					device_printf(sc->sc_dev,
3875 					    "%s: %s: mbuf should've been"
3876 					    " unmapped/freed!\n",
3877 					    __func__,
3878 					    dd->dd_name);
3879 				}
3880 				bus_dmamap_sync(sc->sc_dmat, bf->bf_dmamap,
3881 				    BUS_DMASYNC_POSTREAD);
3882 				bus_dmamap_unload(sc->sc_dmat, bf->bf_dmamap);
3883 				m_freem(bf->bf_m);
3884 				bf->bf_m = NULL;
3885 			}
3886 			if (bf->bf_dmamap != NULL) {
3887 				bus_dmamap_destroy(sc->sc_dmat, bf->bf_dmamap);
3888 				bf->bf_dmamap = NULL;
3889 			}
3890 			ni = bf->bf_node;
3891 			bf->bf_node = NULL;
3892 			if (ni != NULL) {
3893 				/*
3894 				 * Reclaim node reference.
3895 				 */
3896 				ieee80211_free_node(ni);
3897 			}
3898 		}
3899 	}
3900 
3901 	if (head != NULL)
3902 		TAILQ_INIT(head);
3903 
3904 	if (dd->dd_bufptr != NULL)
3905 		free(dd->dd_bufptr, M_ATHDEV);
3906 	memset(dd, 0, sizeof(*dd));
3907 }
3908 
3909 static int
3910 ath_desc_alloc(struct ath_softc *sc)
3911 {
3912 	int error;
3913 
3914 	error = ath_descdma_setup(sc, &sc->sc_txdma, &sc->sc_txbuf,
3915 		    "tx", sc->sc_tx_desclen, ath_txbuf, ATH_MAX_SCATTER);
3916 	if (error != 0) {
3917 		return error;
3918 	}
3919 	sc->sc_txbuf_cnt = ath_txbuf;
3920 
3921 	error = ath_descdma_setup(sc, &sc->sc_txdma_mgmt, &sc->sc_txbuf_mgmt,
3922 		    "tx_mgmt", sc->sc_tx_desclen, ath_txbuf_mgmt,
3923 		    ATH_TXDESC);
3924 	if (error != 0) {
3925 		ath_descdma_cleanup(sc, &sc->sc_txdma, &sc->sc_txbuf);
3926 		return error;
3927 	}
3928 
3929 	/*
3930 	 * XXX mark txbuf_mgmt frames with ATH_BUF_MGMT, so the
3931 	 * flag doesn't have to be set in ath_getbuf_locked().
3932 	 */
3933 
3934 	error = ath_descdma_setup(sc, &sc->sc_bdma, &sc->sc_bbuf,
3935 			"beacon", sc->sc_tx_desclen, ATH_BCBUF, 1);
3936 	if (error != 0) {
3937 		ath_descdma_cleanup(sc, &sc->sc_txdma, &sc->sc_txbuf);
3938 		ath_descdma_cleanup(sc, &sc->sc_txdma_mgmt,
3939 		    &sc->sc_txbuf_mgmt);
3940 		return error;
3941 	}
3942 	return 0;
3943 }
3944 
3945 static void
3946 ath_desc_free(struct ath_softc *sc)
3947 {
3948 
3949 	if (sc->sc_bdma.dd_desc_len != 0)
3950 		ath_descdma_cleanup(sc, &sc->sc_bdma, &sc->sc_bbuf);
3951 	if (sc->sc_txdma.dd_desc_len != 0)
3952 		ath_descdma_cleanup(sc, &sc->sc_txdma, &sc->sc_txbuf);
3953 	if (sc->sc_txdma_mgmt.dd_desc_len != 0)
3954 		ath_descdma_cleanup(sc, &sc->sc_txdma_mgmt,
3955 		    &sc->sc_txbuf_mgmt);
3956 }
3957 
3958 static struct ieee80211_node *
3959 ath_node_alloc(struct ieee80211vap *vap, const uint8_t mac[IEEE80211_ADDR_LEN])
3960 {
3961 	struct ieee80211com *ic = vap->iv_ic;
3962 	struct ath_softc *sc = ic->ic_ifp->if_softc;
3963 	const size_t space = sizeof(struct ath_node) + sc->sc_rc->arc_space;
3964 	struct ath_node *an;
3965 
3966 	an = malloc(space, M_80211_NODE, M_NOWAIT|M_ZERO);
3967 	if (an == NULL) {
3968 		/* XXX stat+msg */
3969 		return NULL;
3970 	}
3971 	ath_rate_node_init(sc, an);
3972 
3973 	/* Setup the mutex - there's no associd yet so set the name to NULL */
3974 	snprintf(an->an_name, sizeof(an->an_name), "%s: node %p",
3975 	    device_get_nameunit(sc->sc_dev), an);
3976 	mtx_init(&an->an_mtx, an->an_name, NULL, MTX_DEF);
3977 
3978 	/* XXX setup ath_tid */
3979 	ath_tx_tid_init(sc, an);
3980 
3981 	DPRINTF(sc, ATH_DEBUG_NODE, "%s: %6D: an %p\n", __func__, mac, ":", an);
3982 	return &an->an_node;
3983 }
3984 
3985 static void
3986 ath_node_cleanup(struct ieee80211_node *ni)
3987 {
3988 	struct ieee80211com *ic = ni->ni_ic;
3989 	struct ath_softc *sc = ic->ic_ifp->if_softc;
3990 
3991 	DPRINTF(sc, ATH_DEBUG_NODE, "%s: %6D: an %p\n", __func__,
3992 	    ni->ni_macaddr, ":", ATH_NODE(ni));
3993 
3994 	/* Cleanup ath_tid, free unused bufs, unlink bufs in TXQ */
3995 	ath_tx_node_flush(sc, ATH_NODE(ni));
3996 	ath_rate_node_cleanup(sc, ATH_NODE(ni));
3997 	sc->sc_node_cleanup(ni);
3998 }
3999 
4000 static void
4001 ath_node_free(struct ieee80211_node *ni)
4002 {
4003 	struct ieee80211com *ic = ni->ni_ic;
4004 	struct ath_softc *sc = ic->ic_ifp->if_softc;
4005 
4006 	DPRINTF(sc, ATH_DEBUG_NODE, "%s: %6D: an %p\n", __func__,
4007 	    ni->ni_macaddr, ":", ATH_NODE(ni));
4008 	mtx_destroy(&ATH_NODE(ni)->an_mtx);
4009 	sc->sc_node_free(ni);
4010 }
4011 
4012 static void
4013 ath_node_getsignal(const struct ieee80211_node *ni, int8_t *rssi, int8_t *noise)
4014 {
4015 	struct ieee80211com *ic = ni->ni_ic;
4016 	struct ath_softc *sc = ic->ic_ifp->if_softc;
4017 	struct ath_hal *ah = sc->sc_ah;
4018 
4019 	*rssi = ic->ic_node_getrssi(ni);
4020 	if (ni->ni_chan != IEEE80211_CHAN_ANYC)
4021 		*noise = ath_hal_getchannoise(ah, ni->ni_chan);
4022 	else
4023 		*noise = -95;		/* nominally correct */
4024 }
4025 
4026 /*
4027  * Set the default antenna.
4028  */
4029 void
4030 ath_setdefantenna(struct ath_softc *sc, u_int antenna)
4031 {
4032 	struct ath_hal *ah = sc->sc_ah;
4033 
4034 	/* XXX block beacon interrupts */
4035 	ath_hal_setdefantenna(ah, antenna);
4036 	if (sc->sc_defant != antenna)
4037 		sc->sc_stats.ast_ant_defswitch++;
4038 	sc->sc_defant = antenna;
4039 	sc->sc_rxotherant = 0;
4040 }
4041 
4042 static void
4043 ath_txq_init(struct ath_softc *sc, struct ath_txq *txq, int qnum)
4044 {
4045 	txq->axq_qnum = qnum;
4046 	txq->axq_ac = 0;
4047 	txq->axq_depth = 0;
4048 	txq->axq_aggr_depth = 0;
4049 	txq->axq_intrcnt = 0;
4050 	txq->axq_link = NULL;
4051 	txq->axq_softc = sc;
4052 	TAILQ_INIT(&txq->axq_q);
4053 	TAILQ_INIT(&txq->axq_tidq);
4054 	TAILQ_INIT(&txq->fifo.axq_q);
4055 	ATH_TXQ_LOCK_INIT(sc, txq);
4056 }
4057 
4058 /*
4059  * Setup a h/w transmit queue.
4060  */
4061 static struct ath_txq *
4062 ath_txq_setup(struct ath_softc *sc, int qtype, int subtype)
4063 {
4064 #define	N(a)	(sizeof(a)/sizeof(a[0]))
4065 	struct ath_hal *ah = sc->sc_ah;
4066 	HAL_TXQ_INFO qi;
4067 	int qnum;
4068 
4069 	memset(&qi, 0, sizeof(qi));
4070 	qi.tqi_subtype = subtype;
4071 	qi.tqi_aifs = HAL_TXQ_USEDEFAULT;
4072 	qi.tqi_cwmin = HAL_TXQ_USEDEFAULT;
4073 	qi.tqi_cwmax = HAL_TXQ_USEDEFAULT;
4074 	/*
4075 	 * Enable interrupts only for EOL and DESC conditions.
4076 	 * We mark tx descriptors to receive a DESC interrupt
4077 	 * when a tx queue gets deep; otherwise waiting for the
4078 	 * EOL to reap descriptors.  Note that this is done to
4079 	 * reduce interrupt load and this only defers reaping
4080 	 * descriptors, never transmitting frames.  Aside from
4081 	 * reducing interrupts this also permits more concurrency.
4082 	 * The only potential downside is if the tx queue backs
4083 	 * up in which case the top half of the kernel may backup
4084 	 * due to a lack of tx descriptors.
4085 	 */
4086 	if (sc->sc_isedma)
4087 		qi.tqi_qflags = HAL_TXQ_TXEOLINT_ENABLE |
4088 		    HAL_TXQ_TXOKINT_ENABLE;
4089 	else
4090 		qi.tqi_qflags = HAL_TXQ_TXEOLINT_ENABLE |
4091 		    HAL_TXQ_TXDESCINT_ENABLE;
4092 
4093 	qnum = ath_hal_setuptxqueue(ah, qtype, &qi);
4094 	if (qnum == -1) {
4095 		/*
4096 		 * NB: don't print a message, this happens
4097 		 * normally on parts with too few tx queues
4098 		 */
4099 		return NULL;
4100 	}
4101 	if (qnum >= N(sc->sc_txq)) {
4102 		device_printf(sc->sc_dev,
4103 			"hal qnum %u out of range, max %zu!\n",
4104 			qnum, N(sc->sc_txq));
4105 		ath_hal_releasetxqueue(ah, qnum);
4106 		return NULL;
4107 	}
4108 	if (!ATH_TXQ_SETUP(sc, qnum)) {
4109 		ath_txq_init(sc, &sc->sc_txq[qnum], qnum);
4110 		sc->sc_txqsetup |= 1<<qnum;
4111 	}
4112 	return &sc->sc_txq[qnum];
4113 #undef N
4114 }
4115 
4116 /*
4117  * Setup a hardware data transmit queue for the specified
4118  * access control.  The hal may not support all requested
4119  * queues in which case it will return a reference to a
4120  * previously setup queue.  We record the mapping from ac's
4121  * to h/w queues for use by ath_tx_start and also track
4122  * the set of h/w queues being used to optimize work in the
4123  * transmit interrupt handler and related routines.
4124  */
4125 static int
4126 ath_tx_setup(struct ath_softc *sc, int ac, int haltype)
4127 {
4128 #define	N(a)	(sizeof(a)/sizeof(a[0]))
4129 	struct ath_txq *txq;
4130 
4131 	if (ac >= N(sc->sc_ac2q)) {
4132 		device_printf(sc->sc_dev, "AC %u out of range, max %zu!\n",
4133 			ac, N(sc->sc_ac2q));
4134 		return 0;
4135 	}
4136 	txq = ath_txq_setup(sc, HAL_TX_QUEUE_DATA, haltype);
4137 	if (txq != NULL) {
4138 		txq->axq_ac = ac;
4139 		sc->sc_ac2q[ac] = txq;
4140 		return 1;
4141 	} else
4142 		return 0;
4143 #undef N
4144 }
4145 
4146 /*
4147  * Update WME parameters for a transmit queue.
4148  */
4149 static int
4150 ath_txq_update(struct ath_softc *sc, int ac)
4151 {
4152 #define	ATH_EXPONENT_TO_VALUE(v)	((1<<v)-1)
4153 #define	ATH_TXOP_TO_US(v)		(v<<5)
4154 	struct ifnet *ifp = sc->sc_ifp;
4155 	struct ieee80211com *ic = ifp->if_l2com;
4156 	struct ath_txq *txq = sc->sc_ac2q[ac];
4157 	struct wmeParams *wmep = &ic->ic_wme.wme_chanParams.cap_wmeParams[ac];
4158 	struct ath_hal *ah = sc->sc_ah;
4159 	HAL_TXQ_INFO qi;
4160 
4161 	ath_hal_gettxqueueprops(ah, txq->axq_qnum, &qi);
4162 #ifdef IEEE80211_SUPPORT_TDMA
4163 	if (sc->sc_tdma) {
4164 		/*
4165 		 * AIFS is zero so there's no pre-transmit wait.  The
4166 		 * burst time defines the slot duration and is configured
4167 		 * through net80211.  The QCU is setup to not do post-xmit
4168 		 * back off, lockout all lower-priority QCU's, and fire
4169 		 * off the DMA beacon alert timer which is setup based
4170 		 * on the slot configuration.
4171 		 */
4172 		qi.tqi_qflags = HAL_TXQ_TXOKINT_ENABLE
4173 			      | HAL_TXQ_TXERRINT_ENABLE
4174 			      | HAL_TXQ_TXURNINT_ENABLE
4175 			      | HAL_TXQ_TXEOLINT_ENABLE
4176 			      | HAL_TXQ_DBA_GATED
4177 			      | HAL_TXQ_BACKOFF_DISABLE
4178 			      | HAL_TXQ_ARB_LOCKOUT_GLOBAL
4179 			      ;
4180 		qi.tqi_aifs = 0;
4181 		/* XXX +dbaprep? */
4182 		qi.tqi_readyTime = sc->sc_tdmaslotlen;
4183 		qi.tqi_burstTime = qi.tqi_readyTime;
4184 	} else {
4185 #endif
4186 		/*
4187 		 * XXX shouldn't this just use the default flags
4188 		 * used in the previous queue setup?
4189 		 */
4190 		qi.tqi_qflags = HAL_TXQ_TXOKINT_ENABLE
4191 			      | HAL_TXQ_TXERRINT_ENABLE
4192 			      | HAL_TXQ_TXDESCINT_ENABLE
4193 			      | HAL_TXQ_TXURNINT_ENABLE
4194 			      | HAL_TXQ_TXEOLINT_ENABLE
4195 			      ;
4196 		qi.tqi_aifs = wmep->wmep_aifsn;
4197 		qi.tqi_cwmin = ATH_EXPONENT_TO_VALUE(wmep->wmep_logcwmin);
4198 		qi.tqi_cwmax = ATH_EXPONENT_TO_VALUE(wmep->wmep_logcwmax);
4199 		qi.tqi_readyTime = 0;
4200 		qi.tqi_burstTime = ATH_TXOP_TO_US(wmep->wmep_txopLimit);
4201 #ifdef IEEE80211_SUPPORT_TDMA
4202 	}
4203 #endif
4204 
4205 	DPRINTF(sc, ATH_DEBUG_RESET,
4206 	    "%s: Q%u qflags 0x%x aifs %u cwmin %u cwmax %u burstTime %u\n",
4207 	    __func__, txq->axq_qnum, qi.tqi_qflags,
4208 	    qi.tqi_aifs, qi.tqi_cwmin, qi.tqi_cwmax, qi.tqi_burstTime);
4209 
4210 	if (!ath_hal_settxqueueprops(ah, txq->axq_qnum, &qi)) {
4211 		if_printf(ifp, "unable to update hardware queue "
4212 			"parameters for %s traffic!\n",
4213 			ieee80211_wme_acnames[ac]);
4214 		return 0;
4215 	} else {
4216 		ath_hal_resettxqueue(ah, txq->axq_qnum); /* push to h/w */
4217 		return 1;
4218 	}
4219 #undef ATH_TXOP_TO_US
4220 #undef ATH_EXPONENT_TO_VALUE
4221 }
4222 
4223 /*
4224  * Callback from the 802.11 layer to update WME parameters.
4225  */
4226 int
4227 ath_wme_update(struct ieee80211com *ic)
4228 {
4229 	struct ath_softc *sc = ic->ic_ifp->if_softc;
4230 
4231 	return !ath_txq_update(sc, WME_AC_BE) ||
4232 	    !ath_txq_update(sc, WME_AC_BK) ||
4233 	    !ath_txq_update(sc, WME_AC_VI) ||
4234 	    !ath_txq_update(sc, WME_AC_VO) ? EIO : 0;
4235 }
4236 
4237 /*
4238  * Reclaim resources for a setup queue.
4239  */
4240 static void
4241 ath_tx_cleanupq(struct ath_softc *sc, struct ath_txq *txq)
4242 {
4243 
4244 	ath_hal_releasetxqueue(sc->sc_ah, txq->axq_qnum);
4245 	sc->sc_txqsetup &= ~(1<<txq->axq_qnum);
4246 	ATH_TXQ_LOCK_DESTROY(txq);
4247 }
4248 
4249 /*
4250  * Reclaim all tx queue resources.
4251  */
4252 static void
4253 ath_tx_cleanup(struct ath_softc *sc)
4254 {
4255 	int i;
4256 
4257 	ATH_TXBUF_LOCK_DESTROY(sc);
4258 	for (i = 0; i < HAL_NUM_TX_QUEUES; i++)
4259 		if (ATH_TXQ_SETUP(sc, i))
4260 			ath_tx_cleanupq(sc, &sc->sc_txq[i]);
4261 }
4262 
4263 /*
4264  * Return h/w rate index for an IEEE rate (w/o basic rate bit)
4265  * using the current rates in sc_rixmap.
4266  */
4267 int
4268 ath_tx_findrix(const struct ath_softc *sc, uint8_t rate)
4269 {
4270 	int rix = sc->sc_rixmap[rate];
4271 	/* NB: return lowest rix for invalid rate */
4272 	return (rix == 0xff ? 0 : rix);
4273 }
4274 
4275 static void
4276 ath_tx_update_stats(struct ath_softc *sc, struct ath_tx_status *ts,
4277     struct ath_buf *bf)
4278 {
4279 	struct ieee80211_node *ni = bf->bf_node;
4280 	struct ifnet *ifp = sc->sc_ifp;
4281 	struct ieee80211com *ic = ifp->if_l2com;
4282 	int sr, lr, pri;
4283 
4284 	if (ts->ts_status == 0) {
4285 		u_int8_t txant = ts->ts_antenna;
4286 		sc->sc_stats.ast_ant_tx[txant]++;
4287 		sc->sc_ant_tx[txant]++;
4288 		if (ts->ts_finaltsi != 0)
4289 			sc->sc_stats.ast_tx_altrate++;
4290 		pri = M_WME_GETAC(bf->bf_m);
4291 		if (pri >= WME_AC_VO)
4292 			ic->ic_wme.wme_hipri_traffic++;
4293 		if ((bf->bf_state.bfs_txflags & HAL_TXDESC_NOACK) == 0)
4294 			ni->ni_inact = ni->ni_inact_reload;
4295 	} else {
4296 		if (ts->ts_status & HAL_TXERR_XRETRY)
4297 			sc->sc_stats.ast_tx_xretries++;
4298 		if (ts->ts_status & HAL_TXERR_FIFO)
4299 			sc->sc_stats.ast_tx_fifoerr++;
4300 		if (ts->ts_status & HAL_TXERR_FILT)
4301 			sc->sc_stats.ast_tx_filtered++;
4302 		if (ts->ts_status & HAL_TXERR_XTXOP)
4303 			sc->sc_stats.ast_tx_xtxop++;
4304 		if (ts->ts_status & HAL_TXERR_TIMER_EXPIRED)
4305 			sc->sc_stats.ast_tx_timerexpired++;
4306 
4307 		if (bf->bf_m->m_flags & M_FF)
4308 			sc->sc_stats.ast_ff_txerr++;
4309 	}
4310 	/* XXX when is this valid? */
4311 	if (ts->ts_flags & HAL_TX_DESC_CFG_ERR)
4312 		sc->sc_stats.ast_tx_desccfgerr++;
4313 	/*
4314 	 * This can be valid for successful frame transmission!
4315 	 * If there's a TX FIFO underrun during aggregate transmission,
4316 	 * the MAC will pad the rest of the aggregate with delimiters.
4317 	 * If a BA is returned, the frame is marked as "OK" and it's up
4318 	 * to the TX completion code to notice which frames weren't
4319 	 * successfully transmitted.
4320 	 */
4321 	if (ts->ts_flags & HAL_TX_DATA_UNDERRUN)
4322 		sc->sc_stats.ast_tx_data_underrun++;
4323 	if (ts->ts_flags & HAL_TX_DELIM_UNDERRUN)
4324 		sc->sc_stats.ast_tx_delim_underrun++;
4325 
4326 	sr = ts->ts_shortretry;
4327 	lr = ts->ts_longretry;
4328 	sc->sc_stats.ast_tx_shortretry += sr;
4329 	sc->sc_stats.ast_tx_longretry += lr;
4330 
4331 }
4332 
4333 /*
4334  * The default completion. If fail is 1, this means
4335  * "please don't retry the frame, and just return -1 status
4336  * to the net80211 stack.
4337  */
4338 void
4339 ath_tx_default_comp(struct ath_softc *sc, struct ath_buf *bf, int fail)
4340 {
4341 	struct ath_tx_status *ts = &bf->bf_status.ds_txstat;
4342 	int st;
4343 
4344 	if (fail == 1)
4345 		st = -1;
4346 	else
4347 		st = ((bf->bf_state.bfs_txflags & HAL_TXDESC_NOACK) == 0) ?
4348 		    ts->ts_status : HAL_TXERR_XRETRY;
4349 
4350 #if 0
4351 	if (bf->bf_state.bfs_dobaw)
4352 		device_printf(sc->sc_dev,
4353 		    "%s: bf %p: seqno %d: dobaw should've been cleared!\n",
4354 		    __func__,
4355 		    bf,
4356 		    SEQNO(bf->bf_state.bfs_seqno));
4357 #endif
4358 	if (bf->bf_next != NULL)
4359 		device_printf(sc->sc_dev,
4360 		    "%s: bf %p: seqno %d: bf_next not NULL!\n",
4361 		    __func__,
4362 		    bf,
4363 		    SEQNO(bf->bf_state.bfs_seqno));
4364 
4365 	/*
4366 	 * Check if the node software queue is empty; if so
4367 	 * then clear the TIM.
4368 	 *
4369 	 * This needs to be done before the buffer is freed as
4370 	 * otherwise the node reference will have been released
4371 	 * and the node may not actually exist any longer.
4372 	 *
4373 	 * XXX I don't like this belonging here, but it's cleaner
4374 	 * to do it here right now then all the other places
4375 	 * where ath_tx_default_comp() is called.
4376 	 *
4377 	 * XXX TODO: during drain, ensure that the callback is
4378 	 * being called so we get a chance to update the TIM.
4379 	 */
4380 	if (bf->bf_node) {
4381 		ATH_TX_LOCK(sc);
4382 		ath_tx_update_tim(sc, bf->bf_node, 0);
4383 		ATH_TX_UNLOCK(sc);
4384 	}
4385 
4386 	/*
4387 	 * Do any tx complete callback.  Note this must
4388 	 * be done before releasing the node reference.
4389 	 * This will free the mbuf, release the net80211
4390 	 * node and recycle the ath_buf.
4391 	 */
4392 	ath_tx_freebuf(sc, bf, st);
4393 }
4394 
4395 /*
4396  * Update rate control with the given completion status.
4397  */
4398 void
4399 ath_tx_update_ratectrl(struct ath_softc *sc, struct ieee80211_node *ni,
4400     struct ath_rc_series *rc, struct ath_tx_status *ts, int frmlen,
4401     int nframes, int nbad)
4402 {
4403 	struct ath_node *an;
4404 
4405 	/* Only for unicast frames */
4406 	if (ni == NULL)
4407 		return;
4408 
4409 	an = ATH_NODE(ni);
4410 	ATH_NODE_UNLOCK_ASSERT(an);
4411 
4412 	if ((ts->ts_status & HAL_TXERR_FILT) == 0) {
4413 		ATH_NODE_LOCK(an);
4414 		ath_rate_tx_complete(sc, an, rc, ts, frmlen, nframes, nbad);
4415 		ATH_NODE_UNLOCK(an);
4416 	}
4417 }
4418 
4419 /*
4420  * Process the completion of the given buffer.
4421  *
4422  * This calls the rate control update and then the buffer completion.
4423  * This will either free the buffer or requeue it.  In any case, the
4424  * bf pointer should be treated as invalid after this function is called.
4425  */
4426 void
4427 ath_tx_process_buf_completion(struct ath_softc *sc, struct ath_txq *txq,
4428     struct ath_tx_status *ts, struct ath_buf *bf)
4429 {
4430 	struct ieee80211_node *ni = bf->bf_node;
4431 
4432 	ATH_TX_UNLOCK_ASSERT(sc);
4433 	ATH_TXQ_UNLOCK_ASSERT(txq);
4434 
4435 	/* If unicast frame, update general statistics */
4436 	if (ni != NULL) {
4437 		/* update statistics */
4438 		ath_tx_update_stats(sc, ts, bf);
4439 	}
4440 
4441 	/*
4442 	 * Call the completion handler.
4443 	 * The completion handler is responsible for
4444 	 * calling the rate control code.
4445 	 *
4446 	 * Frames with no completion handler get the
4447 	 * rate control code called here.
4448 	 */
4449 	if (bf->bf_comp == NULL) {
4450 		if ((ts->ts_status & HAL_TXERR_FILT) == 0 &&
4451 		    (bf->bf_state.bfs_txflags & HAL_TXDESC_NOACK) == 0) {
4452 			/*
4453 			 * XXX assume this isn't an aggregate
4454 			 * frame.
4455 			 */
4456 			ath_tx_update_ratectrl(sc, ni,
4457 			     bf->bf_state.bfs_rc, ts,
4458 			    bf->bf_state.bfs_pktlen, 1,
4459 			    (ts->ts_status == 0 ? 0 : 1));
4460 		}
4461 		ath_tx_default_comp(sc, bf, 0);
4462 	} else
4463 		bf->bf_comp(sc, bf, 0);
4464 }
4465 
4466 
4467 
4468 /*
4469  * Process completed xmit descriptors from the specified queue.
4470  * Kick the packet scheduler if needed. This can occur from this
4471  * particular task.
4472  */
4473 static int
4474 ath_tx_processq(struct ath_softc *sc, struct ath_txq *txq, int dosched)
4475 {
4476 	struct ath_hal *ah = sc->sc_ah;
4477 	struct ath_buf *bf;
4478 	struct ath_desc *ds;
4479 	struct ath_tx_status *ts;
4480 	struct ieee80211_node *ni;
4481 #ifdef	IEEE80211_SUPPORT_SUPERG
4482 	struct ieee80211com *ic = sc->sc_ifp->if_l2com;
4483 #endif	/* IEEE80211_SUPPORT_SUPERG */
4484 	int nacked;
4485 	HAL_STATUS status;
4486 
4487 	DPRINTF(sc, ATH_DEBUG_TX_PROC, "%s: tx queue %u head %p link %p\n",
4488 		__func__, txq->axq_qnum,
4489 		(caddr_t)(uintptr_t) ath_hal_gettxbuf(sc->sc_ah, txq->axq_qnum),
4490 		txq->axq_link);
4491 
4492 	ATH_KTR(sc, ATH_KTR_TXCOMP, 4,
4493 	    "ath_tx_processq: txq=%u head %p link %p depth %p",
4494 	    txq->axq_qnum,
4495 	    (caddr_t)(uintptr_t) ath_hal_gettxbuf(sc->sc_ah, txq->axq_qnum),
4496 	    txq->axq_link,
4497 	    txq->axq_depth);
4498 
4499 	nacked = 0;
4500 	for (;;) {
4501 		ATH_TXQ_LOCK(txq);
4502 		txq->axq_intrcnt = 0;	/* reset periodic desc intr count */
4503 		bf = TAILQ_FIRST(&txq->axq_q);
4504 		if (bf == NULL) {
4505 			ATH_TXQ_UNLOCK(txq);
4506 			break;
4507 		}
4508 		ds = bf->bf_lastds;	/* XXX must be setup correctly! */
4509 		ts = &bf->bf_status.ds_txstat;
4510 
4511 		status = ath_hal_txprocdesc(ah, ds, ts);
4512 #ifdef ATH_DEBUG
4513 		if (sc->sc_debug & ATH_DEBUG_XMIT_DESC)
4514 			ath_printtxbuf(sc, bf, txq->axq_qnum, 0,
4515 			    status == HAL_OK);
4516 		else if ((sc->sc_debug & ATH_DEBUG_RESET) && (dosched == 0))
4517 			ath_printtxbuf(sc, bf, txq->axq_qnum, 0,
4518 			    status == HAL_OK);
4519 #endif
4520 #ifdef	ATH_DEBUG_ALQ
4521 		if (if_ath_alq_checkdebug(&sc->sc_alq,
4522 		    ATH_ALQ_EDMA_TXSTATUS)) {
4523 			if_ath_alq_post(&sc->sc_alq, ATH_ALQ_EDMA_TXSTATUS,
4524 			sc->sc_tx_statuslen,
4525 			(char *) ds);
4526 		}
4527 #endif
4528 
4529 		if (status == HAL_EINPROGRESS) {
4530 			ATH_KTR(sc, ATH_KTR_TXCOMP, 3,
4531 			    "ath_tx_processq: txq=%u, bf=%p ds=%p, HAL_EINPROGRESS",
4532 			    txq->axq_qnum, bf, ds);
4533 			ATH_TXQ_UNLOCK(txq);
4534 			break;
4535 		}
4536 		ATH_TXQ_REMOVE(txq, bf, bf_list);
4537 
4538 		/*
4539 		 * Sanity check.
4540 		 */
4541 		if (txq->axq_qnum != bf->bf_state.bfs_tx_queue) {
4542 			device_printf(sc->sc_dev,
4543 			    "%s: TXQ=%d: bf=%p, bfs_tx_queue=%d\n",
4544 			    __func__,
4545 			    txq->axq_qnum,
4546 			    bf,
4547 			    bf->bf_state.bfs_tx_queue);
4548 		}
4549 		if (txq->axq_qnum != bf->bf_last->bf_state.bfs_tx_queue) {
4550 			device_printf(sc->sc_dev,
4551 			    "%s: TXQ=%d: bf_last=%p, bfs_tx_queue=%d\n",
4552 			    __func__,
4553 			    txq->axq_qnum,
4554 			    bf->bf_last,
4555 			    bf->bf_last->bf_state.bfs_tx_queue);
4556 		}
4557 
4558 #if 0
4559 		if (txq->axq_depth > 0) {
4560 			/*
4561 			 * More frames follow.  Mark the buffer busy
4562 			 * so it's not re-used while the hardware may
4563 			 * still re-read the link field in the descriptor.
4564 			 *
4565 			 * Use the last buffer in an aggregate as that
4566 			 * is where the hardware may be - intermediate
4567 			 * descriptors won't be "busy".
4568 			 */
4569 			bf->bf_last->bf_flags |= ATH_BUF_BUSY;
4570 		} else
4571 			txq->axq_link = NULL;
4572 #else
4573 		bf->bf_last->bf_flags |= ATH_BUF_BUSY;
4574 #endif
4575 		if (bf->bf_state.bfs_aggr)
4576 			txq->axq_aggr_depth--;
4577 
4578 		ni = bf->bf_node;
4579 
4580 		ATH_KTR(sc, ATH_KTR_TXCOMP, 5,
4581 		    "ath_tx_processq: txq=%u, bf=%p, ds=%p, ni=%p, ts_status=0x%08x",
4582 		    txq->axq_qnum, bf, ds, ni, ts->ts_status);
4583 		/*
4584 		 * If unicast frame was ack'd update RSSI,
4585 		 * including the last rx time used to
4586 		 * workaround phantom bmiss interrupts.
4587 		 */
4588 		if (ni != NULL && ts->ts_status == 0 &&
4589 		    ((bf->bf_state.bfs_txflags & HAL_TXDESC_NOACK) == 0)) {
4590 			nacked++;
4591 			sc->sc_stats.ast_tx_rssi = ts->ts_rssi;
4592 			ATH_RSSI_LPF(sc->sc_halstats.ns_avgtxrssi,
4593 				ts->ts_rssi);
4594 		}
4595 		ATH_TXQ_UNLOCK(txq);
4596 
4597 		/*
4598 		 * Update statistics and call completion
4599 		 */
4600 		ath_tx_process_buf_completion(sc, txq, ts, bf);
4601 
4602 		/* XXX at this point, bf and ni may be totally invalid */
4603 	}
4604 #ifdef IEEE80211_SUPPORT_SUPERG
4605 	/*
4606 	 * Flush fast-frame staging queue when traffic slows.
4607 	 */
4608 	if (txq->axq_depth <= 1)
4609 		ieee80211_ff_flush(ic, txq->axq_ac);
4610 #endif
4611 
4612 	/* Kick the software TXQ scheduler */
4613 	if (dosched) {
4614 		ATH_TX_LOCK(sc);
4615 		ath_txq_sched(sc, txq);
4616 		ATH_TX_UNLOCK(sc);
4617 	}
4618 
4619 	ATH_KTR(sc, ATH_KTR_TXCOMP, 1,
4620 	    "ath_tx_processq: txq=%u: done",
4621 	    txq->axq_qnum);
4622 
4623 	return nacked;
4624 }
4625 
4626 #define	TXQACTIVE(t, q)		( (t) & (1 << (q)))
4627 
4628 /*
4629  * Deferred processing of transmit interrupt; special-cased
4630  * for a single hardware transmit queue (e.g. 5210 and 5211).
4631  */
4632 static void
4633 ath_tx_proc_q0(void *arg, int npending)
4634 {
4635 	struct ath_softc *sc = arg;
4636 	struct ifnet *ifp = sc->sc_ifp;
4637 	uint32_t txqs;
4638 
4639 	ATH_PCU_LOCK(sc);
4640 	sc->sc_txproc_cnt++;
4641 	txqs = sc->sc_txq_active;
4642 	sc->sc_txq_active &= ~txqs;
4643 	ATH_PCU_UNLOCK(sc);
4644 
4645 	ATH_LOCK(sc);
4646 	ath_power_set_power_state(sc, HAL_PM_AWAKE);
4647 	ATH_UNLOCK(sc);
4648 
4649 	ATH_KTR(sc, ATH_KTR_TXCOMP, 1,
4650 	    "ath_tx_proc_q0: txqs=0x%08x", txqs);
4651 
4652 	if (TXQACTIVE(txqs, 0) && ath_tx_processq(sc, &sc->sc_txq[0], 1))
4653 		/* XXX why is lastrx updated in tx code? */
4654 		sc->sc_lastrx = ath_hal_gettsf64(sc->sc_ah);
4655 	if (TXQACTIVE(txqs, sc->sc_cabq->axq_qnum))
4656 		ath_tx_processq(sc, sc->sc_cabq, 1);
4657 	IF_LOCK(&ifp->if_snd);
4658 	ifp->if_drv_flags &= ~IFF_DRV_OACTIVE;
4659 	IF_UNLOCK(&ifp->if_snd);
4660 	sc->sc_wd_timer = 0;
4661 
4662 	if (sc->sc_softled)
4663 		ath_led_event(sc, sc->sc_txrix);
4664 
4665 	ATH_PCU_LOCK(sc);
4666 	sc->sc_txproc_cnt--;
4667 	ATH_PCU_UNLOCK(sc);
4668 
4669 	ATH_LOCK(sc);
4670 	ath_power_restore_power_state(sc);
4671 	ATH_UNLOCK(sc);
4672 
4673 	ath_tx_kick(sc);
4674 }
4675 
4676 /*
4677  * Deferred processing of transmit interrupt; special-cased
4678  * for four hardware queues, 0-3 (e.g. 5212 w/ WME support).
4679  */
4680 static void
4681 ath_tx_proc_q0123(void *arg, int npending)
4682 {
4683 	struct ath_softc *sc = arg;
4684 	struct ifnet *ifp = sc->sc_ifp;
4685 	int nacked;
4686 	uint32_t txqs;
4687 
4688 	ATH_PCU_LOCK(sc);
4689 	sc->sc_txproc_cnt++;
4690 	txqs = sc->sc_txq_active;
4691 	sc->sc_txq_active &= ~txqs;
4692 	ATH_PCU_UNLOCK(sc);
4693 
4694 	ATH_LOCK(sc);
4695 	ath_power_set_power_state(sc, HAL_PM_AWAKE);
4696 	ATH_UNLOCK(sc);
4697 
4698 	ATH_KTR(sc, ATH_KTR_TXCOMP, 1,
4699 	    "ath_tx_proc_q0123: txqs=0x%08x", txqs);
4700 
4701 	/*
4702 	 * Process each active queue.
4703 	 */
4704 	nacked = 0;
4705 	if (TXQACTIVE(txqs, 0))
4706 		nacked += ath_tx_processq(sc, &sc->sc_txq[0], 1);
4707 	if (TXQACTIVE(txqs, 1))
4708 		nacked += ath_tx_processq(sc, &sc->sc_txq[1], 1);
4709 	if (TXQACTIVE(txqs, 2))
4710 		nacked += ath_tx_processq(sc, &sc->sc_txq[2], 1);
4711 	if (TXQACTIVE(txqs, 3))
4712 		nacked += ath_tx_processq(sc, &sc->sc_txq[3], 1);
4713 	if (TXQACTIVE(txqs, sc->sc_cabq->axq_qnum))
4714 		ath_tx_processq(sc, sc->sc_cabq, 1);
4715 	if (nacked)
4716 		sc->sc_lastrx = ath_hal_gettsf64(sc->sc_ah);
4717 
4718 	IF_LOCK(&ifp->if_snd);
4719 	ifp->if_drv_flags &= ~IFF_DRV_OACTIVE;
4720 	IF_UNLOCK(&ifp->if_snd);
4721 	sc->sc_wd_timer = 0;
4722 
4723 	if (sc->sc_softled)
4724 		ath_led_event(sc, sc->sc_txrix);
4725 
4726 	ATH_PCU_LOCK(sc);
4727 	sc->sc_txproc_cnt--;
4728 	ATH_PCU_UNLOCK(sc);
4729 
4730 	ATH_LOCK(sc);
4731 	ath_power_restore_power_state(sc);
4732 	ATH_UNLOCK(sc);
4733 
4734 	ath_tx_kick(sc);
4735 }
4736 
4737 /*
4738  * Deferred processing of transmit interrupt.
4739  */
4740 static void
4741 ath_tx_proc(void *arg, int npending)
4742 {
4743 	struct ath_softc *sc = arg;
4744 	struct ifnet *ifp = sc->sc_ifp;
4745 	int i, nacked;
4746 	uint32_t txqs;
4747 
4748 	ATH_PCU_LOCK(sc);
4749 	sc->sc_txproc_cnt++;
4750 	txqs = sc->sc_txq_active;
4751 	sc->sc_txq_active &= ~txqs;
4752 	ATH_PCU_UNLOCK(sc);
4753 
4754 	ATH_LOCK(sc);
4755 	ath_power_set_power_state(sc, HAL_PM_AWAKE);
4756 	ATH_UNLOCK(sc);
4757 
4758 	ATH_KTR(sc, ATH_KTR_TXCOMP, 1, "ath_tx_proc: txqs=0x%08x", txqs);
4759 
4760 	/*
4761 	 * Process each active queue.
4762 	 */
4763 	nacked = 0;
4764 	for (i = 0; i < HAL_NUM_TX_QUEUES; i++)
4765 		if (ATH_TXQ_SETUP(sc, i) && TXQACTIVE(txqs, i))
4766 			nacked += ath_tx_processq(sc, &sc->sc_txq[i], 1);
4767 	if (nacked)
4768 		sc->sc_lastrx = ath_hal_gettsf64(sc->sc_ah);
4769 
4770 	/* XXX check this inside of IF_LOCK? */
4771 	IF_LOCK(&ifp->if_snd);
4772 	ifp->if_drv_flags &= ~IFF_DRV_OACTIVE;
4773 	IF_UNLOCK(&ifp->if_snd);
4774 	sc->sc_wd_timer = 0;
4775 
4776 	if (sc->sc_softled)
4777 		ath_led_event(sc, sc->sc_txrix);
4778 
4779 	ATH_PCU_LOCK(sc);
4780 	sc->sc_txproc_cnt--;
4781 	ATH_PCU_UNLOCK(sc);
4782 
4783 	ATH_LOCK(sc);
4784 	ath_power_restore_power_state(sc);
4785 	ATH_UNLOCK(sc);
4786 
4787 	ath_tx_kick(sc);
4788 }
4789 #undef	TXQACTIVE
4790 
4791 /*
4792  * Deferred processing of TXQ rescheduling.
4793  */
4794 static void
4795 ath_txq_sched_tasklet(void *arg, int npending)
4796 {
4797 	struct ath_softc *sc = arg;
4798 	int i;
4799 
4800 	/* XXX is skipping ok? */
4801 	ATH_PCU_LOCK(sc);
4802 #if 0
4803 	if (sc->sc_inreset_cnt > 0) {
4804 		device_printf(sc->sc_dev,
4805 		    "%s: sc_inreset_cnt > 0; skipping\n", __func__);
4806 		ATH_PCU_UNLOCK(sc);
4807 		return;
4808 	}
4809 #endif
4810 	sc->sc_txproc_cnt++;
4811 	ATH_PCU_UNLOCK(sc);
4812 
4813 	ATH_LOCK(sc);
4814 	ath_power_set_power_state(sc, HAL_PM_AWAKE);
4815 	ATH_UNLOCK(sc);
4816 
4817 	ATH_TX_LOCK(sc);
4818 	for (i = 0; i < HAL_NUM_TX_QUEUES; i++) {
4819 		if (ATH_TXQ_SETUP(sc, i)) {
4820 			ath_txq_sched(sc, &sc->sc_txq[i]);
4821 		}
4822 	}
4823 	ATH_TX_UNLOCK(sc);
4824 
4825 	ATH_LOCK(sc);
4826 	ath_power_restore_power_state(sc);
4827 	ATH_UNLOCK(sc);
4828 
4829 	ATH_PCU_LOCK(sc);
4830 	sc->sc_txproc_cnt--;
4831 	ATH_PCU_UNLOCK(sc);
4832 }
4833 
4834 void
4835 ath_returnbuf_tail(struct ath_softc *sc, struct ath_buf *bf)
4836 {
4837 
4838 	ATH_TXBUF_LOCK_ASSERT(sc);
4839 
4840 	if (bf->bf_flags & ATH_BUF_MGMT)
4841 		TAILQ_INSERT_TAIL(&sc->sc_txbuf_mgmt, bf, bf_list);
4842 	else {
4843 		TAILQ_INSERT_TAIL(&sc->sc_txbuf, bf, bf_list);
4844 		sc->sc_txbuf_cnt++;
4845 		if (sc->sc_txbuf_cnt > ath_txbuf) {
4846 			device_printf(sc->sc_dev,
4847 			    "%s: sc_txbuf_cnt > %d?\n",
4848 			    __func__,
4849 			    ath_txbuf);
4850 			sc->sc_txbuf_cnt = ath_txbuf;
4851 		}
4852 	}
4853 }
4854 
4855 void
4856 ath_returnbuf_head(struct ath_softc *sc, struct ath_buf *bf)
4857 {
4858 
4859 	ATH_TXBUF_LOCK_ASSERT(sc);
4860 
4861 	if (bf->bf_flags & ATH_BUF_MGMT)
4862 		TAILQ_INSERT_HEAD(&sc->sc_txbuf_mgmt, bf, bf_list);
4863 	else {
4864 		TAILQ_INSERT_HEAD(&sc->sc_txbuf, bf, bf_list);
4865 		sc->sc_txbuf_cnt++;
4866 		if (sc->sc_txbuf_cnt > ATH_TXBUF) {
4867 			device_printf(sc->sc_dev,
4868 			    "%s: sc_txbuf_cnt > %d?\n",
4869 			    __func__,
4870 			    ATH_TXBUF);
4871 			sc->sc_txbuf_cnt = ATH_TXBUF;
4872 		}
4873 	}
4874 }
4875 
4876 /*
4877  * Free the holding buffer if it exists
4878  */
4879 void
4880 ath_txq_freeholdingbuf(struct ath_softc *sc, struct ath_txq *txq)
4881 {
4882 	ATH_TXBUF_UNLOCK_ASSERT(sc);
4883 	ATH_TXQ_LOCK_ASSERT(txq);
4884 
4885 	if (txq->axq_holdingbf == NULL)
4886 		return;
4887 
4888 	txq->axq_holdingbf->bf_flags &= ~ATH_BUF_BUSY;
4889 
4890 	ATH_TXBUF_LOCK(sc);
4891 	ath_returnbuf_tail(sc, txq->axq_holdingbf);
4892 	ATH_TXBUF_UNLOCK(sc);
4893 
4894 	txq->axq_holdingbf = NULL;
4895 }
4896 
4897 /*
4898  * Add this buffer to the holding queue, freeing the previous
4899  * one if it exists.
4900  */
4901 static void
4902 ath_txq_addholdingbuf(struct ath_softc *sc, struct ath_buf *bf)
4903 {
4904 	struct ath_txq *txq;
4905 
4906 	txq = &sc->sc_txq[bf->bf_state.bfs_tx_queue];
4907 
4908 	ATH_TXBUF_UNLOCK_ASSERT(sc);
4909 	ATH_TXQ_LOCK_ASSERT(txq);
4910 
4911 	/* XXX assert ATH_BUF_BUSY is set */
4912 
4913 	/* XXX assert the tx queue is under the max number */
4914 	if (bf->bf_state.bfs_tx_queue > HAL_NUM_TX_QUEUES) {
4915 		device_printf(sc->sc_dev, "%s: bf=%p: invalid tx queue (%d)\n",
4916 		    __func__,
4917 		    bf,
4918 		    bf->bf_state.bfs_tx_queue);
4919 		bf->bf_flags &= ~ATH_BUF_BUSY;
4920 		ath_returnbuf_tail(sc, bf);
4921 		return;
4922 	}
4923 	ath_txq_freeholdingbuf(sc, txq);
4924 	txq->axq_holdingbf = bf;
4925 }
4926 
4927 /*
4928  * Return a buffer to the pool and update the 'busy' flag on the
4929  * previous 'tail' entry.
4930  *
4931  * This _must_ only be called when the buffer is involved in a completed
4932  * TX. The logic is that if it was part of an active TX, the previous
4933  * buffer on the list is now not involved in a halted TX DMA queue, waiting
4934  * for restart (eg for TDMA.)
4935  *
4936  * The caller must free the mbuf and recycle the node reference.
4937  *
4938  * XXX This method of handling busy / holding buffers is insanely stupid.
4939  * It requires bf_state.bfs_tx_queue to be correctly assigned.  It would
4940  * be much nicer if buffers in the processq() methods would instead be
4941  * always completed there (pushed onto a txq or ath_bufhead) so we knew
4942  * exactly what hardware queue they came from in the first place.
4943  */
4944 void
4945 ath_freebuf(struct ath_softc *sc, struct ath_buf *bf)
4946 {
4947 	struct ath_txq *txq;
4948 
4949 	txq = &sc->sc_txq[bf->bf_state.bfs_tx_queue];
4950 
4951 	KASSERT((bf->bf_node == NULL), ("%s: bf->bf_node != NULL\n", __func__));
4952 	KASSERT((bf->bf_m == NULL), ("%s: bf->bf_m != NULL\n", __func__));
4953 
4954 	/*
4955 	 * If this buffer is busy, push it onto the holding queue.
4956 	 */
4957 	if (bf->bf_flags & ATH_BUF_BUSY) {
4958 		ATH_TXQ_LOCK(txq);
4959 		ath_txq_addholdingbuf(sc, bf);
4960 		ATH_TXQ_UNLOCK(txq);
4961 		return;
4962 	}
4963 
4964 	/*
4965 	 * Not a busy buffer, so free normally
4966 	 */
4967 	ATH_TXBUF_LOCK(sc);
4968 	ath_returnbuf_tail(sc, bf);
4969 	ATH_TXBUF_UNLOCK(sc);
4970 }
4971 
4972 /*
4973  * This is currently used by ath_tx_draintxq() and
4974  * ath_tx_tid_free_pkts().
4975  *
4976  * It recycles a single ath_buf.
4977  */
4978 void
4979 ath_tx_freebuf(struct ath_softc *sc, struct ath_buf *bf, int status)
4980 {
4981 	struct ieee80211_node *ni = bf->bf_node;
4982 	struct mbuf *m0 = bf->bf_m;
4983 
4984 	/*
4985 	 * Make sure that we only sync/unload if there's an mbuf.
4986 	 * If not (eg we cloned a buffer), the unload will have already
4987 	 * occured.
4988 	 */
4989 	if (bf->bf_m != NULL) {
4990 		bus_dmamap_sync(sc->sc_dmat, bf->bf_dmamap,
4991 		    BUS_DMASYNC_POSTWRITE);
4992 		bus_dmamap_unload(sc->sc_dmat, bf->bf_dmamap);
4993 	}
4994 
4995 	bf->bf_node = NULL;
4996 	bf->bf_m = NULL;
4997 
4998 	/* Free the buffer, it's not needed any longer */
4999 	ath_freebuf(sc, bf);
5000 
5001 	/* Pass the buffer back to net80211 - completing it */
5002 	ieee80211_tx_complete(ni, m0, status);
5003 }
5004 
5005 static struct ath_buf *
5006 ath_tx_draintxq_get_one(struct ath_softc *sc, struct ath_txq *txq)
5007 {
5008 	struct ath_buf *bf;
5009 
5010 	ATH_TXQ_LOCK_ASSERT(txq);
5011 
5012 	/*
5013 	 * Drain the FIFO queue first, then if it's
5014 	 * empty, move to the normal frame queue.
5015 	 */
5016 	bf = TAILQ_FIRST(&txq->fifo.axq_q);
5017 	if (bf != NULL) {
5018 		/*
5019 		 * Is it the last buffer in this set?
5020 		 * Decrement the FIFO counter.
5021 		 */
5022 		if (bf->bf_flags & ATH_BUF_FIFOEND) {
5023 			if (txq->axq_fifo_depth == 0) {
5024 				device_printf(sc->sc_dev,
5025 				    "%s: Q%d: fifo_depth=0, fifo.axq_depth=%d?\n",
5026 				    __func__,
5027 				    txq->axq_qnum,
5028 				    txq->fifo.axq_depth);
5029 			} else
5030 				txq->axq_fifo_depth--;
5031 		}
5032 		ATH_TXQ_REMOVE(&txq->fifo, bf, bf_list);
5033 		return (bf);
5034 	}
5035 
5036 	/*
5037 	 * Debugging!
5038 	 */
5039 	if (txq->axq_fifo_depth != 0 || txq->fifo.axq_depth != 0) {
5040 		device_printf(sc->sc_dev,
5041 		    "%s: Q%d: fifo_depth=%d, fifo.axq_depth=%d\n",
5042 		    __func__,
5043 		    txq->axq_qnum,
5044 		    txq->axq_fifo_depth,
5045 		    txq->fifo.axq_depth);
5046 	}
5047 
5048 	/*
5049 	 * Now drain the pending queue.
5050 	 */
5051 	bf = TAILQ_FIRST(&txq->axq_q);
5052 	if (bf == NULL) {
5053 		txq->axq_link = NULL;
5054 		return (NULL);
5055 	}
5056 	ATH_TXQ_REMOVE(txq, bf, bf_list);
5057 	return (bf);
5058 }
5059 
5060 void
5061 ath_tx_draintxq(struct ath_softc *sc, struct ath_txq *txq)
5062 {
5063 #ifdef ATH_DEBUG
5064 	struct ath_hal *ah = sc->sc_ah;
5065 #endif
5066 	struct ath_buf *bf;
5067 	u_int ix;
5068 
5069 	/*
5070 	 * NB: this assumes output has been stopped and
5071 	 *     we do not need to block ath_tx_proc
5072 	 */
5073 	for (ix = 0;; ix++) {
5074 		ATH_TXQ_LOCK(txq);
5075 		bf = ath_tx_draintxq_get_one(sc, txq);
5076 		if (bf == NULL) {
5077 			ATH_TXQ_UNLOCK(txq);
5078 			break;
5079 		}
5080 		if (bf->bf_state.bfs_aggr)
5081 			txq->axq_aggr_depth--;
5082 #ifdef ATH_DEBUG
5083 		if (sc->sc_debug & ATH_DEBUG_RESET) {
5084 			struct ieee80211com *ic = sc->sc_ifp->if_l2com;
5085 			int status = 0;
5086 
5087 			/*
5088 			 * EDMA operation has a TX completion FIFO
5089 			 * separate from the TX descriptor, so this
5090 			 * method of checking the "completion" status
5091 			 * is wrong.
5092 			 */
5093 			if (! sc->sc_isedma) {
5094 				status = (ath_hal_txprocdesc(ah,
5095 				    bf->bf_lastds,
5096 				    &bf->bf_status.ds_txstat) == HAL_OK);
5097 			}
5098 			ath_printtxbuf(sc, bf, txq->axq_qnum, ix, status);
5099 			ieee80211_dump_pkt(ic, mtod(bf->bf_m, const uint8_t *),
5100 			    bf->bf_m->m_len, 0, -1);
5101 		}
5102 #endif /* ATH_DEBUG */
5103 		/*
5104 		 * Since we're now doing magic in the completion
5105 		 * functions, we -must- call it for aggregation
5106 		 * destinations or BAW tracking will get upset.
5107 		 */
5108 		/*
5109 		 * Clear ATH_BUF_BUSY; the completion handler
5110 		 * will free the buffer.
5111 		 */
5112 		ATH_TXQ_UNLOCK(txq);
5113 		bf->bf_flags &= ~ATH_BUF_BUSY;
5114 		if (bf->bf_comp)
5115 			bf->bf_comp(sc, bf, 1);
5116 		else
5117 			ath_tx_default_comp(sc, bf, 1);
5118 	}
5119 
5120 	/*
5121 	 * Free the holding buffer if it exists
5122 	 */
5123 	ATH_TXQ_LOCK(txq);
5124 	ath_txq_freeholdingbuf(sc, txq);
5125 	ATH_TXQ_UNLOCK(txq);
5126 
5127 	/*
5128 	 * Drain software queued frames which are on
5129 	 * active TIDs.
5130 	 */
5131 	ath_tx_txq_drain(sc, txq);
5132 }
5133 
5134 static void
5135 ath_tx_stopdma(struct ath_softc *sc, struct ath_txq *txq)
5136 {
5137 	struct ath_hal *ah = sc->sc_ah;
5138 
5139 	ATH_TXQ_LOCK_ASSERT(txq);
5140 
5141 	DPRINTF(sc, ATH_DEBUG_RESET,
5142 	    "%s: tx queue [%u] %p, active=%d, hwpending=%d, flags 0x%08x, "
5143 	    "link %p, holdingbf=%p\n",
5144 	    __func__,
5145 	    txq->axq_qnum,
5146 	    (caddr_t)(uintptr_t) ath_hal_gettxbuf(ah, txq->axq_qnum),
5147 	    (int) (!! ath_hal_txqenabled(ah, txq->axq_qnum)),
5148 	    (int) ath_hal_numtxpending(ah, txq->axq_qnum),
5149 	    txq->axq_flags,
5150 	    txq->axq_link,
5151 	    txq->axq_holdingbf);
5152 
5153 	(void) ath_hal_stoptxdma(ah, txq->axq_qnum);
5154 	/* We've stopped TX DMA, so mark this as stopped. */
5155 	txq->axq_flags &= ~ATH_TXQ_PUTRUNNING;
5156 
5157 #ifdef	ATH_DEBUG
5158 	if ((sc->sc_debug & ATH_DEBUG_RESET)
5159 	    && (txq->axq_holdingbf != NULL)) {
5160 		ath_printtxbuf(sc, txq->axq_holdingbf, txq->axq_qnum, 0, 0);
5161 	}
5162 #endif
5163 }
5164 
5165 int
5166 ath_stoptxdma(struct ath_softc *sc)
5167 {
5168 	struct ath_hal *ah = sc->sc_ah;
5169 	int i;
5170 
5171 	/* XXX return value */
5172 	if (sc->sc_invalid)
5173 		return 0;
5174 
5175 	if (!sc->sc_invalid) {
5176 		/* don't touch the hardware if marked invalid */
5177 		DPRINTF(sc, ATH_DEBUG_RESET, "%s: tx queue [%u] %p, link %p\n",
5178 		    __func__, sc->sc_bhalq,
5179 		    (caddr_t)(uintptr_t) ath_hal_gettxbuf(ah, sc->sc_bhalq),
5180 		    NULL);
5181 
5182 		/* stop the beacon queue */
5183 		(void) ath_hal_stoptxdma(ah, sc->sc_bhalq);
5184 
5185 		/* Stop the data queues */
5186 		for (i = 0; i < HAL_NUM_TX_QUEUES; i++) {
5187 			if (ATH_TXQ_SETUP(sc, i)) {
5188 				ATH_TXQ_LOCK(&sc->sc_txq[i]);
5189 				ath_tx_stopdma(sc, &sc->sc_txq[i]);
5190 				ATH_TXQ_UNLOCK(&sc->sc_txq[i]);
5191 			}
5192 		}
5193 	}
5194 
5195 	return 1;
5196 }
5197 
5198 #ifdef	ATH_DEBUG
5199 void
5200 ath_tx_dump(struct ath_softc *sc, struct ath_txq *txq)
5201 {
5202 	struct ath_hal *ah = sc->sc_ah;
5203 	struct ath_buf *bf;
5204 	int i = 0;
5205 
5206 	if (! (sc->sc_debug & ATH_DEBUG_RESET))
5207 		return;
5208 
5209 	device_printf(sc->sc_dev, "%s: Q%d: begin\n",
5210 	    __func__, txq->axq_qnum);
5211 	TAILQ_FOREACH(bf, &txq->axq_q, bf_list) {
5212 		ath_printtxbuf(sc, bf, txq->axq_qnum, i,
5213 			ath_hal_txprocdesc(ah, bf->bf_lastds,
5214 			    &bf->bf_status.ds_txstat) == HAL_OK);
5215 		i++;
5216 	}
5217 	device_printf(sc->sc_dev, "%s: Q%d: end\n",
5218 	    __func__, txq->axq_qnum);
5219 }
5220 #endif /* ATH_DEBUG */
5221 
5222 /*
5223  * Drain the transmit queues and reclaim resources.
5224  */
5225 void
5226 ath_legacy_tx_drain(struct ath_softc *sc, ATH_RESET_TYPE reset_type)
5227 {
5228 	struct ath_hal *ah = sc->sc_ah;
5229 	struct ifnet *ifp = sc->sc_ifp;
5230 	int i;
5231 	struct ath_buf *bf_last;
5232 
5233 	(void) ath_stoptxdma(sc);
5234 
5235 	/*
5236 	 * Dump the queue contents
5237 	 */
5238 	for (i = 0; i < HAL_NUM_TX_QUEUES; i++) {
5239 		/*
5240 		 * XXX TODO: should we just handle the completed TX frames
5241 		 * here, whether or not the reset is a full one or not?
5242 		 */
5243 		if (ATH_TXQ_SETUP(sc, i)) {
5244 #ifdef	ATH_DEBUG
5245 			if (sc->sc_debug & ATH_DEBUG_RESET)
5246 				ath_tx_dump(sc, &sc->sc_txq[i]);
5247 #endif	/* ATH_DEBUG */
5248 			if (reset_type == ATH_RESET_NOLOSS) {
5249 				ath_tx_processq(sc, &sc->sc_txq[i], 0);
5250 				ATH_TXQ_LOCK(&sc->sc_txq[i]);
5251 				/*
5252 				 * Free the holding buffer; DMA is now
5253 				 * stopped.
5254 				 */
5255 				ath_txq_freeholdingbuf(sc, &sc->sc_txq[i]);
5256 				/*
5257 				 * Setup the link pointer to be the
5258 				 * _last_ buffer/descriptor in the list.
5259 				 * If there's nothing in the list, set it
5260 				 * to NULL.
5261 				 */
5262 				bf_last = ATH_TXQ_LAST(&sc->sc_txq[i],
5263 				    axq_q_s);
5264 				if (bf_last != NULL) {
5265 					ath_hal_gettxdesclinkptr(ah,
5266 					    bf_last->bf_lastds,
5267 					    &sc->sc_txq[i].axq_link);
5268 				} else {
5269 					sc->sc_txq[i].axq_link = NULL;
5270 				}
5271 				ATH_TXQ_UNLOCK(&sc->sc_txq[i]);
5272 			} else
5273 				ath_tx_draintxq(sc, &sc->sc_txq[i]);
5274 		}
5275 	}
5276 #ifdef ATH_DEBUG
5277 	if (sc->sc_debug & ATH_DEBUG_RESET) {
5278 		struct ath_buf *bf = TAILQ_FIRST(&sc->sc_bbuf);
5279 		if (bf != NULL && bf->bf_m != NULL) {
5280 			ath_printtxbuf(sc, bf, sc->sc_bhalq, 0,
5281 				ath_hal_txprocdesc(ah, bf->bf_lastds,
5282 				    &bf->bf_status.ds_txstat) == HAL_OK);
5283 			ieee80211_dump_pkt(ifp->if_l2com,
5284 			    mtod(bf->bf_m, const uint8_t *), bf->bf_m->m_len,
5285 			    0, -1);
5286 		}
5287 	}
5288 #endif /* ATH_DEBUG */
5289 	IF_LOCK(&ifp->if_snd);
5290 	ifp->if_drv_flags &= ~IFF_DRV_OACTIVE;
5291 	IF_UNLOCK(&ifp->if_snd);
5292 	sc->sc_wd_timer = 0;
5293 }
5294 
5295 /*
5296  * Update internal state after a channel change.
5297  */
5298 static void
5299 ath_chan_change(struct ath_softc *sc, struct ieee80211_channel *chan)
5300 {
5301 	enum ieee80211_phymode mode;
5302 
5303 	/*
5304 	 * Change channels and update the h/w rate map
5305 	 * if we're switching; e.g. 11a to 11b/g.
5306 	 */
5307 	mode = ieee80211_chan2mode(chan);
5308 	if (mode != sc->sc_curmode)
5309 		ath_setcurmode(sc, mode);
5310 	sc->sc_curchan = chan;
5311 }
5312 
5313 /*
5314  * Set/change channels.  If the channel is really being changed,
5315  * it's done by resetting the chip.  To accomplish this we must
5316  * first cleanup any pending DMA, then restart stuff after a la
5317  * ath_init.
5318  */
5319 static int
5320 ath_chan_set(struct ath_softc *sc, struct ieee80211_channel *chan)
5321 {
5322 	struct ifnet *ifp = sc->sc_ifp;
5323 	struct ieee80211com *ic = ifp->if_l2com;
5324 	struct ath_hal *ah = sc->sc_ah;
5325 	int ret = 0;
5326 
5327 	/* Treat this as an interface reset */
5328 	ATH_PCU_UNLOCK_ASSERT(sc);
5329 	ATH_UNLOCK_ASSERT(sc);
5330 
5331 	/* (Try to) stop TX/RX from occuring */
5332 	taskqueue_block(sc->sc_tq);
5333 
5334 	ATH_PCU_LOCK(sc);
5335 
5336 	/* Stop new RX/TX/interrupt completion */
5337 	if (ath_reset_grablock(sc, 1) == 0) {
5338 		device_printf(sc->sc_dev, "%s: concurrent reset! Danger!\n",
5339 		    __func__);
5340 	}
5341 
5342 	ath_hal_intrset(ah, 0);
5343 
5344 	/* Stop pending RX/TX completion */
5345 	ath_txrx_stop_locked(sc);
5346 
5347 	ATH_PCU_UNLOCK(sc);
5348 
5349 	DPRINTF(sc, ATH_DEBUG_RESET, "%s: %u (%u MHz, flags 0x%x)\n",
5350 	    __func__, ieee80211_chan2ieee(ic, chan),
5351 	    chan->ic_freq, chan->ic_flags);
5352 	if (chan != sc->sc_curchan) {
5353 		HAL_STATUS status;
5354 		/*
5355 		 * To switch channels clear any pending DMA operations;
5356 		 * wait long enough for the RX fifo to drain, reset the
5357 		 * hardware at the new frequency, and then re-enable
5358 		 * the relevant bits of the h/w.
5359 		 */
5360 #if 0
5361 		ath_hal_intrset(ah, 0);		/* disable interrupts */
5362 #endif
5363 		ath_stoprecv(sc, 1);		/* turn off frame recv */
5364 		/*
5365 		 * First, handle completed TX/RX frames.
5366 		 */
5367 		ath_rx_flush(sc);
5368 		ath_draintxq(sc, ATH_RESET_NOLOSS);
5369 		/*
5370 		 * Next, flush the non-scheduled frames.
5371 		 */
5372 		ath_draintxq(sc, ATH_RESET_FULL);	/* clear pending tx frames */
5373 
5374 		ath_update_chainmasks(sc, chan);
5375 		ath_hal_setchainmasks(sc->sc_ah, sc->sc_cur_txchainmask,
5376 		    sc->sc_cur_rxchainmask);
5377 		if (!ath_hal_reset(ah, sc->sc_opmode, chan, AH_TRUE, &status)) {
5378 			if_printf(ifp, "%s: unable to reset "
5379 			    "channel %u (%u MHz, flags 0x%x), hal status %u\n",
5380 			    __func__, ieee80211_chan2ieee(ic, chan),
5381 			    chan->ic_freq, chan->ic_flags, status);
5382 			ret = EIO;
5383 			goto finish;
5384 		}
5385 		sc->sc_diversity = ath_hal_getdiversity(ah);
5386 
5387 		/* Let DFS at it in case it's a DFS channel */
5388 		ath_dfs_radar_enable(sc, chan);
5389 
5390 		/* Let spectral at in case spectral is enabled */
5391 		ath_spectral_enable(sc, chan);
5392 
5393 		/*
5394 		 * Let bluetooth coexistence at in case it's needed for this
5395 		 * channel
5396 		 */
5397 		ath_btcoex_enable(sc, ic->ic_curchan);
5398 
5399 		/*
5400 		 * If we're doing TDMA, enforce the TXOP limitation for chips
5401 		 * that support it.
5402 		 */
5403 		if (sc->sc_hasenforcetxop && sc->sc_tdma)
5404 			ath_hal_setenforcetxop(sc->sc_ah, 1);
5405 		else
5406 			ath_hal_setenforcetxop(sc->sc_ah, 0);
5407 
5408 		/*
5409 		 * Re-enable rx framework.
5410 		 */
5411 		if (ath_startrecv(sc) != 0) {
5412 			if_printf(ifp, "%s: unable to restart recv logic\n",
5413 			    __func__);
5414 			ret = EIO;
5415 			goto finish;
5416 		}
5417 
5418 		/*
5419 		 * Change channels and update the h/w rate map
5420 		 * if we're switching; e.g. 11a to 11b/g.
5421 		 */
5422 		ath_chan_change(sc, chan);
5423 
5424 		/*
5425 		 * Reset clears the beacon timers; reset them
5426 		 * here if needed.
5427 		 */
5428 		if (sc->sc_beacons) {		/* restart beacons */
5429 #ifdef IEEE80211_SUPPORT_TDMA
5430 			if (sc->sc_tdma)
5431 				ath_tdma_config(sc, NULL);
5432 			else
5433 #endif
5434 			ath_beacon_config(sc, NULL);
5435 		}
5436 
5437 		/*
5438 		 * Re-enable interrupts.
5439 		 */
5440 #if 0
5441 		ath_hal_intrset(ah, sc->sc_imask);
5442 #endif
5443 	}
5444 
5445 finish:
5446 	ATH_PCU_LOCK(sc);
5447 	sc->sc_inreset_cnt--;
5448 	/* XXX only do this if sc_inreset_cnt == 0? */
5449 	ath_hal_intrset(ah, sc->sc_imask);
5450 	ATH_PCU_UNLOCK(sc);
5451 
5452 	IF_LOCK(&ifp->if_snd);
5453 	ifp->if_drv_flags &= ~IFF_DRV_OACTIVE;
5454 	IF_UNLOCK(&ifp->if_snd);
5455 	ath_txrx_start(sc);
5456 	/* XXX ath_start? */
5457 
5458 	return ret;
5459 }
5460 
5461 /*
5462  * Periodically recalibrate the PHY to account
5463  * for temperature/environment changes.
5464  */
5465 static void
5466 ath_calibrate(void *arg)
5467 {
5468 	struct ath_softc *sc = arg;
5469 	struct ath_hal *ah = sc->sc_ah;
5470 	struct ifnet *ifp = sc->sc_ifp;
5471 	struct ieee80211com *ic = ifp->if_l2com;
5472 	HAL_BOOL longCal, isCalDone = AH_TRUE;
5473 	HAL_BOOL aniCal, shortCal = AH_FALSE;
5474 	int nextcal;
5475 
5476 	/*
5477 	 * Force the hardware awake for ANI work.
5478 	 */
5479 	ath_power_set_power_state(sc, HAL_PM_AWAKE);
5480 
5481 	/* Skip trying to do this if we're in reset */
5482 	if (sc->sc_inreset_cnt)
5483 		goto restart;
5484 
5485 	if (ic->ic_flags & IEEE80211_F_SCAN)	/* defer, off channel */
5486 		goto restart;
5487 	longCal = (ticks - sc->sc_lastlongcal >= ath_longcalinterval*hz);
5488 	aniCal = (ticks - sc->sc_lastani >= ath_anicalinterval*hz/1000);
5489 	if (sc->sc_doresetcal)
5490 		shortCal = (ticks - sc->sc_lastshortcal >= ath_shortcalinterval*hz/1000);
5491 
5492 	DPRINTF(sc, ATH_DEBUG_CALIBRATE, "%s: shortCal=%d; longCal=%d; aniCal=%d\n", __func__, shortCal, longCal, aniCal);
5493 	if (aniCal) {
5494 		sc->sc_stats.ast_ani_cal++;
5495 		sc->sc_lastani = ticks;
5496 		ath_hal_ani_poll(ah, sc->sc_curchan);
5497 	}
5498 
5499 	if (longCal) {
5500 		sc->sc_stats.ast_per_cal++;
5501 		sc->sc_lastlongcal = ticks;
5502 		if (ath_hal_getrfgain(ah) == HAL_RFGAIN_NEED_CHANGE) {
5503 			/*
5504 			 * Rfgain is out of bounds, reset the chip
5505 			 * to load new gain values.
5506 			 */
5507 			DPRINTF(sc, ATH_DEBUG_CALIBRATE,
5508 				"%s: rfgain change\n", __func__);
5509 			sc->sc_stats.ast_per_rfgain++;
5510 			sc->sc_resetcal = 0;
5511 			sc->sc_doresetcal = AH_TRUE;
5512 			taskqueue_enqueue(sc->sc_tq, &sc->sc_resettask);
5513 			callout_reset(&sc->sc_cal_ch, 1, ath_calibrate, sc);
5514 			ath_power_restore_power_state(sc);
5515 			return;
5516 		}
5517 		/*
5518 		 * If this long cal is after an idle period, then
5519 		 * reset the data collection state so we start fresh.
5520 		 */
5521 		if (sc->sc_resetcal) {
5522 			(void) ath_hal_calreset(ah, sc->sc_curchan);
5523 			sc->sc_lastcalreset = ticks;
5524 			sc->sc_lastshortcal = ticks;
5525 			sc->sc_resetcal = 0;
5526 			sc->sc_doresetcal = AH_TRUE;
5527 		}
5528 	}
5529 
5530 	/* Only call if we're doing a short/long cal, not for ANI calibration */
5531 	if (shortCal || longCal) {
5532 		isCalDone = AH_FALSE;
5533 		if (ath_hal_calibrateN(ah, sc->sc_curchan, longCal, &isCalDone)) {
5534 			if (longCal) {
5535 				/*
5536 				 * Calibrate noise floor data again in case of change.
5537 				 */
5538 				ath_hal_process_noisefloor(ah);
5539 			}
5540 		} else {
5541 			DPRINTF(sc, ATH_DEBUG_ANY,
5542 				"%s: calibration of channel %u failed\n",
5543 				__func__, sc->sc_curchan->ic_freq);
5544 			sc->sc_stats.ast_per_calfail++;
5545 		}
5546 		if (shortCal)
5547 			sc->sc_lastshortcal = ticks;
5548 	}
5549 	if (!isCalDone) {
5550 restart:
5551 		/*
5552 		 * Use a shorter interval to potentially collect multiple
5553 		 * data samples required to complete calibration.  Once
5554 		 * we're told the work is done we drop back to a longer
5555 		 * interval between requests.  We're more aggressive doing
5556 		 * work when operating as an AP to improve operation right
5557 		 * after startup.
5558 		 */
5559 		sc->sc_lastshortcal = ticks;
5560 		nextcal = ath_shortcalinterval*hz/1000;
5561 		if (sc->sc_opmode != HAL_M_HOSTAP)
5562 			nextcal *= 10;
5563 		sc->sc_doresetcal = AH_TRUE;
5564 	} else {
5565 		/* nextcal should be the shortest time for next event */
5566 		nextcal = ath_longcalinterval*hz;
5567 		if (sc->sc_lastcalreset == 0)
5568 			sc->sc_lastcalreset = sc->sc_lastlongcal;
5569 		else if (ticks - sc->sc_lastcalreset >= ath_resetcalinterval*hz)
5570 			sc->sc_resetcal = 1;	/* setup reset next trip */
5571 		sc->sc_doresetcal = AH_FALSE;
5572 	}
5573 	/* ANI calibration may occur more often than short/long/resetcal */
5574 	if (ath_anicalinterval > 0)
5575 		nextcal = MIN(nextcal, ath_anicalinterval*hz/1000);
5576 
5577 	if (nextcal != 0) {
5578 		DPRINTF(sc, ATH_DEBUG_CALIBRATE, "%s: next +%u (%sisCalDone)\n",
5579 		    __func__, nextcal, isCalDone ? "" : "!");
5580 		callout_reset(&sc->sc_cal_ch, nextcal, ath_calibrate, sc);
5581 	} else {
5582 		DPRINTF(sc, ATH_DEBUG_CALIBRATE, "%s: calibration disabled\n",
5583 		    __func__);
5584 		/* NB: don't rearm timer */
5585 	}
5586 	/*
5587 	 * Restore power state now that we're done.
5588 	 */
5589 	ath_power_restore_power_state(sc);
5590 }
5591 
5592 static void
5593 ath_scan_start(struct ieee80211com *ic)
5594 {
5595 	struct ifnet *ifp = ic->ic_ifp;
5596 	struct ath_softc *sc = ifp->if_softc;
5597 	struct ath_hal *ah = sc->sc_ah;
5598 	u_int32_t rfilt;
5599 
5600 	/* XXX calibration timer? */
5601 
5602 	ATH_LOCK(sc);
5603 	sc->sc_scanning = 1;
5604 	sc->sc_syncbeacon = 0;
5605 	rfilt = ath_calcrxfilter(sc);
5606 	ATH_UNLOCK(sc);
5607 
5608 	ATH_PCU_LOCK(sc);
5609 	ath_hal_setrxfilter(ah, rfilt);
5610 	ath_hal_setassocid(ah, ifp->if_broadcastaddr, 0);
5611 	ATH_PCU_UNLOCK(sc);
5612 
5613 	DPRINTF(sc, ATH_DEBUG_STATE, "%s: RX filter 0x%x bssid %s aid 0\n",
5614 		 __func__, rfilt, ether_sprintf(ifp->if_broadcastaddr));
5615 }
5616 
5617 static void
5618 ath_scan_end(struct ieee80211com *ic)
5619 {
5620 	struct ifnet *ifp = ic->ic_ifp;
5621 	struct ath_softc *sc = ifp->if_softc;
5622 	struct ath_hal *ah = sc->sc_ah;
5623 	u_int32_t rfilt;
5624 
5625 	ATH_LOCK(sc);
5626 	sc->sc_scanning = 0;
5627 	rfilt = ath_calcrxfilter(sc);
5628 	ATH_UNLOCK(sc);
5629 
5630 	ATH_PCU_LOCK(sc);
5631 	ath_hal_setrxfilter(ah, rfilt);
5632 	ath_hal_setassocid(ah, sc->sc_curbssid, sc->sc_curaid);
5633 
5634 	ath_hal_process_noisefloor(ah);
5635 	ATH_PCU_UNLOCK(sc);
5636 
5637 	DPRINTF(sc, ATH_DEBUG_STATE, "%s: RX filter 0x%x bssid %s aid 0x%x\n",
5638 		 __func__, rfilt, ether_sprintf(sc->sc_curbssid),
5639 		 sc->sc_curaid);
5640 }
5641 
5642 #ifdef	ATH_ENABLE_11N
5643 /*
5644  * For now, just do a channel change.
5645  *
5646  * Later, we'll go through the hard slog of suspending tx/rx, changing rate
5647  * control state and resetting the hardware without dropping frames out
5648  * of the queue.
5649  *
5650  * The unfortunate trouble here is making absolutely sure that the
5651  * channel width change has propagated enough so the hardware
5652  * absolutely isn't handed bogus frames for it's current operating
5653  * mode. (Eg, 40MHz frames in 20MHz mode.) Since TX and RX can and
5654  * does occur in parallel, we need to make certain we've blocked
5655  * any further ongoing TX (and RX, that can cause raw TX)
5656  * before we do this.
5657  */
5658 static void
5659 ath_update_chw(struct ieee80211com *ic)
5660 {
5661 	struct ifnet *ifp = ic->ic_ifp;
5662 	struct ath_softc *sc = ifp->if_softc;
5663 
5664 	DPRINTF(sc, ATH_DEBUG_STATE, "%s: called\n", __func__);
5665 	ath_set_channel(ic);
5666 }
5667 #endif	/* ATH_ENABLE_11N */
5668 
5669 static void
5670 ath_set_channel(struct ieee80211com *ic)
5671 {
5672 	struct ifnet *ifp = ic->ic_ifp;
5673 	struct ath_softc *sc = ifp->if_softc;
5674 
5675 	ATH_LOCK(sc);
5676 	ath_power_set_power_state(sc, HAL_PM_AWAKE);
5677 	ATH_UNLOCK(sc);
5678 
5679 	(void) ath_chan_set(sc, ic->ic_curchan);
5680 	/*
5681 	 * If we are returning to our bss channel then mark state
5682 	 * so the next recv'd beacon's tsf will be used to sync the
5683 	 * beacon timers.  Note that since we only hear beacons in
5684 	 * sta/ibss mode this has no effect in other operating modes.
5685 	 */
5686 	ATH_LOCK(sc);
5687 	if (!sc->sc_scanning && ic->ic_curchan == ic->ic_bsschan)
5688 		sc->sc_syncbeacon = 1;
5689 	ath_power_restore_power_state(sc);
5690 	ATH_UNLOCK(sc);
5691 }
5692 
5693 /*
5694  * Walk the vap list and check if there any vap's in RUN state.
5695  */
5696 static int
5697 ath_isanyrunningvaps(struct ieee80211vap *this)
5698 {
5699 	struct ieee80211com *ic = this->iv_ic;
5700 	struct ieee80211vap *vap;
5701 
5702 	IEEE80211_LOCK_ASSERT(ic);
5703 
5704 	TAILQ_FOREACH(vap, &ic->ic_vaps, iv_next) {
5705 		if (vap != this && vap->iv_state >= IEEE80211_S_RUN)
5706 			return 1;
5707 	}
5708 	return 0;
5709 }
5710 
5711 static int
5712 ath_newstate(struct ieee80211vap *vap, enum ieee80211_state nstate, int arg)
5713 {
5714 	struct ieee80211com *ic = vap->iv_ic;
5715 	struct ath_softc *sc = ic->ic_ifp->if_softc;
5716 	struct ath_vap *avp = ATH_VAP(vap);
5717 	struct ath_hal *ah = sc->sc_ah;
5718 	struct ieee80211_node *ni = NULL;
5719 	int i, error, stamode;
5720 	u_int32_t rfilt;
5721 	int csa_run_transition = 0;
5722 	enum ieee80211_state ostate = vap->iv_state;
5723 
5724 	static const HAL_LED_STATE leds[] = {
5725 	    HAL_LED_INIT,	/* IEEE80211_S_INIT */
5726 	    HAL_LED_SCAN,	/* IEEE80211_S_SCAN */
5727 	    HAL_LED_AUTH,	/* IEEE80211_S_AUTH */
5728 	    HAL_LED_ASSOC, 	/* IEEE80211_S_ASSOC */
5729 	    HAL_LED_RUN, 	/* IEEE80211_S_CAC */
5730 	    HAL_LED_RUN, 	/* IEEE80211_S_RUN */
5731 	    HAL_LED_RUN, 	/* IEEE80211_S_CSA */
5732 	    HAL_LED_RUN, 	/* IEEE80211_S_SLEEP */
5733 	};
5734 
5735 	DPRINTF(sc, ATH_DEBUG_STATE, "%s: %s -> %s\n", __func__,
5736 		ieee80211_state_name[ostate],
5737 		ieee80211_state_name[nstate]);
5738 
5739 	/*
5740 	 * net80211 _should_ have the comlock asserted at this point.
5741 	 * There are some comments around the calls to vap->iv_newstate
5742 	 * which indicate that it (newstate) may end up dropping the
5743 	 * lock.  This and the subsequent lock assert check after newstate
5744 	 * are an attempt to catch these and figure out how/why.
5745 	 */
5746 	IEEE80211_LOCK_ASSERT(ic);
5747 
5748 	/* Before we touch the hardware - wake it up */
5749 	ATH_LOCK(sc);
5750 	/*
5751 	 * If the NIC is in anything other than SLEEP state,
5752 	 * we need to ensure that self-generated frames are
5753 	 * set for PWRMGT=0.  Otherwise we may end up with
5754 	 * strange situations.
5755 	 *
5756 	 * XXX TODO: is this actually the case? :-)
5757 	 */
5758 	if (nstate != IEEE80211_S_SLEEP)
5759 		ath_power_setselfgen(sc, HAL_PM_AWAKE);
5760 
5761 	/*
5762 	 * Now, wake the thing up.
5763 	 */
5764 	ath_power_set_power_state(sc, HAL_PM_AWAKE);
5765 	ATH_UNLOCK(sc);
5766 
5767 	if (ostate == IEEE80211_S_CSA && nstate == IEEE80211_S_RUN)
5768 		csa_run_transition = 1;
5769 
5770 	callout_drain(&sc->sc_cal_ch);
5771 	ath_hal_setledstate(ah, leds[nstate]);	/* set LED */
5772 
5773 	if (nstate == IEEE80211_S_SCAN) {
5774 		/*
5775 		 * Scanning: turn off beacon miss and don't beacon.
5776 		 * Mark beacon state so when we reach RUN state we'll
5777 		 * [re]setup beacons.  Unblock the task q thread so
5778 		 * deferred interrupt processing is done.
5779 		 */
5780 
5781 		/* Ensure we stay awake during scan */
5782 		ATH_LOCK(sc);
5783 		ath_power_setselfgen(sc, HAL_PM_AWAKE);
5784 		ath_power_setpower(sc, HAL_PM_AWAKE);
5785 		ATH_UNLOCK(sc);
5786 
5787 		ath_hal_intrset(ah,
5788 		    sc->sc_imask &~ (HAL_INT_SWBA | HAL_INT_BMISS));
5789 		sc->sc_imask &= ~(HAL_INT_SWBA | HAL_INT_BMISS);
5790 		sc->sc_beacons = 0;
5791 		taskqueue_unblock(sc->sc_tq);
5792 	}
5793 
5794 	ni = ieee80211_ref_node(vap->iv_bss);
5795 	rfilt = ath_calcrxfilter(sc);
5796 	stamode = (vap->iv_opmode == IEEE80211_M_STA ||
5797 		   vap->iv_opmode == IEEE80211_M_AHDEMO ||
5798 		   vap->iv_opmode == IEEE80211_M_IBSS);
5799 
5800 	/*
5801 	 * XXX Dont need to do this (and others) if we've transitioned
5802 	 * from SLEEP->RUN.
5803 	 */
5804 	if (stamode && nstate == IEEE80211_S_RUN) {
5805 		sc->sc_curaid = ni->ni_associd;
5806 		IEEE80211_ADDR_COPY(sc->sc_curbssid, ni->ni_bssid);
5807 		ath_hal_setassocid(ah, sc->sc_curbssid, sc->sc_curaid);
5808 	}
5809 	DPRINTF(sc, ATH_DEBUG_STATE, "%s: RX filter 0x%x bssid %s aid 0x%x\n",
5810 	   __func__, rfilt, ether_sprintf(sc->sc_curbssid), sc->sc_curaid);
5811 	ath_hal_setrxfilter(ah, rfilt);
5812 
5813 	/* XXX is this to restore keycache on resume? */
5814 	if (vap->iv_opmode != IEEE80211_M_STA &&
5815 	    (vap->iv_flags & IEEE80211_F_PRIVACY)) {
5816 		for (i = 0; i < IEEE80211_WEP_NKID; i++)
5817 			if (ath_hal_keyisvalid(ah, i))
5818 				ath_hal_keysetmac(ah, i, ni->ni_bssid);
5819 	}
5820 
5821 	/*
5822 	 * Invoke the parent method to do net80211 work.
5823 	 */
5824 	error = avp->av_newstate(vap, nstate, arg);
5825 	if (error != 0)
5826 		goto bad;
5827 
5828 	/*
5829 	 * See above: ensure av_newstate() doesn't drop the lock
5830 	 * on us.
5831 	 */
5832 	IEEE80211_LOCK_ASSERT(ic);
5833 
5834 	if (nstate == IEEE80211_S_RUN) {
5835 		/* NB: collect bss node again, it may have changed */
5836 		ieee80211_free_node(ni);
5837 		ni = ieee80211_ref_node(vap->iv_bss);
5838 
5839 		DPRINTF(sc, ATH_DEBUG_STATE,
5840 		    "%s(RUN): iv_flags 0x%08x bintvl %d bssid %s "
5841 		    "capinfo 0x%04x chan %d\n", __func__,
5842 		    vap->iv_flags, ni->ni_intval, ether_sprintf(ni->ni_bssid),
5843 		    ni->ni_capinfo, ieee80211_chan2ieee(ic, ic->ic_curchan));
5844 
5845 		switch (vap->iv_opmode) {
5846 #ifdef IEEE80211_SUPPORT_TDMA
5847 		case IEEE80211_M_AHDEMO:
5848 			if ((vap->iv_caps & IEEE80211_C_TDMA) == 0)
5849 				break;
5850 			/* fall thru... */
5851 #endif
5852 		case IEEE80211_M_HOSTAP:
5853 		case IEEE80211_M_IBSS:
5854 		case IEEE80211_M_MBSS:
5855 			/*
5856 			 * Allocate and setup the beacon frame.
5857 			 *
5858 			 * Stop any previous beacon DMA.  This may be
5859 			 * necessary, for example, when an ibss merge
5860 			 * causes reconfiguration; there will be a state
5861 			 * transition from RUN->RUN that means we may
5862 			 * be called with beacon transmission active.
5863 			 */
5864 			ath_hal_stoptxdma(ah, sc->sc_bhalq);
5865 
5866 			error = ath_beacon_alloc(sc, ni);
5867 			if (error != 0)
5868 				goto bad;
5869 			/*
5870 			 * If joining an adhoc network defer beacon timer
5871 			 * configuration to the next beacon frame so we
5872 			 * have a current TSF to use.  Otherwise we're
5873 			 * starting an ibss/bss so there's no need to delay;
5874 			 * if this is the first vap moving to RUN state, then
5875 			 * beacon state needs to be [re]configured.
5876 			 */
5877 			if (vap->iv_opmode == IEEE80211_M_IBSS &&
5878 			    ni->ni_tstamp.tsf != 0) {
5879 				sc->sc_syncbeacon = 1;
5880 			} else if (!sc->sc_beacons) {
5881 #ifdef IEEE80211_SUPPORT_TDMA
5882 				if (vap->iv_caps & IEEE80211_C_TDMA)
5883 					ath_tdma_config(sc, vap);
5884 				else
5885 #endif
5886 					ath_beacon_config(sc, vap);
5887 				sc->sc_beacons = 1;
5888 			}
5889 			break;
5890 		case IEEE80211_M_STA:
5891 			/*
5892 			 * Defer beacon timer configuration to the next
5893 			 * beacon frame so we have a current TSF to use
5894 			 * (any TSF collected when scanning is likely old).
5895 			 * However if it's due to a CSA -> RUN transition,
5896 			 * force a beacon update so we pick up a lack of
5897 			 * beacons from an AP in CAC and thus force a
5898 			 * scan.
5899 			 *
5900 			 * And, there's also corner cases here where
5901 			 * after a scan, the AP may have disappeared.
5902 			 * In that case, we may not receive an actual
5903 			 * beacon to update the beacon timer and thus we
5904 			 * won't get notified of the missing beacons.
5905 			 */
5906 			if (ostate != IEEE80211_S_RUN &&
5907 			    ostate != IEEE80211_S_SLEEP) {
5908 				DPRINTF(sc, ATH_DEBUG_BEACON,
5909 				    "%s: STA; syncbeacon=1\n", __func__);
5910 				sc->sc_syncbeacon = 1;
5911 
5912 				if (csa_run_transition)
5913 					ath_beacon_config(sc, vap);
5914 
5915 			/*
5916 			 * PR: kern/175227
5917 			 *
5918 			 * Reconfigure beacons during reset; as otherwise
5919 			 * we won't get the beacon timers reprogrammed
5920 			 * after a reset and thus we won't pick up a
5921 			 * beacon miss interrupt.
5922 			 *
5923 			 * Hopefully we'll see a beacon before the BMISS
5924 			 * timer fires (too often), leading to a STA
5925 			 * disassociation.
5926 			 */
5927 				sc->sc_beacons = 1;
5928 			}
5929 			break;
5930 		case IEEE80211_M_MONITOR:
5931 			/*
5932 			 * Monitor mode vaps have only INIT->RUN and RUN->RUN
5933 			 * transitions so we must re-enable interrupts here to
5934 			 * handle the case of a single monitor mode vap.
5935 			 */
5936 			ath_hal_intrset(ah, sc->sc_imask);
5937 			break;
5938 		case IEEE80211_M_WDS:
5939 			break;
5940 		default:
5941 			break;
5942 		}
5943 		/*
5944 		 * Let the hal process statistics collected during a
5945 		 * scan so it can provide calibrated noise floor data.
5946 		 */
5947 		ath_hal_process_noisefloor(ah);
5948 		/*
5949 		 * Reset rssi stats; maybe not the best place...
5950 		 */
5951 		sc->sc_halstats.ns_avgbrssi = ATH_RSSI_DUMMY_MARKER;
5952 		sc->sc_halstats.ns_avgrssi = ATH_RSSI_DUMMY_MARKER;
5953 		sc->sc_halstats.ns_avgtxrssi = ATH_RSSI_DUMMY_MARKER;
5954 
5955 		/*
5956 		 * Force awake for RUN mode.
5957 		 */
5958 		ATH_LOCK(sc);
5959 		ath_power_setselfgen(sc, HAL_PM_AWAKE);
5960 		ath_power_setpower(sc, HAL_PM_AWAKE);
5961 		ATH_UNLOCK(sc);
5962 
5963 		/*
5964 		 * Finally, start any timers and the task q thread
5965 		 * (in case we didn't go through SCAN state).
5966 		 */
5967 		if (ath_longcalinterval != 0) {
5968 			/* start periodic recalibration timer */
5969 			callout_reset(&sc->sc_cal_ch, 1, ath_calibrate, sc);
5970 		} else {
5971 			DPRINTF(sc, ATH_DEBUG_CALIBRATE,
5972 			    "%s: calibration disabled\n", __func__);
5973 		}
5974 
5975 		taskqueue_unblock(sc->sc_tq);
5976 	} else if (nstate == IEEE80211_S_INIT) {
5977 		/*
5978 		 * If there are no vaps left in RUN state then
5979 		 * shutdown host/driver operation:
5980 		 * o disable interrupts
5981 		 * o disable the task queue thread
5982 		 * o mark beacon processing as stopped
5983 		 */
5984 		if (!ath_isanyrunningvaps(vap)) {
5985 			sc->sc_imask &= ~(HAL_INT_SWBA | HAL_INT_BMISS);
5986 			/* disable interrupts  */
5987 			ath_hal_intrset(ah, sc->sc_imask &~ HAL_INT_GLOBAL);
5988 			taskqueue_block(sc->sc_tq);
5989 			sc->sc_beacons = 0;
5990 		}
5991 #ifdef IEEE80211_SUPPORT_TDMA
5992 		ath_hal_setcca(ah, AH_TRUE);
5993 #endif
5994 	} else if (nstate == IEEE80211_S_SLEEP) {
5995 		/* We're going to sleep, so transition appropriately */
5996 		/* For now, only do this if we're a single STA vap */
5997 		if (sc->sc_nvaps == 1 &&
5998 		    vap->iv_opmode == IEEE80211_M_STA) {
5999 			DPRINTF(sc, ATH_DEBUG_BEACON, "%s: syncbeacon=%d\n", __func__, sc->sc_syncbeacon);
6000 			ATH_LOCK(sc);
6001 			/*
6002 			 * Always at least set the self-generated
6003 			 * frame config to set PWRMGT=1.
6004 			 */
6005 			ath_power_setselfgen(sc, HAL_PM_NETWORK_SLEEP);
6006 
6007 			/*
6008 			 * If we're not syncing beacons, transition
6009 			 * to NETWORK_SLEEP.
6010 			 *
6011 			 * We stay awake if syncbeacon > 0 in case
6012 			 * we need to listen for some beacons otherwise
6013 			 * our beacon timer config may be wrong.
6014 			 */
6015 			if (sc->sc_syncbeacon == 0) {
6016 				ath_power_setpower(sc, HAL_PM_NETWORK_SLEEP);
6017 			}
6018 			ATH_UNLOCK(sc);
6019 		}
6020 	}
6021 bad:
6022 	ieee80211_free_node(ni);
6023 
6024 	/*
6025 	 * Restore the power state - either to what it was, or
6026 	 * to network_sleep if it's alright.
6027 	 */
6028 	ATH_LOCK(sc);
6029 	ath_power_restore_power_state(sc);
6030 	ATH_UNLOCK(sc);
6031 	return error;
6032 }
6033 
6034 /*
6035  * Allocate a key cache slot to the station so we can
6036  * setup a mapping from key index to node. The key cache
6037  * slot is needed for managing antenna state and for
6038  * compression when stations do not use crypto.  We do
6039  * it uniliaterally here; if crypto is employed this slot
6040  * will be reassigned.
6041  */
6042 static void
6043 ath_setup_stationkey(struct ieee80211_node *ni)
6044 {
6045 	struct ieee80211vap *vap = ni->ni_vap;
6046 	struct ath_softc *sc = vap->iv_ic->ic_ifp->if_softc;
6047 	ieee80211_keyix keyix, rxkeyix;
6048 
6049 	/* XXX should take a locked ref to vap->iv_bss */
6050 	if (!ath_key_alloc(vap, &ni->ni_ucastkey, &keyix, &rxkeyix)) {
6051 		/*
6052 		 * Key cache is full; we'll fall back to doing
6053 		 * the more expensive lookup in software.  Note
6054 		 * this also means no h/w compression.
6055 		 */
6056 		/* XXX msg+statistic */
6057 	} else {
6058 		/* XXX locking? */
6059 		ni->ni_ucastkey.wk_keyix = keyix;
6060 		ni->ni_ucastkey.wk_rxkeyix = rxkeyix;
6061 		/* NB: must mark device key to get called back on delete */
6062 		ni->ni_ucastkey.wk_flags |= IEEE80211_KEY_DEVKEY;
6063 		IEEE80211_ADDR_COPY(ni->ni_ucastkey.wk_macaddr, ni->ni_macaddr);
6064 		/* NB: this will create a pass-thru key entry */
6065 		ath_keyset(sc, vap, &ni->ni_ucastkey, vap->iv_bss);
6066 	}
6067 }
6068 
6069 /*
6070  * Setup driver-specific state for a newly associated node.
6071  * Note that we're called also on a re-associate, the isnew
6072  * param tells us if this is the first time or not.
6073  */
6074 static void
6075 ath_newassoc(struct ieee80211_node *ni, int isnew)
6076 {
6077 	struct ath_node *an = ATH_NODE(ni);
6078 	struct ieee80211vap *vap = ni->ni_vap;
6079 	struct ath_softc *sc = vap->iv_ic->ic_ifp->if_softc;
6080 	const struct ieee80211_txparam *tp = ni->ni_txparms;
6081 
6082 	an->an_mcastrix = ath_tx_findrix(sc, tp->mcastrate);
6083 	an->an_mgmtrix = ath_tx_findrix(sc, tp->mgmtrate);
6084 
6085 	DPRINTF(sc, ATH_DEBUG_NODE, "%s: %6D: reassoc; isnew=%d, is_powersave=%d\n",
6086 	    __func__,
6087 	    ni->ni_macaddr,
6088 	    ":",
6089 	    isnew,
6090 	    an->an_is_powersave);
6091 
6092 	ATH_NODE_LOCK(an);
6093 	ath_rate_newassoc(sc, an, isnew);
6094 	ATH_NODE_UNLOCK(an);
6095 
6096 	if (isnew &&
6097 	    (vap->iv_flags & IEEE80211_F_PRIVACY) == 0 && sc->sc_hasclrkey &&
6098 	    ni->ni_ucastkey.wk_keyix == IEEE80211_KEYIX_NONE)
6099 		ath_setup_stationkey(ni);
6100 
6101 	/*
6102 	 * If we're reassociating, make sure that any paused queues
6103 	 * get unpaused.
6104 	 *
6105 	 * Now, we may hvae frames in the hardware queue for this node.
6106 	 * So if we are reassociating and there are frames in the queue,
6107 	 * we need to go through the cleanup path to ensure that they're
6108 	 * marked as non-aggregate.
6109 	 */
6110 	if (! isnew) {
6111 		DPRINTF(sc, ATH_DEBUG_NODE,
6112 		    "%s: %6D: reassoc; is_powersave=%d\n",
6113 		    __func__,
6114 		    ni->ni_macaddr,
6115 		    ":",
6116 		    an->an_is_powersave);
6117 
6118 		/* XXX for now, we can't hold the lock across assoc */
6119 		ath_tx_node_reassoc(sc, an);
6120 
6121 		/* XXX for now, we can't hold the lock across wakeup */
6122 		if (an->an_is_powersave)
6123 			ath_tx_node_wakeup(sc, an);
6124 	}
6125 }
6126 
6127 static int
6128 ath_setregdomain(struct ieee80211com *ic, struct ieee80211_regdomain *reg,
6129 	int nchans, struct ieee80211_channel chans[])
6130 {
6131 	struct ath_softc *sc = ic->ic_ifp->if_softc;
6132 	struct ath_hal *ah = sc->sc_ah;
6133 	HAL_STATUS status;
6134 
6135 	DPRINTF(sc, ATH_DEBUG_REGDOMAIN,
6136 	    "%s: rd %u cc %u location %c%s\n",
6137 	    __func__, reg->regdomain, reg->country, reg->location,
6138 	    reg->ecm ? " ecm" : "");
6139 
6140 	status = ath_hal_set_channels(ah, chans, nchans,
6141 	    reg->country, reg->regdomain);
6142 	if (status != HAL_OK) {
6143 		DPRINTF(sc, ATH_DEBUG_REGDOMAIN, "%s: failed, status %u\n",
6144 		    __func__, status);
6145 		return EINVAL;		/* XXX */
6146 	}
6147 
6148 	return 0;
6149 }
6150 
6151 static void
6152 ath_getradiocaps(struct ieee80211com *ic,
6153 	int maxchans, int *nchans, struct ieee80211_channel chans[])
6154 {
6155 	struct ath_softc *sc = ic->ic_ifp->if_softc;
6156 	struct ath_hal *ah = sc->sc_ah;
6157 
6158 	DPRINTF(sc, ATH_DEBUG_REGDOMAIN, "%s: use rd %u cc %d\n",
6159 	    __func__, SKU_DEBUG, CTRY_DEFAULT);
6160 
6161 	/* XXX check return */
6162 	(void) ath_hal_getchannels(ah, chans, maxchans, nchans,
6163 	    HAL_MODE_ALL, CTRY_DEFAULT, SKU_DEBUG, AH_TRUE);
6164 
6165 }
6166 
6167 static int
6168 ath_getchannels(struct ath_softc *sc)
6169 {
6170 	struct ifnet *ifp = sc->sc_ifp;
6171 	struct ieee80211com *ic = ifp->if_l2com;
6172 	struct ath_hal *ah = sc->sc_ah;
6173 	HAL_STATUS status;
6174 
6175 	/*
6176 	 * Collect channel set based on EEPROM contents.
6177 	 */
6178 	status = ath_hal_init_channels(ah, ic->ic_channels, IEEE80211_CHAN_MAX,
6179 	    &ic->ic_nchans, HAL_MODE_ALL, CTRY_DEFAULT, SKU_NONE, AH_TRUE);
6180 	if (status != HAL_OK) {
6181 		if_printf(ifp, "%s: unable to collect channel list from hal, "
6182 		    "status %d\n", __func__, status);
6183 		return EINVAL;
6184 	}
6185 	(void) ath_hal_getregdomain(ah, &sc->sc_eerd);
6186 	ath_hal_getcountrycode(ah, &sc->sc_eecc);	/* NB: cannot fail */
6187 	/* XXX map Atheros sku's to net80211 SKU's */
6188 	/* XXX net80211 types too small */
6189 	ic->ic_regdomain.regdomain = (uint16_t) sc->sc_eerd;
6190 	ic->ic_regdomain.country = (uint16_t) sc->sc_eecc;
6191 	ic->ic_regdomain.isocc[0] = ' ';	/* XXX don't know */
6192 	ic->ic_regdomain.isocc[1] = ' ';
6193 
6194 	ic->ic_regdomain.ecm = 1;
6195 	ic->ic_regdomain.location = 'I';
6196 
6197 	DPRINTF(sc, ATH_DEBUG_REGDOMAIN,
6198 	    "%s: eeprom rd %u cc %u (mapped rd %u cc %u) location %c%s\n",
6199 	    __func__, sc->sc_eerd, sc->sc_eecc,
6200 	    ic->ic_regdomain.regdomain, ic->ic_regdomain.country,
6201 	    ic->ic_regdomain.location, ic->ic_regdomain.ecm ? " ecm" : "");
6202 	return 0;
6203 }
6204 
6205 static int
6206 ath_rate_setup(struct ath_softc *sc, u_int mode)
6207 {
6208 	struct ath_hal *ah = sc->sc_ah;
6209 	const HAL_RATE_TABLE *rt;
6210 
6211 	switch (mode) {
6212 	case IEEE80211_MODE_11A:
6213 		rt = ath_hal_getratetable(ah, HAL_MODE_11A);
6214 		break;
6215 	case IEEE80211_MODE_HALF:
6216 		rt = ath_hal_getratetable(ah, HAL_MODE_11A_HALF_RATE);
6217 		break;
6218 	case IEEE80211_MODE_QUARTER:
6219 		rt = ath_hal_getratetable(ah, HAL_MODE_11A_QUARTER_RATE);
6220 		break;
6221 	case IEEE80211_MODE_11B:
6222 		rt = ath_hal_getratetable(ah, HAL_MODE_11B);
6223 		break;
6224 	case IEEE80211_MODE_11G:
6225 		rt = ath_hal_getratetable(ah, HAL_MODE_11G);
6226 		break;
6227 	case IEEE80211_MODE_TURBO_A:
6228 		rt = ath_hal_getratetable(ah, HAL_MODE_108A);
6229 		break;
6230 	case IEEE80211_MODE_TURBO_G:
6231 		rt = ath_hal_getratetable(ah, HAL_MODE_108G);
6232 		break;
6233 	case IEEE80211_MODE_STURBO_A:
6234 		rt = ath_hal_getratetable(ah, HAL_MODE_TURBO);
6235 		break;
6236 	case IEEE80211_MODE_11NA:
6237 		rt = ath_hal_getratetable(ah, HAL_MODE_11NA_HT20);
6238 		break;
6239 	case IEEE80211_MODE_11NG:
6240 		rt = ath_hal_getratetable(ah, HAL_MODE_11NG_HT20);
6241 		break;
6242 	default:
6243 		DPRINTF(sc, ATH_DEBUG_ANY, "%s: invalid mode %u\n",
6244 			__func__, mode);
6245 		return 0;
6246 	}
6247 	sc->sc_rates[mode] = rt;
6248 	return (rt != NULL);
6249 }
6250 
6251 static void
6252 ath_setcurmode(struct ath_softc *sc, enum ieee80211_phymode mode)
6253 {
6254 #define	N(a)	(sizeof(a)/sizeof(a[0]))
6255 	/* NB: on/off times from the Atheros NDIS driver, w/ permission */
6256 	static const struct {
6257 		u_int		rate;		/* tx/rx 802.11 rate */
6258 		u_int16_t	timeOn;		/* LED on time (ms) */
6259 		u_int16_t	timeOff;	/* LED off time (ms) */
6260 	} blinkrates[] = {
6261 		{ 108,  40,  10 },
6262 		{  96,  44,  11 },
6263 		{  72,  50,  13 },
6264 		{  48,  57,  14 },
6265 		{  36,  67,  16 },
6266 		{  24,  80,  20 },
6267 		{  22, 100,  25 },
6268 		{  18, 133,  34 },
6269 		{  12, 160,  40 },
6270 		{  10, 200,  50 },
6271 		{   6, 240,  58 },
6272 		{   4, 267,  66 },
6273 		{   2, 400, 100 },
6274 		{   0, 500, 130 },
6275 		/* XXX half/quarter rates */
6276 	};
6277 	const HAL_RATE_TABLE *rt;
6278 	int i, j;
6279 
6280 	memset(sc->sc_rixmap, 0xff, sizeof(sc->sc_rixmap));
6281 	rt = sc->sc_rates[mode];
6282 	KASSERT(rt != NULL, ("no h/w rate set for phy mode %u", mode));
6283 	for (i = 0; i < rt->rateCount; i++) {
6284 		uint8_t ieeerate = rt->info[i].dot11Rate & IEEE80211_RATE_VAL;
6285 		if (rt->info[i].phy != IEEE80211_T_HT)
6286 			sc->sc_rixmap[ieeerate] = i;
6287 		else
6288 			sc->sc_rixmap[ieeerate | IEEE80211_RATE_MCS] = i;
6289 	}
6290 	memset(sc->sc_hwmap, 0, sizeof(sc->sc_hwmap));
6291 	for (i = 0; i < N(sc->sc_hwmap); i++) {
6292 		if (i >= rt->rateCount) {
6293 			sc->sc_hwmap[i].ledon = (500 * hz) / 1000;
6294 			sc->sc_hwmap[i].ledoff = (130 * hz) / 1000;
6295 			continue;
6296 		}
6297 		sc->sc_hwmap[i].ieeerate =
6298 			rt->info[i].dot11Rate & IEEE80211_RATE_VAL;
6299 		if (rt->info[i].phy == IEEE80211_T_HT)
6300 			sc->sc_hwmap[i].ieeerate |= IEEE80211_RATE_MCS;
6301 		sc->sc_hwmap[i].txflags = IEEE80211_RADIOTAP_F_DATAPAD;
6302 		if (rt->info[i].shortPreamble ||
6303 		    rt->info[i].phy == IEEE80211_T_OFDM)
6304 			sc->sc_hwmap[i].txflags |= IEEE80211_RADIOTAP_F_SHORTPRE;
6305 		sc->sc_hwmap[i].rxflags = sc->sc_hwmap[i].txflags;
6306 		for (j = 0; j < N(blinkrates)-1; j++)
6307 			if (blinkrates[j].rate == sc->sc_hwmap[i].ieeerate)
6308 				break;
6309 		/* NB: this uses the last entry if the rate isn't found */
6310 		/* XXX beware of overlow */
6311 		sc->sc_hwmap[i].ledon = (blinkrates[j].timeOn * hz) / 1000;
6312 		sc->sc_hwmap[i].ledoff = (blinkrates[j].timeOff * hz) / 1000;
6313 	}
6314 	sc->sc_currates = rt;
6315 	sc->sc_curmode = mode;
6316 	/*
6317 	 * All protection frames are transmited at 2Mb/s for
6318 	 * 11g, otherwise at 1Mb/s.
6319 	 */
6320 	if (mode == IEEE80211_MODE_11G)
6321 		sc->sc_protrix = ath_tx_findrix(sc, 2*2);
6322 	else
6323 		sc->sc_protrix = ath_tx_findrix(sc, 2*1);
6324 	/* NB: caller is responsible for resetting rate control state */
6325 #undef N
6326 }
6327 
6328 static void
6329 ath_watchdog(void *arg)
6330 {
6331 	struct ath_softc *sc = arg;
6332 	int do_reset = 0;
6333 
6334 	if (sc->sc_wd_timer != 0 && --sc->sc_wd_timer == 0) {
6335 		struct ifnet *ifp = sc->sc_ifp;
6336 		uint32_t hangs;
6337 
6338 		ATH_LOCK(sc);
6339 		ath_power_set_power_state(sc, HAL_PM_AWAKE);
6340 		ATH_UNLOCK(sc);
6341 
6342 		if (ath_hal_gethangstate(sc->sc_ah, 0xffff, &hangs) &&
6343 		    hangs != 0) {
6344 			if_printf(ifp, "%s hang detected (0x%x)\n",
6345 			    hangs & 0xff ? "bb" : "mac", hangs);
6346 		} else
6347 			if_printf(ifp, "device timeout\n");
6348 		do_reset = 1;
6349 		ifp->if_oerrors++;
6350 		sc->sc_stats.ast_watchdog++;
6351 
6352 		ATH_LOCK(sc);
6353 		ath_power_restore_power_state(sc);
6354 		ATH_UNLOCK(sc);
6355 	}
6356 
6357 	/*
6358 	 * We can't hold the lock across the ath_reset() call.
6359 	 *
6360 	 * And since this routine can't hold a lock and sleep,
6361 	 * do the reset deferred.
6362 	 */
6363 	if (do_reset) {
6364 		taskqueue_enqueue(sc->sc_tq, &sc->sc_resettask);
6365 	}
6366 
6367 	callout_schedule(&sc->sc_wd_ch, hz);
6368 }
6369 
6370 /*
6371  * Fetch the rate control statistics for the given node.
6372  */
6373 static int
6374 ath_ioctl_ratestats(struct ath_softc *sc, struct ath_rateioctl *rs)
6375 {
6376 	struct ath_node *an;
6377 	struct ieee80211com *ic = sc->sc_ifp->if_l2com;
6378 	struct ieee80211_node *ni;
6379 	int error = 0;
6380 
6381 	/* Perform a lookup on the given node */
6382 	ni = ieee80211_find_node(&ic->ic_sta, rs->is_u.macaddr);
6383 	if (ni == NULL) {
6384 		error = EINVAL;
6385 		goto bad;
6386 	}
6387 
6388 	/* Lock the ath_node */
6389 	an = ATH_NODE(ni);
6390 	ATH_NODE_LOCK(an);
6391 
6392 	/* Fetch the rate control stats for this node */
6393 	error = ath_rate_fetch_node_stats(sc, an, rs);
6394 
6395 	/* No matter what happens here, just drop through */
6396 
6397 	/* Unlock the ath_node */
6398 	ATH_NODE_UNLOCK(an);
6399 
6400 	/* Unref the node */
6401 	ieee80211_node_decref(ni);
6402 
6403 bad:
6404 	return (error);
6405 }
6406 
6407 #ifdef ATH_DIAGAPI
6408 /*
6409  * Diagnostic interface to the HAL.  This is used by various
6410  * tools to do things like retrieve register contents for
6411  * debugging.  The mechanism is intentionally opaque so that
6412  * it can change frequently w/o concern for compatiblity.
6413  */
6414 static int
6415 ath_ioctl_diag(struct ath_softc *sc, struct ath_diag *ad)
6416 {
6417 	struct ath_hal *ah = sc->sc_ah;
6418 	u_int id = ad->ad_id & ATH_DIAG_ID;
6419 	void *indata = NULL;
6420 	void *outdata = NULL;
6421 	u_int32_t insize = ad->ad_in_size;
6422 	u_int32_t outsize = ad->ad_out_size;
6423 	int error = 0;
6424 
6425 	if (ad->ad_id & ATH_DIAG_IN) {
6426 		/*
6427 		 * Copy in data.
6428 		 */
6429 		indata = malloc(insize, M_TEMP, M_NOWAIT);
6430 		if (indata == NULL) {
6431 			error = ENOMEM;
6432 			goto bad;
6433 		}
6434 		error = copyin(ad->ad_in_data, indata, insize);
6435 		if (error)
6436 			goto bad;
6437 	}
6438 	if (ad->ad_id & ATH_DIAG_DYN) {
6439 		/*
6440 		 * Allocate a buffer for the results (otherwise the HAL
6441 		 * returns a pointer to a buffer where we can read the
6442 		 * results).  Note that we depend on the HAL leaving this
6443 		 * pointer for us to use below in reclaiming the buffer;
6444 		 * may want to be more defensive.
6445 		 */
6446 		outdata = malloc(outsize, M_TEMP, M_NOWAIT);
6447 		if (outdata == NULL) {
6448 			error = ENOMEM;
6449 			goto bad;
6450 		}
6451 	}
6452 
6453 
6454 	ATH_LOCK(sc);
6455 	if (id != HAL_DIAG_REGS)
6456 		ath_power_set_power_state(sc, HAL_PM_AWAKE);
6457 	ATH_UNLOCK(sc);
6458 
6459 	if (ath_hal_getdiagstate(ah, id, indata, insize, &outdata, &outsize)) {
6460 		if (outsize < ad->ad_out_size)
6461 			ad->ad_out_size = outsize;
6462 		if (outdata != NULL)
6463 			error = copyout(outdata, ad->ad_out_data,
6464 					ad->ad_out_size);
6465 	} else {
6466 		error = EINVAL;
6467 	}
6468 
6469 	ATH_LOCK(sc);
6470 	if (id != HAL_DIAG_REGS)
6471 		ath_power_restore_power_state(sc);
6472 	ATH_UNLOCK(sc);
6473 
6474 bad:
6475 	if ((ad->ad_id & ATH_DIAG_IN) && indata != NULL)
6476 		free(indata, M_TEMP);
6477 	if ((ad->ad_id & ATH_DIAG_DYN) && outdata != NULL)
6478 		free(outdata, M_TEMP);
6479 	return error;
6480 }
6481 #endif /* ATH_DIAGAPI */
6482 
6483 static int
6484 ath_ioctl(struct ifnet *ifp, u_long cmd, caddr_t data)
6485 {
6486 #define	IS_RUNNING(ifp) \
6487 	((ifp->if_flags & IFF_UP) && (ifp->if_drv_flags & IFF_DRV_RUNNING))
6488 	struct ath_softc *sc = ifp->if_softc;
6489 	struct ieee80211com *ic = ifp->if_l2com;
6490 	struct ifreq *ifr = (struct ifreq *)data;
6491 	const HAL_RATE_TABLE *rt;
6492 	int error = 0;
6493 
6494 	switch (cmd) {
6495 	case SIOCSIFFLAGS:
6496 		if (IS_RUNNING(ifp)) {
6497 			/*
6498 			 * To avoid rescanning another access point,
6499 			 * do not call ath_init() here.  Instead,
6500 			 * only reflect promisc mode settings.
6501 			 */
6502 			ATH_LOCK(sc);
6503 			ath_power_set_power_state(sc, HAL_PM_AWAKE);
6504 			ath_mode_init(sc);
6505 			ath_power_restore_power_state(sc);
6506 			ATH_UNLOCK(sc);
6507 		} else if (ifp->if_flags & IFF_UP) {
6508 			/*
6509 			 * Beware of being called during attach/detach
6510 			 * to reset promiscuous mode.  In that case we
6511 			 * will still be marked UP but not RUNNING.
6512 			 * However trying to re-init the interface
6513 			 * is the wrong thing to do as we've already
6514 			 * torn down much of our state.  There's
6515 			 * probably a better way to deal with this.
6516 			 */
6517 			if (!sc->sc_invalid)
6518 				ath_init(sc);	/* XXX lose error */
6519 		} else {
6520 			ATH_LOCK(sc);
6521 			ath_stop_locked(ifp);
6522 			if (!sc->sc_invalid)
6523 				ath_power_setpower(sc, HAL_PM_FULL_SLEEP);
6524 			ATH_UNLOCK(sc);
6525 		}
6526 		break;
6527 	case SIOCGIFMEDIA:
6528 	case SIOCSIFMEDIA:
6529 		error = ifmedia_ioctl(ifp, ifr, &ic->ic_media, cmd);
6530 		break;
6531 	case SIOCGATHSTATS:
6532 		/* NB: embed these numbers to get a consistent view */
6533 		sc->sc_stats.ast_tx_packets = ifp->if_opackets;
6534 		sc->sc_stats.ast_rx_packets = ifp->if_ipackets;
6535 		sc->sc_stats.ast_tx_rssi = ATH_RSSI(sc->sc_halstats.ns_avgtxrssi);
6536 		sc->sc_stats.ast_rx_rssi = ATH_RSSI(sc->sc_halstats.ns_avgrssi);
6537 #ifdef IEEE80211_SUPPORT_TDMA
6538 		sc->sc_stats.ast_tdma_tsfadjp = TDMA_AVG(sc->sc_avgtsfdeltap);
6539 		sc->sc_stats.ast_tdma_tsfadjm = TDMA_AVG(sc->sc_avgtsfdeltam);
6540 #endif
6541 		rt = sc->sc_currates;
6542 		sc->sc_stats.ast_tx_rate =
6543 		    rt->info[sc->sc_txrix].dot11Rate &~ IEEE80211_RATE_BASIC;
6544 		if (rt->info[sc->sc_txrix].phy & IEEE80211_T_HT)
6545 			sc->sc_stats.ast_tx_rate |= IEEE80211_RATE_MCS;
6546 		return copyout(&sc->sc_stats,
6547 		    ifr->ifr_data, sizeof (sc->sc_stats));
6548 	case SIOCGATHAGSTATS:
6549 		return copyout(&sc->sc_aggr_stats,
6550 		    ifr->ifr_data, sizeof (sc->sc_aggr_stats));
6551 	case SIOCZATHSTATS:
6552 		error = priv_check(curthread, PRIV_DRIVER);
6553 		if (error == 0) {
6554 			memset(&sc->sc_stats, 0, sizeof(sc->sc_stats));
6555 			memset(&sc->sc_aggr_stats, 0,
6556 			    sizeof(sc->sc_aggr_stats));
6557 			memset(&sc->sc_intr_stats, 0,
6558 			    sizeof(sc->sc_intr_stats));
6559 		}
6560 		break;
6561 #ifdef ATH_DIAGAPI
6562 	case SIOCGATHDIAG:
6563 		error = ath_ioctl_diag(sc, (struct ath_diag *) ifr);
6564 		break;
6565 	case SIOCGATHPHYERR:
6566 		error = ath_ioctl_phyerr(sc,(struct ath_diag*) ifr);
6567 		break;
6568 #endif
6569 	case SIOCGATHSPECTRAL:
6570 		error = ath_ioctl_spectral(sc,(struct ath_diag*) ifr);
6571 		break;
6572 	case SIOCGATHNODERATESTATS:
6573 		error = ath_ioctl_ratestats(sc, (struct ath_rateioctl *) ifr);
6574 		break;
6575 	case SIOCGIFADDR:
6576 		error = ether_ioctl(ifp, cmd, data);
6577 		break;
6578 	default:
6579 		error = EINVAL;
6580 		break;
6581 	}
6582 	return error;
6583 #undef IS_RUNNING
6584 }
6585 
6586 /*
6587  * Announce various information on device/driver attach.
6588  */
6589 static void
6590 ath_announce(struct ath_softc *sc)
6591 {
6592 	struct ifnet *ifp = sc->sc_ifp;
6593 	struct ath_hal *ah = sc->sc_ah;
6594 
6595 	if_printf(ifp, "AR%s mac %d.%d RF%s phy %d.%d\n",
6596 		ath_hal_mac_name(ah), ah->ah_macVersion, ah->ah_macRev,
6597 		ath_hal_rf_name(ah), ah->ah_phyRev >> 4, ah->ah_phyRev & 0xf);
6598 	if_printf(ifp, "2GHz radio: 0x%.4x; 5GHz radio: 0x%.4x\n",
6599 		ah->ah_analog2GhzRev, ah->ah_analog5GhzRev);
6600 	if (bootverbose) {
6601 		int i;
6602 		for (i = 0; i <= WME_AC_VO; i++) {
6603 			struct ath_txq *txq = sc->sc_ac2q[i];
6604 			if_printf(ifp, "Use hw queue %u for %s traffic\n",
6605 				txq->axq_qnum, ieee80211_wme_acnames[i]);
6606 		}
6607 		if_printf(ifp, "Use hw queue %u for CAB traffic\n",
6608 			sc->sc_cabq->axq_qnum);
6609 		if_printf(ifp, "Use hw queue %u for beacons\n", sc->sc_bhalq);
6610 	}
6611 	if (ath_rxbuf != ATH_RXBUF)
6612 		if_printf(ifp, "using %u rx buffers\n", ath_rxbuf);
6613 	if (ath_txbuf != ATH_TXBUF)
6614 		if_printf(ifp, "using %u tx buffers\n", ath_txbuf);
6615 	if (sc->sc_mcastkey && bootverbose)
6616 		if_printf(ifp, "using multicast key search\n");
6617 }
6618 
6619 static void
6620 ath_dfs_tasklet(void *p, int npending)
6621 {
6622 	struct ath_softc *sc = (struct ath_softc *) p;
6623 	struct ifnet *ifp = sc->sc_ifp;
6624 	struct ieee80211com *ic = ifp->if_l2com;
6625 
6626 	/*
6627 	 * If previous processing has found a radar event,
6628 	 * signal this to the net80211 layer to begin DFS
6629 	 * processing.
6630 	 */
6631 	if (ath_dfs_process_radar_event(sc, sc->sc_curchan)) {
6632 		/* DFS event found, initiate channel change */
6633 		/*
6634 		 * XXX doesn't currently tell us whether the event
6635 		 * XXX was found in the primary or extension
6636 		 * XXX channel!
6637 		 */
6638 		IEEE80211_LOCK(ic);
6639 		ieee80211_dfs_notify_radar(ic, sc->sc_curchan);
6640 		IEEE80211_UNLOCK(ic);
6641 	}
6642 }
6643 
6644 /*
6645  * Enable/disable power save.  This must be called with
6646  * no TX driver locks currently held, so it should only
6647  * be called from the RX path (which doesn't hold any
6648  * TX driver locks.)
6649  */
6650 static void
6651 ath_node_powersave(struct ieee80211_node *ni, int enable)
6652 {
6653 #ifdef	ATH_SW_PSQ
6654 	struct ath_node *an = ATH_NODE(ni);
6655 	struct ieee80211com *ic = ni->ni_ic;
6656 	struct ath_softc *sc = ic->ic_ifp->if_softc;
6657 	struct ath_vap *avp = ATH_VAP(ni->ni_vap);
6658 
6659 	/* XXX and no TXQ locks should be held here */
6660 
6661 	DPRINTF(sc, ATH_DEBUG_NODE_PWRSAVE, "%s: %6D: enable=%d\n",
6662 	    __func__,
6663 	    ni->ni_macaddr,
6664 	    ":",
6665 	    !! enable);
6666 
6667 	/* Suspend or resume software queue handling */
6668 	if (enable)
6669 		ath_tx_node_sleep(sc, an);
6670 	else
6671 		ath_tx_node_wakeup(sc, an);
6672 
6673 	/* Update net80211 state */
6674 	avp->av_node_ps(ni, enable);
6675 #else
6676 	struct ath_vap *avp = ATH_VAP(ni->ni_vap);
6677 
6678 	/* Update net80211 state */
6679 	avp->av_node_ps(ni, enable);
6680 #endif/* ATH_SW_PSQ */
6681 }
6682 
6683 /*
6684  * Notification from net80211 that the powersave queue state has
6685  * changed.
6686  *
6687  * Since the software queue also may have some frames:
6688  *
6689  * + if the node software queue has frames and the TID state
6690  *   is 0, we set the TIM;
6691  * + if the node and the stack are both empty, we clear the TIM bit.
6692  * + If the stack tries to set the bit, always set it.
6693  * + If the stack tries to clear the bit, only clear it if the
6694  *   software queue in question is also cleared.
6695  *
6696  * TODO: this is called during node teardown; so let's ensure this
6697  * is all correctly handled and that the TIM bit is cleared.
6698  * It may be that the node flush is called _AFTER_ the net80211
6699  * stack clears the TIM.
6700  *
6701  * Here is the racy part.  Since it's possible >1 concurrent,
6702  * overlapping TXes will appear complete with a TX completion in
6703  * another thread, it's possible that the concurrent TIM calls will
6704  * clash.  We can't hold the node lock here because setting the
6705  * TIM grabs the net80211 comlock and this may cause a LOR.
6706  * The solution is either to totally serialise _everything_ at
6707  * this point (ie, all TX, completion and any reset/flush go into
6708  * one taskqueue) or a new "ath TIM lock" needs to be created that
6709  * just wraps the driver state change and this call to avp->av_set_tim().
6710  *
6711  * The same race exists in the net80211 power save queue handling
6712  * as well.  Since multiple transmitting threads may queue frames
6713  * into the driver, as well as ps-poll and the driver transmitting
6714  * frames (and thus clearing the psq), it's quite possible that
6715  * a packet entering the PSQ and a ps-poll being handled will
6716  * race, causing the TIM to be cleared and not re-set.
6717  */
6718 static int
6719 ath_node_set_tim(struct ieee80211_node *ni, int enable)
6720 {
6721 #ifdef	ATH_SW_PSQ
6722 	struct ieee80211com *ic = ni->ni_ic;
6723 	struct ath_softc *sc = ic->ic_ifp->if_softc;
6724 	struct ath_node *an = ATH_NODE(ni);
6725 	struct ath_vap *avp = ATH_VAP(ni->ni_vap);
6726 	int changed = 0;
6727 
6728 	ATH_TX_LOCK(sc);
6729 	an->an_stack_psq = enable;
6730 
6731 	/*
6732 	 * This will get called for all operating modes,
6733 	 * even if avp->av_set_tim is unset.
6734 	 * It's currently set for hostap/ibss modes; but
6735 	 * the same infrastructure is used for both STA
6736 	 * and AP/IBSS node power save.
6737 	 */
6738 	if (avp->av_set_tim == NULL) {
6739 		ATH_TX_UNLOCK(sc);
6740 		return (0);
6741 	}
6742 
6743 	/*
6744 	 * If setting the bit, always set it here.
6745 	 * If clearing the bit, only clear it if the
6746 	 * software queue is also empty.
6747 	 *
6748 	 * If the node has left power save, just clear the TIM
6749 	 * bit regardless of the state of the power save queue.
6750 	 *
6751 	 * XXX TODO: although atomics are used, it's quite possible
6752 	 * that a race will occur between this and setting/clearing
6753 	 * in another thread.  TX completion will occur always in
6754 	 * one thread, however setting/clearing the TIM bit can come
6755 	 * from a variety of different process contexts!
6756 	 */
6757 	if (enable && an->an_tim_set == 1) {
6758 		DPRINTF(sc, ATH_DEBUG_NODE_PWRSAVE,
6759 		    "%s: %6D: enable=%d, tim_set=1, ignoring\n",
6760 		    __func__,
6761 		    ni->ni_macaddr,
6762 		    ":",
6763 		    enable);
6764 		ATH_TX_UNLOCK(sc);
6765 	} else if (enable) {
6766 		DPRINTF(sc, ATH_DEBUG_NODE_PWRSAVE,
6767 		    "%s: %6D: enable=%d, enabling TIM\n",
6768 		    __func__,
6769 		    ni->ni_macaddr,
6770 		    ":",
6771 		    enable);
6772 		an->an_tim_set = 1;
6773 		ATH_TX_UNLOCK(sc);
6774 		changed = avp->av_set_tim(ni, enable);
6775 	} else if (an->an_swq_depth == 0) {
6776 		/* disable */
6777 		DPRINTF(sc, ATH_DEBUG_NODE_PWRSAVE,
6778 		    "%s: %6D: enable=%d, an_swq_depth == 0, disabling\n",
6779 		    __func__,
6780 		    ni->ni_macaddr,
6781 		    ":",
6782 		    enable);
6783 		an->an_tim_set = 0;
6784 		ATH_TX_UNLOCK(sc);
6785 		changed = avp->av_set_tim(ni, enable);
6786 	} else if (! an->an_is_powersave) {
6787 		/*
6788 		 * disable regardless; the node isn't in powersave now
6789 		 */
6790 		DPRINTF(sc, ATH_DEBUG_NODE_PWRSAVE,
6791 		    "%s: %6D: enable=%d, an_pwrsave=0, disabling\n",
6792 		    __func__,
6793 		    ni->ni_macaddr,
6794 		    ":",
6795 		    enable);
6796 		an->an_tim_set = 0;
6797 		ATH_TX_UNLOCK(sc);
6798 		changed = avp->av_set_tim(ni, enable);
6799 	} else {
6800 		/*
6801 		 * psq disable, node is currently in powersave, node
6802 		 * software queue isn't empty, so don't clear the TIM bit
6803 		 * for now.
6804 		 */
6805 		ATH_TX_UNLOCK(sc);
6806 		DPRINTF(sc, ATH_DEBUG_NODE_PWRSAVE,
6807 		    "%s: %6D: enable=%d, an_swq_depth > 0, ignoring\n",
6808 		    __func__,
6809 		    ni->ni_macaddr,
6810 		    ":",
6811 		    enable);
6812 		changed = 0;
6813 	}
6814 
6815 	return (changed);
6816 #else
6817 	struct ath_vap *avp = ATH_VAP(ni->ni_vap);
6818 
6819 	/*
6820 	 * Some operating modes don't set av_set_tim(), so don't
6821 	 * update it here.
6822 	 */
6823 	if (avp->av_set_tim == NULL)
6824 		return (0);
6825 
6826 	return (avp->av_set_tim(ni, enable));
6827 #endif /* ATH_SW_PSQ */
6828 }
6829 
6830 /*
6831  * Set or update the TIM from the software queue.
6832  *
6833  * Check the software queue depth before attempting to do lock
6834  * anything; that avoids trying to obtain the lock.  Then,
6835  * re-check afterwards to ensure nothing has changed in the
6836  * meantime.
6837  *
6838  * set:   This is designed to be called from the TX path, after
6839  *        a frame has been queued; to see if the swq > 0.
6840  *
6841  * clear: This is designed to be called from the buffer completion point
6842  *        (right now it's ath_tx_default_comp()) where the state of
6843  *        a software queue has changed.
6844  *
6845  * It makes sense to place it at buffer free / completion rather
6846  * than after each software queue operation, as there's no real
6847  * point in churning the TIM bit as the last frames in the software
6848  * queue are transmitted.  If they fail and we retry them, we'd
6849  * just be setting the TIM bit again anyway.
6850  */
6851 void
6852 ath_tx_update_tim(struct ath_softc *sc, struct ieee80211_node *ni,
6853      int enable)
6854 {
6855 #ifdef	ATH_SW_PSQ
6856 	struct ath_node *an;
6857 	struct ath_vap *avp;
6858 
6859 	/* Don't do this for broadcast/etc frames */
6860 	if (ni == NULL)
6861 		return;
6862 
6863 	an = ATH_NODE(ni);
6864 	avp = ATH_VAP(ni->ni_vap);
6865 
6866 	/*
6867 	 * And for operating modes without the TIM handler set, let's
6868 	 * just skip those.
6869 	 */
6870 	if (avp->av_set_tim == NULL)
6871 		return;
6872 
6873 	ATH_TX_LOCK_ASSERT(sc);
6874 
6875 	if (enable) {
6876 		if (an->an_is_powersave &&
6877 		    an->an_tim_set == 0 &&
6878 		    an->an_swq_depth != 0) {
6879 			DPRINTF(sc, ATH_DEBUG_NODE_PWRSAVE,
6880 			    "%s: %6D: swq_depth>0, tim_set=0, set!\n",
6881 			    __func__,
6882 			    ni->ni_macaddr,
6883 			    ":");
6884 			an->an_tim_set = 1;
6885 			(void) avp->av_set_tim(ni, 1);
6886 		}
6887 	} else {
6888 		/*
6889 		 * Don't bother grabbing the lock unless the queue is empty.
6890 		 */
6891 		if (&an->an_swq_depth != 0)
6892 			return;
6893 
6894 		if (an->an_is_powersave &&
6895 		    an->an_stack_psq == 0 &&
6896 		    an->an_tim_set == 1 &&
6897 		    an->an_swq_depth == 0) {
6898 			DPRINTF(sc, ATH_DEBUG_NODE_PWRSAVE,
6899 			    "%s: %6D: swq_depth=0, tim_set=1, psq_set=0,"
6900 			    " clear!\n",
6901 			    __func__,
6902 			    ni->ni_macaddr,
6903 			    ":");
6904 			an->an_tim_set = 0;
6905 			(void) avp->av_set_tim(ni, 0);
6906 		}
6907 	}
6908 #else
6909 	return;
6910 #endif	/* ATH_SW_PSQ */
6911 }
6912 
6913 /*
6914  * Received a ps-poll frame from net80211.
6915  *
6916  * Here we get a chance to serve out a software-queued frame ourselves
6917  * before we punt it to net80211 to transmit us one itself - either
6918  * because there's traffic in the net80211 psq, or a NULL frame to
6919  * indicate there's nothing else.
6920  */
6921 static void
6922 ath_node_recv_pspoll(struct ieee80211_node *ni, struct mbuf *m)
6923 {
6924 #ifdef	ATH_SW_PSQ
6925 	struct ath_node *an;
6926 	struct ath_vap *avp;
6927 	struct ieee80211com *ic = ni->ni_ic;
6928 	struct ath_softc *sc = ic->ic_ifp->if_softc;
6929 	int tid;
6930 
6931 	/* Just paranoia */
6932 	if (ni == NULL)
6933 		return;
6934 
6935 	/*
6936 	 * Unassociated (temporary node) station.
6937 	 */
6938 	if (ni->ni_associd == 0)
6939 		return;
6940 
6941 	/*
6942 	 * We do have an active node, so let's begin looking into it.
6943 	 */
6944 	an = ATH_NODE(ni);
6945 	avp = ATH_VAP(ni->ni_vap);
6946 
6947 	/*
6948 	 * For now, we just call the original ps-poll method.
6949 	 * Once we're ready to flip this on:
6950 	 *
6951 	 * + Set leak to 1, as no matter what we're going to have
6952 	 *   to send a frame;
6953 	 * + Check the software queue and if there's something in it,
6954 	 *   schedule the highest TID thas has traffic from this node.
6955 	 *   Then make sure we schedule the software scheduler to
6956 	 *   run so it picks up said frame.
6957 	 *
6958 	 * That way whatever happens, we'll at least send _a_ frame
6959 	 * to the given node.
6960 	 *
6961 	 * Again, yes, it's crappy QoS if the node has multiple
6962 	 * TIDs worth of traffic - but let's get it working first
6963 	 * before we optimise it.
6964 	 *
6965 	 * Also yes, there's definitely latency here - we're not
6966 	 * direct dispatching to the hardware in this path (and
6967 	 * we're likely being called from the packet receive path,
6968 	 * so going back into TX may be a little hairy!) but again
6969 	 * I'd like to get this working first before optimising
6970 	 * turn-around time.
6971 	 */
6972 
6973 	ATH_TX_LOCK(sc);
6974 
6975 	/*
6976 	 * Legacy - we're called and the node isn't asleep.
6977 	 * Immediately punt.
6978 	 */
6979 	if (! an->an_is_powersave) {
6980 		DPRINTF(sc, ATH_DEBUG_NODE_PWRSAVE,
6981 		    "%s: %6D: not in powersave?\n",
6982 		    __func__,
6983 		    ni->ni_macaddr,
6984 		    ":");
6985 		ATH_TX_UNLOCK(sc);
6986 		avp->av_recv_pspoll(ni, m);
6987 		return;
6988 	}
6989 
6990 	/*
6991 	 * We're in powersave.
6992 	 *
6993 	 * Leak a frame.
6994 	 */
6995 	an->an_leak_count = 1;
6996 
6997 	/*
6998 	 * Now, if there's no frames in the node, just punt to
6999 	 * recv_pspoll.
7000 	 *
7001 	 * Don't bother checking if the TIM bit is set, we really
7002 	 * only care if there are any frames here!
7003 	 */
7004 	if (an->an_swq_depth == 0) {
7005 		ATH_TX_UNLOCK(sc);
7006 		DPRINTF(sc, ATH_DEBUG_NODE_PWRSAVE,
7007 		    "%s: %6D: SWQ empty; punting to net80211\n",
7008 		    __func__,
7009 		    ni->ni_macaddr,
7010 		    ":");
7011 		avp->av_recv_pspoll(ni, m);
7012 		return;
7013 	}
7014 
7015 	/*
7016 	 * Ok, let's schedule the highest TID that has traffic
7017 	 * and then schedule something.
7018 	 */
7019 	for (tid = IEEE80211_TID_SIZE - 1; tid >= 0; tid--) {
7020 		struct ath_tid *atid = &an->an_tid[tid];
7021 		/*
7022 		 * No frames? Skip.
7023 		 */
7024 		if (atid->axq_depth == 0)
7025 			continue;
7026 		ath_tx_tid_sched(sc, atid);
7027 		/*
7028 		 * XXX we could do a direct call to the TXQ
7029 		 * scheduler code here to optimise latency
7030 		 * at the expense of a REALLY deep callstack.
7031 		 */
7032 		ATH_TX_UNLOCK(sc);
7033 		taskqueue_enqueue(sc->sc_tq, &sc->sc_txqtask);
7034 		DPRINTF(sc, ATH_DEBUG_NODE_PWRSAVE,
7035 		    "%s: %6D: leaking frame to TID %d\n",
7036 		    __func__,
7037 		    ni->ni_macaddr,
7038 		    ":",
7039 		    tid);
7040 		return;
7041 	}
7042 
7043 	ATH_TX_UNLOCK(sc);
7044 
7045 	/*
7046 	 * XXX nothing in the TIDs at this point? Eek.
7047 	 */
7048 	DPRINTF(sc, ATH_DEBUG_NODE_PWRSAVE,
7049 	    "%s: %6D: TIDs empty, but ath_node showed traffic?!\n",
7050 	    __func__,
7051 	    ni->ni_macaddr,
7052 	    ":");
7053 	avp->av_recv_pspoll(ni, m);
7054 #else
7055 	avp->av_recv_pspoll(ni, m);
7056 #endif	/* ATH_SW_PSQ */
7057 }
7058 
7059 MODULE_VERSION(if_ath, 1);
7060 MODULE_DEPEND(if_ath, wlan, 1, 1, 1);          /* 802.11 media layer */
7061 #if	defined(IEEE80211_ALQ) || defined(AH_DEBUG_ALQ)
7062 MODULE_DEPEND(if_ath, alq, 1, 1, 1);
7063 #endif
7064