xref: /freebsd/sys/dev/ath/if_ath.c (revision 3d184db2f82e0bfab9e52a155be9d3eb8c71382a)
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_dl.h>
77 #include <net/if_media.h>
78 #include <net/if_types.h>
79 #include <net/if_arp.h>
80 #include <net/ethernet.h>
81 #include <net/if_llc.h>
82 
83 #include <net80211/ieee80211_var.h>
84 #include <net80211/ieee80211_regdomain.h>
85 #ifdef IEEE80211_SUPPORT_SUPERG
86 #include <net80211/ieee80211_superg.h>
87 #endif
88 #ifdef IEEE80211_SUPPORT_TDMA
89 #include <net80211/ieee80211_tdma.h>
90 #endif
91 
92 #include <net/bpf.h>
93 
94 #ifdef INET
95 #include <netinet/in.h>
96 #include <netinet/if_ether.h>
97 #endif
98 
99 #include <dev/ath/if_athvar.h>
100 #include <dev/ath/ath_hal/ah_devid.h>		/* XXX for softled */
101 #include <dev/ath/ath_hal/ah_diagcodes.h>
102 
103 #include <dev/ath/if_ath_debug.h>
104 #include <dev/ath/if_ath_misc.h>
105 #include <dev/ath/if_ath_tsf.h>
106 #include <dev/ath/if_ath_tx.h>
107 #include <dev/ath/if_ath_sysctl.h>
108 #include <dev/ath/if_ath_led.h>
109 #include <dev/ath/if_ath_keycache.h>
110 #include <dev/ath/if_ath_rx.h>
111 #include <dev/ath/if_ath_rx_edma.h>
112 #include <dev/ath/if_ath_beacon.h>
113 #include <dev/ath/if_athdfs.h>
114 
115 #ifdef ATH_TX99_DIAG
116 #include <dev/ath/ath_tx99/ath_tx99.h>
117 #endif
118 
119 #define	ATH_KTR_INTR	KTR_SPARE4
120 #define	ATH_KTR_ERR	KTR_SPARE3
121 
122 /*
123  * ATH_BCBUF determines the number of vap's that can transmit
124  * beacons and also (currently) the number of vap's that can
125  * have unique mac addresses/bssid.  When staggering beacons
126  * 4 is probably a good max as otherwise the beacons become
127  * very closely spaced and there is limited time for cab q traffic
128  * to go out.  You can burst beacons instead but that is not good
129  * for stations in power save and at some point you really want
130  * another radio (and channel).
131  *
132  * The limit on the number of mac addresses is tied to our use of
133  * the U/L bit and tracking addresses in a byte; it would be
134  * worthwhile to allow more for applications like proxy sta.
135  */
136 CTASSERT(ATH_BCBUF <= 8);
137 
138 static struct ieee80211vap *ath_vap_create(struct ieee80211com *,
139 		    const char [IFNAMSIZ], int, enum ieee80211_opmode, int,
140 		    const uint8_t [IEEE80211_ADDR_LEN],
141 		    const uint8_t [IEEE80211_ADDR_LEN]);
142 static void	ath_vap_delete(struct ieee80211vap *);
143 static void	ath_init(void *);
144 static void	ath_stop_locked(struct ifnet *);
145 static void	ath_stop(struct ifnet *);
146 static int	ath_reset_vap(struct ieee80211vap *, u_long);
147 static int	ath_media_change(struct ifnet *);
148 static void	ath_watchdog(void *);
149 static int	ath_ioctl(struct ifnet *, u_long, caddr_t);
150 static void	ath_fatal_proc(void *, int);
151 static void	ath_bmiss_vap(struct ieee80211vap *);
152 static void	ath_bmiss_proc(void *, int);
153 static void	ath_key_update_begin(struct ieee80211vap *);
154 static void	ath_key_update_end(struct ieee80211vap *);
155 static void	ath_update_mcast(struct ifnet *);
156 static void	ath_update_promisc(struct ifnet *);
157 static void	ath_updateslot(struct ifnet *);
158 static void	ath_bstuck_proc(void *, int);
159 static void	ath_reset_proc(void *, int);
160 static int	ath_desc_alloc(struct ath_softc *);
161 static void	ath_desc_free(struct ath_softc *);
162 static struct ieee80211_node *ath_node_alloc(struct ieee80211vap *,
163 			const uint8_t [IEEE80211_ADDR_LEN]);
164 static void	ath_node_cleanup(struct ieee80211_node *);
165 static void	ath_node_free(struct ieee80211_node *);
166 static void	ath_node_getsignal(const struct ieee80211_node *,
167 			int8_t *, int8_t *);
168 static void	ath_txq_init(struct ath_softc *sc, struct ath_txq *, int);
169 static struct ath_txq *ath_txq_setup(struct ath_softc*, int qtype, int subtype);
170 static int	ath_tx_setup(struct ath_softc *, int, int);
171 static void	ath_tx_cleanupq(struct ath_softc *, struct ath_txq *);
172 static void	ath_tx_cleanup(struct ath_softc *);
173 static void	ath_tx_proc_q0(void *, int);
174 static void	ath_tx_proc_q0123(void *, int);
175 static void	ath_tx_proc(void *, int);
176 static void	ath_txq_sched_tasklet(void *, int);
177 static int	ath_chan_set(struct ath_softc *, struct ieee80211_channel *);
178 static void	ath_draintxq(struct ath_softc *, ATH_RESET_TYPE reset_type);
179 static void	ath_chan_change(struct ath_softc *, struct ieee80211_channel *);
180 static void	ath_scan_start(struct ieee80211com *);
181 static void	ath_scan_end(struct ieee80211com *);
182 static void	ath_set_channel(struct ieee80211com *);
183 #ifdef	ATH_ENABLE_11N
184 static void	ath_update_chw(struct ieee80211com *);
185 #endif	/* ATH_ENABLE_11N */
186 static void	ath_calibrate(void *);
187 static int	ath_newstate(struct ieee80211vap *, enum ieee80211_state, int);
188 static void	ath_setup_stationkey(struct ieee80211_node *);
189 static void	ath_newassoc(struct ieee80211_node *, int);
190 static int	ath_setregdomain(struct ieee80211com *,
191 		    struct ieee80211_regdomain *, int,
192 		    struct ieee80211_channel []);
193 static void	ath_getradiocaps(struct ieee80211com *, int, int *,
194 		    struct ieee80211_channel []);
195 static int	ath_getchannels(struct ath_softc *);
196 
197 static int	ath_rate_setup(struct ath_softc *, u_int mode);
198 static void	ath_setcurmode(struct ath_softc *, enum ieee80211_phymode);
199 
200 static void	ath_announce(struct ath_softc *);
201 
202 static void	ath_dfs_tasklet(void *, int);
203 
204 #ifdef IEEE80211_SUPPORT_TDMA
205 #include <dev/ath/if_ath_tdma.h>
206 #endif
207 
208 #if 0
209 #define	TDMA_EP_MULTIPLIER	(1<<10) /* pow2 to optimize out * and / */
210 #define	TDMA_LPF_LEN		6
211 #define	TDMA_DUMMY_MARKER	0x127
212 #define	TDMA_EP_MUL(x, mul)	((x) * (mul))
213 #define	TDMA_IN(x)		(TDMA_EP_MUL((x), TDMA_EP_MULTIPLIER))
214 #define	TDMA_LPF(x, y, len) \
215     ((x != TDMA_DUMMY_MARKER) ? (((x) * ((len)-1) + (y)) / (len)) : (y))
216 #define	TDMA_SAMPLE(x, y) do {					\
217 	x = TDMA_LPF((x), TDMA_IN(y), TDMA_LPF_LEN);		\
218 } while (0)
219 #define	TDMA_EP_RND(x,mul) \
220 	((((x)%(mul)) >= ((mul)/2)) ? ((x) + ((mul) - 1)) / (mul) : (x)/(mul))
221 #define	TDMA_AVG(x)		TDMA_EP_RND(x, TDMA_EP_MULTIPLIER)
222 #endif /* IEEE80211_SUPPORT_TDMA */
223 
224 SYSCTL_DECL(_hw_ath);
225 
226 /* XXX validate sysctl values */
227 static	int ath_longcalinterval = 30;		/* long cals every 30 secs */
228 SYSCTL_INT(_hw_ath, OID_AUTO, longcal, CTLFLAG_RW, &ath_longcalinterval,
229 	    0, "long chip calibration interval (secs)");
230 static	int ath_shortcalinterval = 100;		/* short cals every 100 ms */
231 SYSCTL_INT(_hw_ath, OID_AUTO, shortcal, CTLFLAG_RW, &ath_shortcalinterval,
232 	    0, "short chip calibration interval (msecs)");
233 static	int ath_resetcalinterval = 20*60;	/* reset cal state 20 mins */
234 SYSCTL_INT(_hw_ath, OID_AUTO, resetcal, CTLFLAG_RW, &ath_resetcalinterval,
235 	    0, "reset chip calibration results (secs)");
236 static	int ath_anicalinterval = 100;		/* ANI calibration - 100 msec */
237 SYSCTL_INT(_hw_ath, OID_AUTO, anical, CTLFLAG_RW, &ath_anicalinterval,
238 	    0, "ANI calibration (msecs)");
239 
240 int ath_rxbuf = ATH_RXBUF;		/* # rx buffers to allocate */
241 SYSCTL_INT(_hw_ath, OID_AUTO, rxbuf, CTLFLAG_RW, &ath_rxbuf,
242 	    0, "rx buffers allocated");
243 TUNABLE_INT("hw.ath.rxbuf", &ath_rxbuf);
244 int ath_txbuf = ATH_TXBUF;		/* # tx buffers to allocate */
245 SYSCTL_INT(_hw_ath, OID_AUTO, txbuf, CTLFLAG_RW, &ath_txbuf,
246 	    0, "tx buffers allocated");
247 TUNABLE_INT("hw.ath.txbuf", &ath_txbuf);
248 int ath_txbuf_mgmt = ATH_MGMT_TXBUF;	/* # mgmt tx buffers to allocate */
249 SYSCTL_INT(_hw_ath, OID_AUTO, txbuf_mgmt, CTLFLAG_RW, &ath_txbuf_mgmt,
250 	    0, "tx (mgmt) buffers allocated");
251 TUNABLE_INT("hw.ath.txbuf_mgmt", &ath_txbuf_mgmt);
252 
253 int ath_bstuck_threshold = 4;		/* max missed beacons */
254 SYSCTL_INT(_hw_ath, OID_AUTO, bstuck, CTLFLAG_RW, &ath_bstuck_threshold,
255 	    0, "max missed beacon xmits before chip reset");
256 
257 MALLOC_DEFINE(M_ATHDEV, "athdev", "ath driver dma buffers");
258 
259 #define	HAL_MODE_HT20 (HAL_MODE_11NG_HT20 | HAL_MODE_11NA_HT20)
260 #define	HAL_MODE_HT40 \
261 	(HAL_MODE_11NG_HT40PLUS | HAL_MODE_11NG_HT40MINUS | \
262 	HAL_MODE_11NA_HT40PLUS | HAL_MODE_11NA_HT40MINUS)
263 int
264 ath_attach(u_int16_t devid, struct ath_softc *sc)
265 {
266 	struct ifnet *ifp;
267 	struct ieee80211com *ic;
268 	struct ath_hal *ah = NULL;
269 	HAL_STATUS status;
270 	int error = 0, i;
271 	u_int wmodes;
272 	uint8_t macaddr[IEEE80211_ADDR_LEN];
273 	int rx_chainmask, tx_chainmask;
274 
275 	DPRINTF(sc, ATH_DEBUG_ANY, "%s: devid 0x%x\n", __func__, devid);
276 
277 	ifp = sc->sc_ifp = if_alloc(IFT_IEEE80211);
278 	if (ifp == NULL) {
279 		device_printf(sc->sc_dev, "can not if_alloc()\n");
280 		error = ENOSPC;
281 		goto bad;
282 	}
283 	ic = ifp->if_l2com;
284 
285 	/* set these up early for if_printf use */
286 	if_initname(ifp, device_get_name(sc->sc_dev),
287 		device_get_unit(sc->sc_dev));
288 
289 	ah = ath_hal_attach(devid, sc, sc->sc_st, sc->sc_sh,
290 	    sc->sc_eepromdata, &status);
291 	if (ah == NULL) {
292 		if_printf(ifp, "unable to attach hardware; HAL status %u\n",
293 			status);
294 		error = ENXIO;
295 		goto bad;
296 	}
297 	sc->sc_ah = ah;
298 	sc->sc_invalid = 0;	/* ready to go, enable interrupt handling */
299 #ifdef	ATH_DEBUG
300 	sc->sc_debug = ath_debug;
301 #endif
302 
303 	/*
304 	 * Setup the DMA/EDMA functions based on the current
305 	 * hardware support.
306 	 *
307 	 * This is required before the descriptors are allocated.
308 	 */
309 	if (ath_hal_hasedma(sc->sc_ah)) {
310 		sc->sc_isedma = 1;
311 		ath_recv_setup_edma(sc);
312 	} else
313 		ath_recv_setup_legacy(sc);
314 
315 	/*
316 	 * Check if the MAC has multi-rate retry support.
317 	 * We do this by trying to setup a fake extended
318 	 * descriptor.  MAC's that don't have support will
319 	 * return false w/o doing anything.  MAC's that do
320 	 * support it will return true w/o doing anything.
321 	 */
322 	sc->sc_mrretry = ath_hal_setupxtxdesc(ah, NULL, 0,0, 0,0, 0,0);
323 
324 	/*
325 	 * Check if the device has hardware counters for PHY
326 	 * errors.  If so we need to enable the MIB interrupt
327 	 * so we can act on stat triggers.
328 	 */
329 	if (ath_hal_hwphycounters(ah))
330 		sc->sc_needmib = 1;
331 
332 	/*
333 	 * Get the hardware key cache size.
334 	 */
335 	sc->sc_keymax = ath_hal_keycachesize(ah);
336 	if (sc->sc_keymax > ATH_KEYMAX) {
337 		if_printf(ifp, "Warning, using only %u of %u key cache slots\n",
338 			ATH_KEYMAX, sc->sc_keymax);
339 		sc->sc_keymax = ATH_KEYMAX;
340 	}
341 	/*
342 	 * Reset the key cache since some parts do not
343 	 * reset the contents on initial power up.
344 	 */
345 	for (i = 0; i < sc->sc_keymax; i++)
346 		ath_hal_keyreset(ah, i);
347 
348 	/*
349 	 * Collect the default channel list.
350 	 */
351 	error = ath_getchannels(sc);
352 	if (error != 0)
353 		goto bad;
354 
355 	/*
356 	 * Setup rate tables for all potential media types.
357 	 */
358 	ath_rate_setup(sc, IEEE80211_MODE_11A);
359 	ath_rate_setup(sc, IEEE80211_MODE_11B);
360 	ath_rate_setup(sc, IEEE80211_MODE_11G);
361 	ath_rate_setup(sc, IEEE80211_MODE_TURBO_A);
362 	ath_rate_setup(sc, IEEE80211_MODE_TURBO_G);
363 	ath_rate_setup(sc, IEEE80211_MODE_STURBO_A);
364 	ath_rate_setup(sc, IEEE80211_MODE_11NA);
365 	ath_rate_setup(sc, IEEE80211_MODE_11NG);
366 	ath_rate_setup(sc, IEEE80211_MODE_HALF);
367 	ath_rate_setup(sc, IEEE80211_MODE_QUARTER);
368 
369 	/* NB: setup here so ath_rate_update is happy */
370 	ath_setcurmode(sc, IEEE80211_MODE_11A);
371 
372 	/*
373 	 * Allocate tx+rx descriptors and populate the lists.
374 	 */
375 	error = ath_desc_alloc(sc);
376 	if (error != 0) {
377 		if_printf(ifp, "failed to allocate descriptors: %d\n", error);
378 		goto bad;
379 	}
380 
381 	error = ath_rxdma_setup(sc);
382 	if (error != 0) {
383 		if_printf(ifp, "failed to allocate RX descriptors: %d\n",
384 		    error);
385 		goto bad;
386 	}
387 
388 	callout_init_mtx(&sc->sc_cal_ch, &sc->sc_mtx, 0);
389 	callout_init_mtx(&sc->sc_wd_ch, &sc->sc_mtx, 0);
390 
391 	ATH_TXBUF_LOCK_INIT(sc);
392 
393 	sc->sc_tq = taskqueue_create("ath_taskq", M_NOWAIT,
394 		taskqueue_thread_enqueue, &sc->sc_tq);
395 	taskqueue_start_threads(&sc->sc_tq, 1, PI_NET,
396 		"%s taskq", ifp->if_xname);
397 
398 	TASK_INIT(&sc->sc_rxtask, 0, sc->sc_rx.recv_tasklet, sc);
399 	TASK_INIT(&sc->sc_bmisstask, 0, ath_bmiss_proc, sc);
400 	TASK_INIT(&sc->sc_bstucktask,0, ath_bstuck_proc, sc);
401 	TASK_INIT(&sc->sc_resettask,0, ath_reset_proc, sc);
402 	TASK_INIT(&sc->sc_txqtask,0, ath_txq_sched_tasklet, sc);
403 	TASK_INIT(&sc->sc_fataltask,0, ath_fatal_proc, sc);
404 
405 	/*
406 	 * Allocate hardware transmit queues: one queue for
407 	 * beacon frames and one data queue for each QoS
408 	 * priority.  Note that the hal handles resetting
409 	 * these queues at the needed time.
410 	 *
411 	 * XXX PS-Poll
412 	 */
413 	sc->sc_bhalq = ath_beaconq_setup(ah);
414 	if (sc->sc_bhalq == (u_int) -1) {
415 		if_printf(ifp, "unable to setup a beacon xmit queue!\n");
416 		error = EIO;
417 		goto bad2;
418 	}
419 	sc->sc_cabq = ath_txq_setup(sc, HAL_TX_QUEUE_CAB, 0);
420 	if (sc->sc_cabq == NULL) {
421 		if_printf(ifp, "unable to setup CAB xmit queue!\n");
422 		error = EIO;
423 		goto bad2;
424 	}
425 	/* NB: insure BK queue is the lowest priority h/w queue */
426 	if (!ath_tx_setup(sc, WME_AC_BK, HAL_WME_AC_BK)) {
427 		if_printf(ifp, "unable to setup xmit queue for %s traffic!\n",
428 			ieee80211_wme_acnames[WME_AC_BK]);
429 		error = EIO;
430 		goto bad2;
431 	}
432 	if (!ath_tx_setup(sc, WME_AC_BE, HAL_WME_AC_BE) ||
433 	    !ath_tx_setup(sc, WME_AC_VI, HAL_WME_AC_VI) ||
434 	    !ath_tx_setup(sc, WME_AC_VO, HAL_WME_AC_VO)) {
435 		/*
436 		 * Not enough hardware tx queues to properly do WME;
437 		 * just punt and assign them all to the same h/w queue.
438 		 * We could do a better job of this if, for example,
439 		 * we allocate queues when we switch from station to
440 		 * AP mode.
441 		 */
442 		if (sc->sc_ac2q[WME_AC_VI] != NULL)
443 			ath_tx_cleanupq(sc, sc->sc_ac2q[WME_AC_VI]);
444 		if (sc->sc_ac2q[WME_AC_BE] != NULL)
445 			ath_tx_cleanupq(sc, sc->sc_ac2q[WME_AC_BE]);
446 		sc->sc_ac2q[WME_AC_BE] = sc->sc_ac2q[WME_AC_BK];
447 		sc->sc_ac2q[WME_AC_VI] = sc->sc_ac2q[WME_AC_BK];
448 		sc->sc_ac2q[WME_AC_VO] = sc->sc_ac2q[WME_AC_BK];
449 	}
450 
451 	/*
452 	 * Special case certain configurations.  Note the
453 	 * CAB queue is handled by these specially so don't
454 	 * include them when checking the txq setup mask.
455 	 */
456 	switch (sc->sc_txqsetup &~ (1<<sc->sc_cabq->axq_qnum)) {
457 	case 0x01:
458 		TASK_INIT(&sc->sc_txtask, 0, ath_tx_proc_q0, sc);
459 		break;
460 	case 0x0f:
461 		TASK_INIT(&sc->sc_txtask, 0, ath_tx_proc_q0123, sc);
462 		break;
463 	default:
464 		TASK_INIT(&sc->sc_txtask, 0, ath_tx_proc, sc);
465 		break;
466 	}
467 
468 	/*
469 	 * Setup rate control.  Some rate control modules
470 	 * call back to change the anntena state so expose
471 	 * the necessary entry points.
472 	 * XXX maybe belongs in struct ath_ratectrl?
473 	 */
474 	sc->sc_setdefantenna = ath_setdefantenna;
475 	sc->sc_rc = ath_rate_attach(sc);
476 	if (sc->sc_rc == NULL) {
477 		error = EIO;
478 		goto bad2;
479 	}
480 
481 	/* Attach DFS module */
482 	if (! ath_dfs_attach(sc)) {
483 		device_printf(sc->sc_dev,
484 		    "%s: unable to attach DFS\n", __func__);
485 		error = EIO;
486 		goto bad2;
487 	}
488 
489 	/* Start DFS processing tasklet */
490 	TASK_INIT(&sc->sc_dfstask, 0, ath_dfs_tasklet, sc);
491 
492 	/* Configure LED state */
493 	sc->sc_blinking = 0;
494 	sc->sc_ledstate = 1;
495 	sc->sc_ledon = 0;			/* low true */
496 	sc->sc_ledidle = (2700*hz)/1000;	/* 2.7sec */
497 	callout_init(&sc->sc_ledtimer, CALLOUT_MPSAFE);
498 
499 	/*
500 	 * Don't setup hardware-based blinking.
501 	 *
502 	 * Although some NICs may have this configured in the
503 	 * default reset register values, the user may wish
504 	 * to alter which pins have which function.
505 	 *
506 	 * The reference driver attaches the MAC network LED to GPIO1 and
507 	 * the MAC power LED to GPIO2.  However, the DWA-552 cardbus
508 	 * NIC has these reversed.
509 	 */
510 	sc->sc_hardled = (1 == 0);
511 	sc->sc_led_net_pin = -1;
512 	sc->sc_led_pwr_pin = -1;
513 	/*
514 	 * Auto-enable soft led processing for IBM cards and for
515 	 * 5211 minipci cards.  Users can also manually enable/disable
516 	 * support with a sysctl.
517 	 */
518 	sc->sc_softled = (devid == AR5212_DEVID_IBM || devid == AR5211_DEVID);
519 	ath_led_config(sc);
520 	ath_hal_setledstate(ah, HAL_LED_INIT);
521 
522 	ifp->if_softc = sc;
523 	ifp->if_flags = IFF_SIMPLEX | IFF_BROADCAST | IFF_MULTICAST;
524 	ifp->if_start = ath_start;
525 	ifp->if_ioctl = ath_ioctl;
526 	ifp->if_init = ath_init;
527 	IFQ_SET_MAXLEN(&ifp->if_snd, ifqmaxlen);
528 	ifp->if_snd.ifq_drv_maxlen = ifqmaxlen;
529 	IFQ_SET_READY(&ifp->if_snd);
530 
531 	ic->ic_ifp = ifp;
532 	/* XXX not right but it's not used anywhere important */
533 	ic->ic_phytype = IEEE80211_T_OFDM;
534 	ic->ic_opmode = IEEE80211_M_STA;
535 	ic->ic_caps =
536 		  IEEE80211_C_STA		/* station mode */
537 		| IEEE80211_C_IBSS		/* ibss, nee adhoc, mode */
538 		| IEEE80211_C_HOSTAP		/* hostap mode */
539 		| IEEE80211_C_MONITOR		/* monitor mode */
540 		| IEEE80211_C_AHDEMO		/* adhoc demo mode */
541 		| IEEE80211_C_WDS		/* 4-address traffic works */
542 		| IEEE80211_C_MBSS		/* mesh point link mode */
543 		| IEEE80211_C_SHPREAMBLE	/* short preamble supported */
544 		| IEEE80211_C_SHSLOT		/* short slot time supported */
545 		| IEEE80211_C_WPA		/* capable of WPA1+WPA2 */
546 #ifndef	ATH_ENABLE_11N
547 		| IEEE80211_C_BGSCAN		/* capable of bg scanning */
548 #endif
549 		| IEEE80211_C_TXFRAG		/* handle tx frags */
550 #ifdef	ATH_ENABLE_DFS
551 		| IEEE80211_C_DFS		/* Enable radar detection */
552 #endif
553 		;
554 	/*
555 	 * Query the hal to figure out h/w crypto support.
556 	 */
557 	if (ath_hal_ciphersupported(ah, HAL_CIPHER_WEP))
558 		ic->ic_cryptocaps |= IEEE80211_CRYPTO_WEP;
559 	if (ath_hal_ciphersupported(ah, HAL_CIPHER_AES_OCB))
560 		ic->ic_cryptocaps |= IEEE80211_CRYPTO_AES_OCB;
561 	if (ath_hal_ciphersupported(ah, HAL_CIPHER_AES_CCM))
562 		ic->ic_cryptocaps |= IEEE80211_CRYPTO_AES_CCM;
563 	if (ath_hal_ciphersupported(ah, HAL_CIPHER_CKIP))
564 		ic->ic_cryptocaps |= IEEE80211_CRYPTO_CKIP;
565 	if (ath_hal_ciphersupported(ah, HAL_CIPHER_TKIP)) {
566 		ic->ic_cryptocaps |= IEEE80211_CRYPTO_TKIP;
567 		/*
568 		 * Check if h/w does the MIC and/or whether the
569 		 * separate key cache entries are required to
570 		 * handle both tx+rx MIC keys.
571 		 */
572 		if (ath_hal_ciphersupported(ah, HAL_CIPHER_MIC))
573 			ic->ic_cryptocaps |= IEEE80211_CRYPTO_TKIPMIC;
574 		/*
575 		 * If the h/w supports storing tx+rx MIC keys
576 		 * in one cache slot automatically enable use.
577 		 */
578 		if (ath_hal_hastkipsplit(ah) ||
579 		    !ath_hal_settkipsplit(ah, AH_FALSE))
580 			sc->sc_splitmic = 1;
581 		/*
582 		 * If the h/w can do TKIP MIC together with WME then
583 		 * we use it; otherwise we force the MIC to be done
584 		 * in software by the net80211 layer.
585 		 */
586 		if (ath_hal_haswmetkipmic(ah))
587 			sc->sc_wmetkipmic = 1;
588 	}
589 	sc->sc_hasclrkey = ath_hal_ciphersupported(ah, HAL_CIPHER_CLR);
590 	/*
591 	 * Check for multicast key search support.
592 	 */
593 	if (ath_hal_hasmcastkeysearch(sc->sc_ah) &&
594 	    !ath_hal_getmcastkeysearch(sc->sc_ah)) {
595 		ath_hal_setmcastkeysearch(sc->sc_ah, 1);
596 	}
597 	sc->sc_mcastkey = ath_hal_getmcastkeysearch(ah);
598 	/*
599 	 * Mark key cache slots associated with global keys
600 	 * as in use.  If we knew TKIP was not to be used we
601 	 * could leave the +32, +64, and +32+64 slots free.
602 	 */
603 	for (i = 0; i < IEEE80211_WEP_NKID; i++) {
604 		setbit(sc->sc_keymap, i);
605 		setbit(sc->sc_keymap, i+64);
606 		if (sc->sc_splitmic) {
607 			setbit(sc->sc_keymap, i+32);
608 			setbit(sc->sc_keymap, i+32+64);
609 		}
610 	}
611 	/*
612 	 * TPC support can be done either with a global cap or
613 	 * per-packet support.  The latter is not available on
614 	 * all parts.  We're a bit pedantic here as all parts
615 	 * support a global cap.
616 	 */
617 	if (ath_hal_hastpc(ah) || ath_hal_hastxpowlimit(ah))
618 		ic->ic_caps |= IEEE80211_C_TXPMGT;
619 
620 	/*
621 	 * Mark WME capability only if we have sufficient
622 	 * hardware queues to do proper priority scheduling.
623 	 */
624 	if (sc->sc_ac2q[WME_AC_BE] != sc->sc_ac2q[WME_AC_BK])
625 		ic->ic_caps |= IEEE80211_C_WME;
626 	/*
627 	 * Check for misc other capabilities.
628 	 */
629 	if (ath_hal_hasbursting(ah))
630 		ic->ic_caps |= IEEE80211_C_BURST;
631 	sc->sc_hasbmask = ath_hal_hasbssidmask(ah);
632 	sc->sc_hasbmatch = ath_hal_hasbssidmatch(ah);
633 	sc->sc_hastsfadd = ath_hal_hastsfadjust(ah);
634 	sc->sc_rxslink = ath_hal_self_linked_final_rxdesc(ah);
635 	sc->sc_rxtsf32 = ath_hal_has_long_rxdesc_tsf(ah);
636 	if (ath_hal_hasfastframes(ah))
637 		ic->ic_caps |= IEEE80211_C_FF;
638 	wmodes = ath_hal_getwirelessmodes(ah);
639 	if (wmodes & (HAL_MODE_108G|HAL_MODE_TURBO))
640 		ic->ic_caps |= IEEE80211_C_TURBOP;
641 #ifdef IEEE80211_SUPPORT_TDMA
642 	if (ath_hal_macversion(ah) > 0x78) {
643 		ic->ic_caps |= IEEE80211_C_TDMA; /* capable of TDMA */
644 		ic->ic_tdma_update = ath_tdma_update;
645 	}
646 #endif
647 
648 	/*
649 	 * TODO: enforce that at least this many frames are available
650 	 * in the txbuf list before allowing data frames (raw or
651 	 * otherwise) to be transmitted.
652 	 */
653 	sc->sc_txq_data_minfree = 10;
654 	/*
655 	 * Leave this as default to maintain legacy behaviour.
656 	 * Shortening the cabq/mcastq may end up causing some
657 	 * undesirable behaviour.
658 	 */
659 	sc->sc_txq_mcastq_maxdepth = ath_txbuf;
660 
661 	/*
662 	 * Allow the TX and RX chainmasks to be overridden by
663 	 * environment variables and/or device.hints.
664 	 *
665 	 * This must be done early - before the hardware is
666 	 * calibrated or before the 802.11n stream calculation
667 	 * is done.
668 	 */
669 	if (resource_int_value(device_get_name(sc->sc_dev),
670 	    device_get_unit(sc->sc_dev), "rx_chainmask",
671 	    &rx_chainmask) == 0) {
672 		device_printf(sc->sc_dev, "Setting RX chainmask to 0x%x\n",
673 		    rx_chainmask);
674 		(void) ath_hal_setrxchainmask(sc->sc_ah, rx_chainmask);
675 	}
676 	if (resource_int_value(device_get_name(sc->sc_dev),
677 	    device_get_unit(sc->sc_dev), "tx_chainmask",
678 	    &tx_chainmask) == 0) {
679 		device_printf(sc->sc_dev, "Setting TX chainmask to 0x%x\n",
680 		    tx_chainmask);
681 		(void) ath_hal_settxchainmask(sc->sc_ah, tx_chainmask);
682 	}
683 
684 #ifdef	ATH_ENABLE_11N
685 	/*
686 	 * Query HT capabilities
687 	 */
688 	if (ath_hal_getcapability(ah, HAL_CAP_HT, 0, NULL) == HAL_OK &&
689 	    (wmodes & (HAL_MODE_HT20 | HAL_MODE_HT40))) {
690 		int rxs, txs;
691 
692 		device_printf(sc->sc_dev, "[HT] enabling HT modes\n");
693 		ic->ic_htcaps = IEEE80211_HTC_HT	/* HT operation */
694 			    | IEEE80211_HTC_AMPDU	/* A-MPDU tx/rx */
695 			    | IEEE80211_HTC_AMSDU	/* A-MSDU tx/rx */
696 			    | IEEE80211_HTCAP_MAXAMSDU_3839
697 			    				/* max A-MSDU length */
698 			    | IEEE80211_HTCAP_SMPS_OFF;	/* SM power save off */
699 			;
700 
701 		/*
702 		 * Enable short-GI for HT20 only if the hardware
703 		 * advertises support.
704 		 * Notably, anything earlier than the AR9287 doesn't.
705 		 */
706 		if ((ath_hal_getcapability(ah,
707 		    HAL_CAP_HT20_SGI, 0, NULL) == HAL_OK) &&
708 		    (wmodes & HAL_MODE_HT20)) {
709 			device_printf(sc->sc_dev,
710 			    "[HT] enabling short-GI in 20MHz mode\n");
711 			ic->ic_htcaps |= IEEE80211_HTCAP_SHORTGI20;
712 		}
713 
714 		if (wmodes & HAL_MODE_HT40)
715 			ic->ic_htcaps |= IEEE80211_HTCAP_CHWIDTH40
716 			    |  IEEE80211_HTCAP_SHORTGI40;
717 
718 		/*
719 		 * TX/RX streams need to be taken into account when
720 		 * negotiating which MCS rates it'll receive and
721 		 * what MCS rates are available for TX.
722 		 */
723 		(void) ath_hal_getcapability(ah, HAL_CAP_STREAMS, 0, &txs);
724 		(void) ath_hal_getcapability(ah, HAL_CAP_STREAMS, 1, &rxs);
725 
726 		ath_hal_getrxchainmask(ah, &sc->sc_rxchainmask);
727 		ath_hal_gettxchainmask(ah, &sc->sc_txchainmask);
728 
729 		ic->ic_txstream = txs;
730 		ic->ic_rxstream = rxs;
731 
732 		(void) ath_hal_getcapability(ah, HAL_CAP_RTS_AGGR_LIMIT, 1,
733 		    &sc->sc_rts_aggr_limit);
734 		if (sc->sc_rts_aggr_limit != (64 * 1024))
735 			device_printf(sc->sc_dev,
736 			    "[HT] RTS aggregates limited to %d KiB\n",
737 			    sc->sc_rts_aggr_limit / 1024);
738 
739 		device_printf(sc->sc_dev,
740 		    "[HT] %d RX streams; %d TX streams\n", rxs, txs);
741 	}
742 #endif
743 
744 	/*
745 	 * Initial aggregation settings.
746 	 */
747 	sc->sc_hwq_limit = ATH_AGGR_MIN_QDEPTH;
748 	sc->sc_tid_hwq_lo = ATH_AGGR_SCHED_LOW;
749 	sc->sc_tid_hwq_hi = ATH_AGGR_SCHED_HIGH;
750 
751 	/*
752 	 * Check if the hardware requires PCI register serialisation.
753 	 * Some of the Owl based MACs require this.
754 	 */
755 	if (mp_ncpus > 1 &&
756 	    ath_hal_getcapability(ah, HAL_CAP_SERIALISE_WAR,
757 	     0, NULL) == HAL_OK) {
758 		sc->sc_ah->ah_config.ah_serialise_reg_war = 1;
759 		device_printf(sc->sc_dev,
760 		    "Enabling register serialisation\n");
761 	}
762 
763 	/*
764 	 * Indicate we need the 802.11 header padded to a
765 	 * 32-bit boundary for 4-address and QoS frames.
766 	 */
767 	ic->ic_flags |= IEEE80211_F_DATAPAD;
768 
769 	/*
770 	 * Query the hal about antenna support.
771 	 */
772 	sc->sc_defant = ath_hal_getdefantenna(ah);
773 
774 	/*
775 	 * Not all chips have the VEOL support we want to
776 	 * use with IBSS beacons; check here for it.
777 	 */
778 	sc->sc_hasveol = ath_hal_hasveol(ah);
779 
780 	/* get mac address from hardware */
781 	ath_hal_getmac(ah, macaddr);
782 	if (sc->sc_hasbmask)
783 		ath_hal_getbssidmask(ah, sc->sc_hwbssidmask);
784 
785 	/* NB: used to size node table key mapping array */
786 	ic->ic_max_keyix = sc->sc_keymax;
787 	/* call MI attach routine. */
788 	ieee80211_ifattach(ic, macaddr);
789 	ic->ic_setregdomain = ath_setregdomain;
790 	ic->ic_getradiocaps = ath_getradiocaps;
791 	sc->sc_opmode = HAL_M_STA;
792 
793 	/* override default methods */
794 	ic->ic_newassoc = ath_newassoc;
795 	ic->ic_updateslot = ath_updateslot;
796 	ic->ic_wme.wme_update = ath_wme_update;
797 	ic->ic_vap_create = ath_vap_create;
798 	ic->ic_vap_delete = ath_vap_delete;
799 	ic->ic_raw_xmit = ath_raw_xmit;
800 	ic->ic_update_mcast = ath_update_mcast;
801 	ic->ic_update_promisc = ath_update_promisc;
802 	ic->ic_node_alloc = ath_node_alloc;
803 	sc->sc_node_free = ic->ic_node_free;
804 	ic->ic_node_free = ath_node_free;
805 	sc->sc_node_cleanup = ic->ic_node_cleanup;
806 	ic->ic_node_cleanup = ath_node_cleanup;
807 	ic->ic_node_getsignal = ath_node_getsignal;
808 	ic->ic_scan_start = ath_scan_start;
809 	ic->ic_scan_end = ath_scan_end;
810 	ic->ic_set_channel = ath_set_channel;
811 #ifdef	ATH_ENABLE_11N
812 	/* 802.11n specific - but just override anyway */
813 	sc->sc_addba_request = ic->ic_addba_request;
814 	sc->sc_addba_response = ic->ic_addba_response;
815 	sc->sc_addba_stop = ic->ic_addba_stop;
816 	sc->sc_bar_response = ic->ic_bar_response;
817 	sc->sc_addba_response_timeout = ic->ic_addba_response_timeout;
818 
819 	ic->ic_addba_request = ath_addba_request;
820 	ic->ic_addba_response = ath_addba_response;
821 	ic->ic_addba_response_timeout = ath_addba_response_timeout;
822 	ic->ic_addba_stop = ath_addba_stop;
823 	ic->ic_bar_response = ath_bar_response;
824 
825 	ic->ic_update_chw = ath_update_chw;
826 #endif	/* ATH_ENABLE_11N */
827 
828 #ifdef	ATH_ENABLE_RADIOTAP_VENDOR_EXT
829 	/*
830 	 * There's one vendor bitmap entry in the RX radiotap
831 	 * header; make sure that's taken into account.
832 	 */
833 	ieee80211_radiotap_attachv(ic,
834 	    &sc->sc_tx_th.wt_ihdr, sizeof(sc->sc_tx_th), 0,
835 		ATH_TX_RADIOTAP_PRESENT,
836 	    &sc->sc_rx_th.wr_ihdr, sizeof(sc->sc_rx_th), 1,
837 		ATH_RX_RADIOTAP_PRESENT);
838 #else
839 	/*
840 	 * No vendor bitmap/extensions are present.
841 	 */
842 	ieee80211_radiotap_attach(ic,
843 	    &sc->sc_tx_th.wt_ihdr, sizeof(sc->sc_tx_th),
844 		ATH_TX_RADIOTAP_PRESENT,
845 	    &sc->sc_rx_th.wr_ihdr, sizeof(sc->sc_rx_th),
846 		ATH_RX_RADIOTAP_PRESENT);
847 #endif	/* ATH_ENABLE_RADIOTAP_VENDOR_EXT */
848 
849 	/*
850 	 * Setup dynamic sysctl's now that country code and
851 	 * regdomain are available from the hal.
852 	 */
853 	ath_sysctlattach(sc);
854 	ath_sysctl_stats_attach(sc);
855 	ath_sysctl_hal_attach(sc);
856 
857 	if (bootverbose)
858 		ieee80211_announce(ic);
859 	ath_announce(sc);
860 	return 0;
861 bad2:
862 	ath_tx_cleanup(sc);
863 	ath_desc_free(sc);
864 	ath_rxdma_teardown(sc);
865 bad:
866 	if (ah)
867 		ath_hal_detach(ah);
868 	if (ifp != NULL)
869 		if_free(ifp);
870 	sc->sc_invalid = 1;
871 	return error;
872 }
873 
874 int
875 ath_detach(struct ath_softc *sc)
876 {
877 	struct ifnet *ifp = sc->sc_ifp;
878 
879 	DPRINTF(sc, ATH_DEBUG_ANY, "%s: if_flags %x\n",
880 		__func__, ifp->if_flags);
881 
882 	/*
883 	 * NB: the order of these is important:
884 	 * o stop the chip so no more interrupts will fire
885 	 * o call the 802.11 layer before detaching the hal to
886 	 *   insure callbacks into the driver to delete global
887 	 *   key cache entries can be handled
888 	 * o free the taskqueue which drains any pending tasks
889 	 * o reclaim the tx queue data structures after calling
890 	 *   the 802.11 layer as we'll get called back to reclaim
891 	 *   node state and potentially want to use them
892 	 * o to cleanup the tx queues the hal is called, so detach
893 	 *   it last
894 	 * Other than that, it's straightforward...
895 	 */
896 	ath_stop(ifp);
897 	ieee80211_ifdetach(ifp->if_l2com);
898 	taskqueue_free(sc->sc_tq);
899 #ifdef ATH_TX99_DIAG
900 	if (sc->sc_tx99 != NULL)
901 		sc->sc_tx99->detach(sc->sc_tx99);
902 #endif
903 	ath_rate_detach(sc->sc_rc);
904 
905 	ath_dfs_detach(sc);
906 	ath_desc_free(sc);
907 	ath_rxdma_teardown(sc);
908 	ath_tx_cleanup(sc);
909 	ath_hal_detach(sc->sc_ah);	/* NB: sets chip in full sleep */
910 	if_free(ifp);
911 
912 	return 0;
913 }
914 
915 /*
916  * MAC address handling for multiple BSS on the same radio.
917  * The first vap uses the MAC address from the EEPROM.  For
918  * subsequent vap's we set the U/L bit (bit 1) in the MAC
919  * address and use the next six bits as an index.
920  */
921 static void
922 assign_address(struct ath_softc *sc, uint8_t mac[IEEE80211_ADDR_LEN], int clone)
923 {
924 	int i;
925 
926 	if (clone && sc->sc_hasbmask) {
927 		/* NB: we only do this if h/w supports multiple bssid */
928 		for (i = 0; i < 8; i++)
929 			if ((sc->sc_bssidmask & (1<<i)) == 0)
930 				break;
931 		if (i != 0)
932 			mac[0] |= (i << 2)|0x2;
933 	} else
934 		i = 0;
935 	sc->sc_bssidmask |= 1<<i;
936 	sc->sc_hwbssidmask[0] &= ~mac[0];
937 	if (i == 0)
938 		sc->sc_nbssid0++;
939 }
940 
941 static void
942 reclaim_address(struct ath_softc *sc, const uint8_t mac[IEEE80211_ADDR_LEN])
943 {
944 	int i = mac[0] >> 2;
945 	uint8_t mask;
946 
947 	if (i != 0 || --sc->sc_nbssid0 == 0) {
948 		sc->sc_bssidmask &= ~(1<<i);
949 		/* recalculate bssid mask from remaining addresses */
950 		mask = 0xff;
951 		for (i = 1; i < 8; i++)
952 			if (sc->sc_bssidmask & (1<<i))
953 				mask &= ~((i<<2)|0x2);
954 		sc->sc_hwbssidmask[0] |= mask;
955 	}
956 }
957 
958 /*
959  * Assign a beacon xmit slot.  We try to space out
960  * assignments so when beacons are staggered the
961  * traffic coming out of the cab q has maximal time
962  * to go out before the next beacon is scheduled.
963  */
964 static int
965 assign_bslot(struct ath_softc *sc)
966 {
967 	u_int slot, free;
968 
969 	free = 0;
970 	for (slot = 0; slot < ATH_BCBUF; slot++)
971 		if (sc->sc_bslot[slot] == NULL) {
972 			if (sc->sc_bslot[(slot+1)%ATH_BCBUF] == NULL &&
973 			    sc->sc_bslot[(slot-1)%ATH_BCBUF] == NULL)
974 				return slot;
975 			free = slot;
976 			/* NB: keep looking for a double slot */
977 		}
978 	return free;
979 }
980 
981 static struct ieee80211vap *
982 ath_vap_create(struct ieee80211com *ic, const char name[IFNAMSIZ], int unit,
983     enum ieee80211_opmode opmode, int flags,
984     const uint8_t bssid[IEEE80211_ADDR_LEN],
985     const uint8_t mac0[IEEE80211_ADDR_LEN])
986 {
987 	struct ath_softc *sc = ic->ic_ifp->if_softc;
988 	struct ath_vap *avp;
989 	struct ieee80211vap *vap;
990 	uint8_t mac[IEEE80211_ADDR_LEN];
991 	int needbeacon, error;
992 	enum ieee80211_opmode ic_opmode;
993 
994 	avp = (struct ath_vap *) malloc(sizeof(struct ath_vap),
995 	    M_80211_VAP, M_WAITOK | M_ZERO);
996 	needbeacon = 0;
997 	IEEE80211_ADDR_COPY(mac, mac0);
998 
999 	ATH_LOCK(sc);
1000 	ic_opmode = opmode;		/* default to opmode of new vap */
1001 	switch (opmode) {
1002 	case IEEE80211_M_STA:
1003 		if (sc->sc_nstavaps != 0) {	/* XXX only 1 for now */
1004 			device_printf(sc->sc_dev, "only 1 sta vap supported\n");
1005 			goto bad;
1006 		}
1007 		if (sc->sc_nvaps) {
1008 			/*
1009 			 * With multiple vaps we must fall back
1010 			 * to s/w beacon miss handling.
1011 			 */
1012 			flags |= IEEE80211_CLONE_NOBEACONS;
1013 		}
1014 		if (flags & IEEE80211_CLONE_NOBEACONS) {
1015 			/*
1016 			 * Station mode w/o beacons are implemented w/ AP mode.
1017 			 */
1018 			ic_opmode = IEEE80211_M_HOSTAP;
1019 		}
1020 		break;
1021 	case IEEE80211_M_IBSS:
1022 		if (sc->sc_nvaps != 0) {	/* XXX only 1 for now */
1023 			device_printf(sc->sc_dev,
1024 			    "only 1 ibss vap supported\n");
1025 			goto bad;
1026 		}
1027 		needbeacon = 1;
1028 		break;
1029 	case IEEE80211_M_AHDEMO:
1030 #ifdef IEEE80211_SUPPORT_TDMA
1031 		if (flags & IEEE80211_CLONE_TDMA) {
1032 			if (sc->sc_nvaps != 0) {
1033 				device_printf(sc->sc_dev,
1034 				    "only 1 tdma vap supported\n");
1035 				goto bad;
1036 			}
1037 			needbeacon = 1;
1038 			flags |= IEEE80211_CLONE_NOBEACONS;
1039 		}
1040 		/* fall thru... */
1041 #endif
1042 	case IEEE80211_M_MONITOR:
1043 		if (sc->sc_nvaps != 0 && ic->ic_opmode != opmode) {
1044 			/*
1045 			 * Adopt existing mode.  Adding a monitor or ahdemo
1046 			 * vap to an existing configuration is of dubious
1047 			 * value but should be ok.
1048 			 */
1049 			/* XXX not right for monitor mode */
1050 			ic_opmode = ic->ic_opmode;
1051 		}
1052 		break;
1053 	case IEEE80211_M_HOSTAP:
1054 	case IEEE80211_M_MBSS:
1055 		needbeacon = 1;
1056 		break;
1057 	case IEEE80211_M_WDS:
1058 		if (sc->sc_nvaps != 0 && ic->ic_opmode == IEEE80211_M_STA) {
1059 			device_printf(sc->sc_dev,
1060 			    "wds not supported in sta mode\n");
1061 			goto bad;
1062 		}
1063 		/*
1064 		 * Silently remove any request for a unique
1065 		 * bssid; WDS vap's always share the local
1066 		 * mac address.
1067 		 */
1068 		flags &= ~IEEE80211_CLONE_BSSID;
1069 		if (sc->sc_nvaps == 0)
1070 			ic_opmode = IEEE80211_M_HOSTAP;
1071 		else
1072 			ic_opmode = ic->ic_opmode;
1073 		break;
1074 	default:
1075 		device_printf(sc->sc_dev, "unknown opmode %d\n", opmode);
1076 		goto bad;
1077 	}
1078 	/*
1079 	 * Check that a beacon buffer is available; the code below assumes it.
1080 	 */
1081 	if (needbeacon & TAILQ_EMPTY(&sc->sc_bbuf)) {
1082 		device_printf(sc->sc_dev, "no beacon buffer available\n");
1083 		goto bad;
1084 	}
1085 
1086 	/* STA, AHDEMO? */
1087 	if (opmode == IEEE80211_M_HOSTAP || opmode == IEEE80211_M_MBSS) {
1088 		assign_address(sc, mac, flags & IEEE80211_CLONE_BSSID);
1089 		ath_hal_setbssidmask(sc->sc_ah, sc->sc_hwbssidmask);
1090 	}
1091 
1092 	vap = &avp->av_vap;
1093 	/* XXX can't hold mutex across if_alloc */
1094 	ATH_UNLOCK(sc);
1095 	error = ieee80211_vap_setup(ic, vap, name, unit, opmode, flags,
1096 	    bssid, mac);
1097 	ATH_LOCK(sc);
1098 	if (error != 0) {
1099 		device_printf(sc->sc_dev, "%s: error %d creating vap\n",
1100 		    __func__, error);
1101 		goto bad2;
1102 	}
1103 
1104 	/* h/w crypto support */
1105 	vap->iv_key_alloc = ath_key_alloc;
1106 	vap->iv_key_delete = ath_key_delete;
1107 	vap->iv_key_set = ath_key_set;
1108 	vap->iv_key_update_begin = ath_key_update_begin;
1109 	vap->iv_key_update_end = ath_key_update_end;
1110 
1111 	/* override various methods */
1112 	avp->av_recv_mgmt = vap->iv_recv_mgmt;
1113 	vap->iv_recv_mgmt = ath_recv_mgmt;
1114 	vap->iv_reset = ath_reset_vap;
1115 	vap->iv_update_beacon = ath_beacon_update;
1116 	avp->av_newstate = vap->iv_newstate;
1117 	vap->iv_newstate = ath_newstate;
1118 	avp->av_bmiss = vap->iv_bmiss;
1119 	vap->iv_bmiss = ath_bmiss_vap;
1120 
1121 	/* Set default parameters */
1122 
1123 	/*
1124 	 * Anything earlier than some AR9300 series MACs don't
1125 	 * support a smaller MPDU density.
1126 	 */
1127 	vap->iv_ampdu_density = IEEE80211_HTCAP_MPDUDENSITY_8;
1128 	/*
1129 	 * All NICs can handle the maximum size, however
1130 	 * AR5416 based MACs can only TX aggregates w/ RTS
1131 	 * protection when the total aggregate size is <= 8k.
1132 	 * However, for now that's enforced by the TX path.
1133 	 */
1134 	vap->iv_ampdu_rxmax = IEEE80211_HTCAP_MAXRXAMPDU_64K;
1135 
1136 	avp->av_bslot = -1;
1137 	if (needbeacon) {
1138 		/*
1139 		 * Allocate beacon state and setup the q for buffered
1140 		 * multicast frames.  We know a beacon buffer is
1141 		 * available because we checked above.
1142 		 */
1143 		avp->av_bcbuf = TAILQ_FIRST(&sc->sc_bbuf);
1144 		TAILQ_REMOVE(&sc->sc_bbuf, avp->av_bcbuf, bf_list);
1145 		if (opmode != IEEE80211_M_IBSS || !sc->sc_hasveol) {
1146 			/*
1147 			 * Assign the vap to a beacon xmit slot.  As above
1148 			 * this cannot fail to find a free one.
1149 			 */
1150 			avp->av_bslot = assign_bslot(sc);
1151 			KASSERT(sc->sc_bslot[avp->av_bslot] == NULL,
1152 			    ("beacon slot %u not empty", avp->av_bslot));
1153 			sc->sc_bslot[avp->av_bslot] = vap;
1154 			sc->sc_nbcnvaps++;
1155 		}
1156 		if (sc->sc_hastsfadd && sc->sc_nbcnvaps > 0) {
1157 			/*
1158 			 * Multple vaps are to transmit beacons and we
1159 			 * have h/w support for TSF adjusting; enable
1160 			 * use of staggered beacons.
1161 			 */
1162 			sc->sc_stagbeacons = 1;
1163 		}
1164 		ath_txq_init(sc, &avp->av_mcastq, ATH_TXQ_SWQ);
1165 	}
1166 
1167 	ic->ic_opmode = ic_opmode;
1168 	if (opmode != IEEE80211_M_WDS) {
1169 		sc->sc_nvaps++;
1170 		if (opmode == IEEE80211_M_STA)
1171 			sc->sc_nstavaps++;
1172 		if (opmode == IEEE80211_M_MBSS)
1173 			sc->sc_nmeshvaps++;
1174 	}
1175 	switch (ic_opmode) {
1176 	case IEEE80211_M_IBSS:
1177 		sc->sc_opmode = HAL_M_IBSS;
1178 		break;
1179 	case IEEE80211_M_STA:
1180 		sc->sc_opmode = HAL_M_STA;
1181 		break;
1182 	case IEEE80211_M_AHDEMO:
1183 #ifdef IEEE80211_SUPPORT_TDMA
1184 		if (vap->iv_caps & IEEE80211_C_TDMA) {
1185 			sc->sc_tdma = 1;
1186 			/* NB: disable tsf adjust */
1187 			sc->sc_stagbeacons = 0;
1188 		}
1189 		/*
1190 		 * NB: adhoc demo mode is a pseudo mode; to the hal it's
1191 		 * just ap mode.
1192 		 */
1193 		/* fall thru... */
1194 #endif
1195 	case IEEE80211_M_HOSTAP:
1196 	case IEEE80211_M_MBSS:
1197 		sc->sc_opmode = HAL_M_HOSTAP;
1198 		break;
1199 	case IEEE80211_M_MONITOR:
1200 		sc->sc_opmode = HAL_M_MONITOR;
1201 		break;
1202 	default:
1203 		/* XXX should not happen */
1204 		break;
1205 	}
1206 	if (sc->sc_hastsfadd) {
1207 		/*
1208 		 * Configure whether or not TSF adjust should be done.
1209 		 */
1210 		ath_hal_settsfadjust(sc->sc_ah, sc->sc_stagbeacons);
1211 	}
1212 	if (flags & IEEE80211_CLONE_NOBEACONS) {
1213 		/*
1214 		 * Enable s/w beacon miss handling.
1215 		 */
1216 		sc->sc_swbmiss = 1;
1217 	}
1218 	ATH_UNLOCK(sc);
1219 
1220 	/* complete setup */
1221 	ieee80211_vap_attach(vap, ath_media_change, ieee80211_media_status);
1222 	return vap;
1223 bad2:
1224 	reclaim_address(sc, mac);
1225 	ath_hal_setbssidmask(sc->sc_ah, sc->sc_hwbssidmask);
1226 bad:
1227 	free(avp, M_80211_VAP);
1228 	ATH_UNLOCK(sc);
1229 	return NULL;
1230 }
1231 
1232 static void
1233 ath_vap_delete(struct ieee80211vap *vap)
1234 {
1235 	struct ieee80211com *ic = vap->iv_ic;
1236 	struct ifnet *ifp = ic->ic_ifp;
1237 	struct ath_softc *sc = ifp->if_softc;
1238 	struct ath_hal *ah = sc->sc_ah;
1239 	struct ath_vap *avp = ATH_VAP(vap);
1240 
1241 	DPRINTF(sc, ATH_DEBUG_RESET, "%s: called\n", __func__);
1242 	if (ifp->if_drv_flags & IFF_DRV_RUNNING) {
1243 		/*
1244 		 * Quiesce the hardware while we remove the vap.  In
1245 		 * particular we need to reclaim all references to
1246 		 * the vap state by any frames pending on the tx queues.
1247 		 */
1248 		ath_hal_intrset(ah, 0);		/* disable interrupts */
1249 		ath_draintxq(sc, ATH_RESET_DEFAULT);		/* stop hw xmit side */
1250 		/* XXX Do all frames from all vaps/nodes need draining here? */
1251 		ath_stoprecv(sc, 1);		/* stop recv side */
1252 	}
1253 
1254 	ieee80211_vap_detach(vap);
1255 
1256 	/*
1257 	 * XXX Danger Will Robinson! Danger!
1258 	 *
1259 	 * Because ieee80211_vap_detach() can queue a frame (the station
1260 	 * diassociate message?) after we've drained the TXQ and
1261 	 * flushed the software TXQ, we will end up with a frame queued
1262 	 * to a node whose vap is about to be freed.
1263 	 *
1264 	 * To work around this, flush the hardware/software again.
1265 	 * This may be racy - the ath task may be running and the packet
1266 	 * may be being scheduled between sw->hw txq. Tsk.
1267 	 *
1268 	 * TODO: figure out why a new node gets allocated somewhere around
1269 	 * here (after the ath_tx_swq() call; and after an ath_stop_locked()
1270 	 * call!)
1271 	 */
1272 
1273 	ath_draintxq(sc, ATH_RESET_DEFAULT);
1274 
1275 	ATH_LOCK(sc);
1276 	/*
1277 	 * Reclaim beacon state.  Note this must be done before
1278 	 * the vap instance is reclaimed as we may have a reference
1279 	 * to it in the buffer for the beacon frame.
1280 	 */
1281 	if (avp->av_bcbuf != NULL) {
1282 		if (avp->av_bslot != -1) {
1283 			sc->sc_bslot[avp->av_bslot] = NULL;
1284 			sc->sc_nbcnvaps--;
1285 		}
1286 		ath_beacon_return(sc, avp->av_bcbuf);
1287 		avp->av_bcbuf = NULL;
1288 		if (sc->sc_nbcnvaps == 0) {
1289 			sc->sc_stagbeacons = 0;
1290 			if (sc->sc_hastsfadd)
1291 				ath_hal_settsfadjust(sc->sc_ah, 0);
1292 		}
1293 		/*
1294 		 * Reclaim any pending mcast frames for the vap.
1295 		 */
1296 		ath_tx_draintxq(sc, &avp->av_mcastq);
1297 		ATH_TXQ_LOCK_DESTROY(&avp->av_mcastq);
1298 	}
1299 	/*
1300 	 * Update bookkeeping.
1301 	 */
1302 	if (vap->iv_opmode == IEEE80211_M_STA) {
1303 		sc->sc_nstavaps--;
1304 		if (sc->sc_nstavaps == 0 && sc->sc_swbmiss)
1305 			sc->sc_swbmiss = 0;
1306 	} else if (vap->iv_opmode == IEEE80211_M_HOSTAP ||
1307 	    vap->iv_opmode == IEEE80211_M_MBSS) {
1308 		reclaim_address(sc, vap->iv_myaddr);
1309 		ath_hal_setbssidmask(ah, sc->sc_hwbssidmask);
1310 		if (vap->iv_opmode == IEEE80211_M_MBSS)
1311 			sc->sc_nmeshvaps--;
1312 	}
1313 	if (vap->iv_opmode != IEEE80211_M_WDS)
1314 		sc->sc_nvaps--;
1315 #ifdef IEEE80211_SUPPORT_TDMA
1316 	/* TDMA operation ceases when the last vap is destroyed */
1317 	if (sc->sc_tdma && sc->sc_nvaps == 0) {
1318 		sc->sc_tdma = 0;
1319 		sc->sc_swbmiss = 0;
1320 	}
1321 #endif
1322 	free(avp, M_80211_VAP);
1323 
1324 	if (ifp->if_drv_flags & IFF_DRV_RUNNING) {
1325 		/*
1326 		 * Restart rx+tx machines if still running (RUNNING will
1327 		 * be reset if we just destroyed the last vap).
1328 		 */
1329 		if (ath_startrecv(sc) != 0)
1330 			if_printf(ifp, "%s: unable to restart recv logic\n",
1331 			    __func__);
1332 		if (sc->sc_beacons) {		/* restart beacons */
1333 #ifdef IEEE80211_SUPPORT_TDMA
1334 			if (sc->sc_tdma)
1335 				ath_tdma_config(sc, NULL);
1336 			else
1337 #endif
1338 				ath_beacon_config(sc, NULL);
1339 		}
1340 		ath_hal_intrset(ah, sc->sc_imask);
1341 	}
1342 	ATH_UNLOCK(sc);
1343 }
1344 
1345 void
1346 ath_suspend(struct ath_softc *sc)
1347 {
1348 	struct ifnet *ifp = sc->sc_ifp;
1349 	struct ieee80211com *ic = ifp->if_l2com;
1350 
1351 	DPRINTF(sc, ATH_DEBUG_ANY, "%s: if_flags %x\n",
1352 		__func__, ifp->if_flags);
1353 
1354 	sc->sc_resume_up = (ifp->if_flags & IFF_UP) != 0;
1355 
1356 	ieee80211_suspend_all(ic);
1357 	/*
1358 	 * NB: don't worry about putting the chip in low power
1359 	 * mode; pci will power off our socket on suspend and
1360 	 * CardBus detaches the device.
1361 	 */
1362 
1363 	/*
1364 	 * XXX ensure none of the taskqueues are running
1365 	 * XXX ensure sc_invalid is 1
1366 	 * XXX ensure the calibration callout is disabled
1367 	 */
1368 
1369 	/* Disable the PCIe PHY, complete with workarounds */
1370 	ath_hal_enablepcie(sc->sc_ah, 1, 1);
1371 }
1372 
1373 /*
1374  * Reset the key cache since some parts do not reset the
1375  * contents on resume.  First we clear all entries, then
1376  * re-load keys that the 802.11 layer assumes are setup
1377  * in h/w.
1378  */
1379 static void
1380 ath_reset_keycache(struct ath_softc *sc)
1381 {
1382 	struct ifnet *ifp = sc->sc_ifp;
1383 	struct ieee80211com *ic = ifp->if_l2com;
1384 	struct ath_hal *ah = sc->sc_ah;
1385 	int i;
1386 
1387 	for (i = 0; i < sc->sc_keymax; i++)
1388 		ath_hal_keyreset(ah, i);
1389 	ieee80211_crypto_reload_keys(ic);
1390 }
1391 
1392 void
1393 ath_resume(struct ath_softc *sc)
1394 {
1395 	struct ifnet *ifp = sc->sc_ifp;
1396 	struct ieee80211com *ic = ifp->if_l2com;
1397 	struct ath_hal *ah = sc->sc_ah;
1398 	HAL_STATUS status;
1399 
1400 	DPRINTF(sc, ATH_DEBUG_ANY, "%s: if_flags %x\n",
1401 		__func__, ifp->if_flags);
1402 
1403 	/* Re-enable PCIe, re-enable the PCIe bus */
1404 	ath_hal_enablepcie(ah, 0, 0);
1405 
1406 	/*
1407 	 * Must reset the chip before we reload the
1408 	 * keycache as we were powered down on suspend.
1409 	 */
1410 	ath_hal_reset(ah, sc->sc_opmode,
1411 	    sc->sc_curchan != NULL ? sc->sc_curchan : ic->ic_curchan,
1412 	    AH_FALSE, &status);
1413 	ath_reset_keycache(sc);
1414 
1415 	/* Let DFS at it in case it's a DFS channel */
1416 	ath_dfs_radar_enable(sc, ic->ic_curchan);
1417 
1418 	/* Restore the LED configuration */
1419 	ath_led_config(sc);
1420 	ath_hal_setledstate(ah, HAL_LED_INIT);
1421 
1422 	if (sc->sc_resume_up)
1423 		ieee80211_resume_all(ic);
1424 
1425 	/* XXX beacons ? */
1426 }
1427 
1428 void
1429 ath_shutdown(struct ath_softc *sc)
1430 {
1431 	struct ifnet *ifp = sc->sc_ifp;
1432 
1433 	DPRINTF(sc, ATH_DEBUG_ANY, "%s: if_flags %x\n",
1434 		__func__, ifp->if_flags);
1435 
1436 	ath_stop(ifp);
1437 	/* NB: no point powering down chip as we're about to reboot */
1438 }
1439 
1440 /*
1441  * Interrupt handler.  Most of the actual processing is deferred.
1442  */
1443 void
1444 ath_intr(void *arg)
1445 {
1446 	struct ath_softc *sc = arg;
1447 	struct ifnet *ifp = sc->sc_ifp;
1448 	struct ath_hal *ah = sc->sc_ah;
1449 	HAL_INT status = 0;
1450 	uint32_t txqs;
1451 
1452 	/*
1453 	 * If we're inside a reset path, just print a warning and
1454 	 * clear the ISR. The reset routine will finish it for us.
1455 	 */
1456 	ATH_PCU_LOCK(sc);
1457 	if (sc->sc_inreset_cnt) {
1458 		HAL_INT status;
1459 		ath_hal_getisr(ah, &status);	/* clear ISR */
1460 		ath_hal_intrset(ah, 0);		/* disable further intr's */
1461 		DPRINTF(sc, ATH_DEBUG_ANY,
1462 		    "%s: in reset, ignoring: status=0x%x\n",
1463 		    __func__, status);
1464 		ATH_PCU_UNLOCK(sc);
1465 		return;
1466 	}
1467 
1468 	if (sc->sc_invalid) {
1469 		/*
1470 		 * The hardware is not ready/present, don't touch anything.
1471 		 * Note this can happen early on if the IRQ is shared.
1472 		 */
1473 		DPRINTF(sc, ATH_DEBUG_ANY, "%s: invalid; ignored\n", __func__);
1474 		ATH_PCU_UNLOCK(sc);
1475 		return;
1476 	}
1477 	if (!ath_hal_intrpend(ah)) {		/* shared irq, not for us */
1478 		ATH_PCU_UNLOCK(sc);
1479 		return;
1480 	}
1481 
1482 	if ((ifp->if_flags & IFF_UP) == 0 ||
1483 	    (ifp->if_drv_flags & IFF_DRV_RUNNING) == 0) {
1484 		HAL_INT status;
1485 
1486 		DPRINTF(sc, ATH_DEBUG_ANY, "%s: if_flags 0x%x\n",
1487 			__func__, ifp->if_flags);
1488 		ath_hal_getisr(ah, &status);	/* clear ISR */
1489 		ath_hal_intrset(ah, 0);		/* disable further intr's */
1490 		ATH_PCU_UNLOCK(sc);
1491 		return;
1492 	}
1493 
1494 	/*
1495 	 * Figure out the reason(s) for the interrupt.  Note
1496 	 * that the hal returns a pseudo-ISR that may include
1497 	 * bits we haven't explicitly enabled so we mask the
1498 	 * value to insure we only process bits we requested.
1499 	 */
1500 	ath_hal_getisr(ah, &status);		/* NB: clears ISR too */
1501 	DPRINTF(sc, ATH_DEBUG_INTR, "%s: status 0x%x\n", __func__, status);
1502 	CTR1(ATH_KTR_INTR, "ath_intr: mask=0x%.8x", status);
1503 #ifdef	ATH_KTR_INTR_DEBUG
1504 	CTR5(ATH_KTR_INTR,
1505 	    "ath_intr: ISR=0x%.8x, ISR_S0=0x%.8x, ISR_S1=0x%.8x, ISR_S2=0x%.8x, ISR_S5=0x%.8x",
1506 	    ah->ah_intrstate[0],
1507 	    ah->ah_intrstate[1],
1508 	    ah->ah_intrstate[2],
1509 	    ah->ah_intrstate[3],
1510 	    ah->ah_intrstate[6]);
1511 #endif
1512 
1513 	/* Squirrel away SYNC interrupt debugging */
1514 	if (ah->ah_syncstate != 0) {
1515 		int i;
1516 		for (i = 0; i < 32; i++)
1517 			if (ah->ah_syncstate & (i << i))
1518 				sc->sc_intr_stats.sync_intr[i]++;
1519 	}
1520 
1521 	status &= sc->sc_imask;			/* discard unasked for bits */
1522 
1523 	/* Short-circuit un-handled interrupts */
1524 	if (status == 0x0) {
1525 		ATH_PCU_UNLOCK(sc);
1526 		return;
1527 	}
1528 
1529 	/*
1530 	 * Take a note that we're inside the interrupt handler, so
1531 	 * the reset routines know to wait.
1532 	 */
1533 	sc->sc_intr_cnt++;
1534 	ATH_PCU_UNLOCK(sc);
1535 
1536 	/*
1537 	 * Handle the interrupt. We won't run concurrent with the reset
1538 	 * or channel change routines as they'll wait for sc_intr_cnt
1539 	 * to be 0 before continuing.
1540 	 */
1541 	if (status & HAL_INT_FATAL) {
1542 		sc->sc_stats.ast_hardware++;
1543 		ath_hal_intrset(ah, 0);		/* disable intr's until reset */
1544 		taskqueue_enqueue(sc->sc_tq, &sc->sc_fataltask);
1545 	} else {
1546 		if (status & HAL_INT_SWBA) {
1547 			/*
1548 			 * Software beacon alert--time to send a beacon.
1549 			 * Handle beacon transmission directly; deferring
1550 			 * this is too slow to meet timing constraints
1551 			 * under load.
1552 			 */
1553 #ifdef IEEE80211_SUPPORT_TDMA
1554 			if (sc->sc_tdma) {
1555 				if (sc->sc_tdmaswba == 0) {
1556 					struct ieee80211com *ic = ifp->if_l2com;
1557 					struct ieee80211vap *vap =
1558 					    TAILQ_FIRST(&ic->ic_vaps);
1559 					ath_tdma_beacon_send(sc, vap);
1560 					sc->sc_tdmaswba =
1561 					    vap->iv_tdma->tdma_bintval;
1562 				} else
1563 					sc->sc_tdmaswba--;
1564 			} else
1565 #endif
1566 			{
1567 				ath_beacon_proc(sc, 0);
1568 #ifdef IEEE80211_SUPPORT_SUPERG
1569 				/*
1570 				 * Schedule the rx taskq in case there's no
1571 				 * traffic so any frames held on the staging
1572 				 * queue are aged and potentially flushed.
1573 				 */
1574 				taskqueue_enqueue(sc->sc_tq, &sc->sc_rxtask);
1575 #endif
1576 			}
1577 		}
1578 		if (status & HAL_INT_RXEOL) {
1579 			int imask;
1580 			CTR0(ATH_KTR_ERR, "ath_intr: RXEOL");
1581 			ATH_PCU_LOCK(sc);
1582 			/*
1583 			 * NB: the hardware should re-read the link when
1584 			 *     RXE bit is written, but it doesn't work at
1585 			 *     least on older hardware revs.
1586 			 */
1587 			sc->sc_stats.ast_rxeol++;
1588 			/*
1589 			 * Disable RXEOL/RXORN - prevent an interrupt
1590 			 * storm until the PCU logic can be reset.
1591 			 * In case the interface is reset some other
1592 			 * way before "sc_kickpcu" is called, don't
1593 			 * modify sc_imask - that way if it is reset
1594 			 * by a call to ath_reset() somehow, the
1595 			 * interrupt mask will be correctly reprogrammed.
1596 			 */
1597 			imask = sc->sc_imask;
1598 			imask &= ~(HAL_INT_RXEOL | HAL_INT_RXORN);
1599 			ath_hal_intrset(ah, imask);
1600 			/*
1601 			 * Only blank sc_rxlink if we've not yet kicked
1602 			 * the PCU.
1603 			 *
1604 			 * This isn't entirely correct - the correct solution
1605 			 * would be to have a PCU lock and engage that for
1606 			 * the duration of the PCU fiddling; which would include
1607 			 * running the RX process. Otherwise we could end up
1608 			 * messing up the RX descriptor chain and making the
1609 			 * RX desc list much shorter.
1610 			 */
1611 			if (! sc->sc_kickpcu)
1612 				sc->sc_rxlink = NULL;
1613 			sc->sc_kickpcu = 1;
1614 			/*
1615 			 * Enqueue an RX proc, to handled whatever
1616 			 * is in the RX queue.
1617 			 * This will then kick the PCU.
1618 			 */
1619 			taskqueue_enqueue(sc->sc_tq, &sc->sc_rxtask);
1620 			ATH_PCU_UNLOCK(sc);
1621 		}
1622 		if (status & HAL_INT_TXURN) {
1623 			sc->sc_stats.ast_txurn++;
1624 			/* bump tx trigger level */
1625 			ath_hal_updatetxtriglevel(ah, AH_TRUE);
1626 		}
1627 		if (status & HAL_INT_RX) {
1628 			sc->sc_stats.ast_rx_intr++;
1629 			taskqueue_enqueue(sc->sc_tq, &sc->sc_rxtask);
1630 		}
1631 		if (status & HAL_INT_TX) {
1632 			sc->sc_stats.ast_tx_intr++;
1633 			/*
1634 			 * Grab all the currently set bits in the HAL txq bitmap
1635 			 * and blank them. This is the only place we should be
1636 			 * doing this.
1637 			 */
1638 			ATH_PCU_LOCK(sc);
1639 			txqs = 0xffffffff;
1640 			ath_hal_gettxintrtxqs(sc->sc_ah, &txqs);
1641 			sc->sc_txq_active |= txqs;
1642 			taskqueue_enqueue(sc->sc_tq, &sc->sc_txtask);
1643 			ATH_PCU_UNLOCK(sc);
1644 		}
1645 		if (status & HAL_INT_BMISS) {
1646 			sc->sc_stats.ast_bmiss++;
1647 			taskqueue_enqueue(sc->sc_tq, &sc->sc_bmisstask);
1648 		}
1649 		if (status & HAL_INT_GTT)
1650 			sc->sc_stats.ast_tx_timeout++;
1651 		if (status & HAL_INT_CST)
1652 			sc->sc_stats.ast_tx_cst++;
1653 		if (status & HAL_INT_MIB) {
1654 			sc->sc_stats.ast_mib++;
1655 			ATH_PCU_LOCK(sc);
1656 			/*
1657 			 * Disable interrupts until we service the MIB
1658 			 * interrupt; otherwise it will continue to fire.
1659 			 */
1660 			ath_hal_intrset(ah, 0);
1661 			/*
1662 			 * Let the hal handle the event.  We assume it will
1663 			 * clear whatever condition caused the interrupt.
1664 			 */
1665 			ath_hal_mibevent(ah, &sc->sc_halstats);
1666 			/*
1667 			 * Don't reset the interrupt if we've just
1668 			 * kicked the PCU, or we may get a nested
1669 			 * RXEOL before the rxproc has had a chance
1670 			 * to run.
1671 			 */
1672 			if (sc->sc_kickpcu == 0)
1673 				ath_hal_intrset(ah, sc->sc_imask);
1674 			ATH_PCU_UNLOCK(sc);
1675 		}
1676 		if (status & HAL_INT_RXORN) {
1677 			/* NB: hal marks HAL_INT_FATAL when RXORN is fatal */
1678 			CTR0(ATH_KTR_ERR, "ath_intr: RXORN");
1679 			sc->sc_stats.ast_rxorn++;
1680 		}
1681 	}
1682 	ATH_PCU_LOCK(sc);
1683 	sc->sc_intr_cnt--;
1684 	ATH_PCU_UNLOCK(sc);
1685 }
1686 
1687 static void
1688 ath_fatal_proc(void *arg, int pending)
1689 {
1690 	struct ath_softc *sc = arg;
1691 	struct ifnet *ifp = sc->sc_ifp;
1692 	u_int32_t *state;
1693 	u_int32_t len;
1694 	void *sp;
1695 
1696 	if_printf(ifp, "hardware error; resetting\n");
1697 	/*
1698 	 * Fatal errors are unrecoverable.  Typically these
1699 	 * are caused by DMA errors.  Collect h/w state from
1700 	 * the hal so we can diagnose what's going on.
1701 	 */
1702 	if (ath_hal_getfatalstate(sc->sc_ah, &sp, &len)) {
1703 		KASSERT(len >= 6*sizeof(u_int32_t), ("len %u bytes", len));
1704 		state = sp;
1705 		if_printf(ifp, "0x%08x 0x%08x 0x%08x, 0x%08x 0x%08x 0x%08x\n",
1706 		    state[0], state[1] , state[2], state[3],
1707 		    state[4], state[5]);
1708 	}
1709 	ath_reset(ifp, ATH_RESET_NOLOSS);
1710 }
1711 
1712 static void
1713 ath_bmiss_vap(struct ieee80211vap *vap)
1714 {
1715 	/*
1716 	 * Workaround phantom bmiss interrupts by sanity-checking
1717 	 * the time of our last rx'd frame.  If it is within the
1718 	 * beacon miss interval then ignore the interrupt.  If it's
1719 	 * truly a bmiss we'll get another interrupt soon and that'll
1720 	 * be dispatched up for processing.  Note this applies only
1721 	 * for h/w beacon miss events.
1722 	 */
1723 	if ((vap->iv_flags_ext & IEEE80211_FEXT_SWBMISS) == 0) {
1724 		struct ifnet *ifp = vap->iv_ic->ic_ifp;
1725 		struct ath_softc *sc = ifp->if_softc;
1726 		u_int64_t lastrx = sc->sc_lastrx;
1727 		u_int64_t tsf = ath_hal_gettsf64(sc->sc_ah);
1728 		/* XXX should take a locked ref to iv_bss */
1729 		u_int bmisstimeout =
1730 			vap->iv_bmissthreshold * vap->iv_bss->ni_intval * 1024;
1731 
1732 		DPRINTF(sc, ATH_DEBUG_BEACON,
1733 		    "%s: tsf %llu lastrx %lld (%llu) bmiss %u\n",
1734 		    __func__, (unsigned long long) tsf,
1735 		    (unsigned long long)(tsf - lastrx),
1736 		    (unsigned long long) lastrx, bmisstimeout);
1737 
1738 		if (tsf - lastrx <= bmisstimeout) {
1739 			sc->sc_stats.ast_bmiss_phantom++;
1740 			return;
1741 		}
1742 	}
1743 	ATH_VAP(vap)->av_bmiss(vap);
1744 }
1745 
1746 static int
1747 ath_hal_gethangstate(struct ath_hal *ah, uint32_t mask, uint32_t *hangs)
1748 {
1749 	uint32_t rsize;
1750 	void *sp;
1751 
1752 	if (!ath_hal_getdiagstate(ah, HAL_DIAG_CHECK_HANGS, &mask, sizeof(mask), &sp, &rsize))
1753 		return 0;
1754 	KASSERT(rsize == sizeof(uint32_t), ("resultsize %u", rsize));
1755 	*hangs = *(uint32_t *)sp;
1756 	return 1;
1757 }
1758 
1759 static void
1760 ath_bmiss_proc(void *arg, int pending)
1761 {
1762 	struct ath_softc *sc = arg;
1763 	struct ifnet *ifp = sc->sc_ifp;
1764 	uint32_t hangs;
1765 
1766 	DPRINTF(sc, ATH_DEBUG_ANY, "%s: pending %u\n", __func__, pending);
1767 
1768 	if (ath_hal_gethangstate(sc->sc_ah, 0xff, &hangs) && hangs != 0) {
1769 		if_printf(ifp, "bb hang detected (0x%x), resetting\n", hangs);
1770 		ath_reset(ifp, ATH_RESET_NOLOSS);
1771 	} else
1772 		ieee80211_beacon_miss(ifp->if_l2com);
1773 }
1774 
1775 /*
1776  * Handle TKIP MIC setup to deal hardware that doesn't do MIC
1777  * calcs together with WME.  If necessary disable the crypto
1778  * hardware and mark the 802.11 state so keys will be setup
1779  * with the MIC work done in software.
1780  */
1781 static void
1782 ath_settkipmic(struct ath_softc *sc)
1783 {
1784 	struct ifnet *ifp = sc->sc_ifp;
1785 	struct ieee80211com *ic = ifp->if_l2com;
1786 
1787 	if ((ic->ic_cryptocaps & IEEE80211_CRYPTO_TKIP) && !sc->sc_wmetkipmic) {
1788 		if (ic->ic_flags & IEEE80211_F_WME) {
1789 			ath_hal_settkipmic(sc->sc_ah, AH_FALSE);
1790 			ic->ic_cryptocaps &= ~IEEE80211_CRYPTO_TKIPMIC;
1791 		} else {
1792 			ath_hal_settkipmic(sc->sc_ah, AH_TRUE);
1793 			ic->ic_cryptocaps |= IEEE80211_CRYPTO_TKIPMIC;
1794 		}
1795 	}
1796 }
1797 
1798 static void
1799 ath_init(void *arg)
1800 {
1801 	struct ath_softc *sc = (struct ath_softc *) arg;
1802 	struct ifnet *ifp = sc->sc_ifp;
1803 	struct ieee80211com *ic = ifp->if_l2com;
1804 	struct ath_hal *ah = sc->sc_ah;
1805 	HAL_STATUS status;
1806 
1807 	DPRINTF(sc, ATH_DEBUG_ANY, "%s: if_flags 0x%x\n",
1808 		__func__, ifp->if_flags);
1809 
1810 	ATH_LOCK(sc);
1811 	/*
1812 	 * Stop anything previously setup.  This is safe
1813 	 * whether this is the first time through or not.
1814 	 */
1815 	ath_stop_locked(ifp);
1816 
1817 	/*
1818 	 * The basic interface to setting the hardware in a good
1819 	 * state is ``reset''.  On return the hardware is known to
1820 	 * be powered up and with interrupts disabled.  This must
1821 	 * be followed by initialization of the appropriate bits
1822 	 * and then setup of the interrupt mask.
1823 	 */
1824 	ath_settkipmic(sc);
1825 	if (!ath_hal_reset(ah, sc->sc_opmode, ic->ic_curchan, AH_FALSE, &status)) {
1826 		if_printf(ifp, "unable to reset hardware; hal status %u\n",
1827 			status);
1828 		ATH_UNLOCK(sc);
1829 		return;
1830 	}
1831 	ath_chan_change(sc, ic->ic_curchan);
1832 
1833 	/* Let DFS at it in case it's a DFS channel */
1834 	ath_dfs_radar_enable(sc, ic->ic_curchan);
1835 
1836 	/*
1837 	 * Likewise this is set during reset so update
1838 	 * state cached in the driver.
1839 	 */
1840 	sc->sc_diversity = ath_hal_getdiversity(ah);
1841 	sc->sc_lastlongcal = 0;
1842 	sc->sc_resetcal = 1;
1843 	sc->sc_lastcalreset = 0;
1844 	sc->sc_lastani = 0;
1845 	sc->sc_lastshortcal = 0;
1846 	sc->sc_doresetcal = AH_FALSE;
1847 	/*
1848 	 * Beacon timers were cleared here; give ath_newstate()
1849 	 * a hint that the beacon timers should be poked when
1850 	 * things transition to the RUN state.
1851 	 */
1852 	sc->sc_beacons = 0;
1853 
1854 	/*
1855 	 * Setup the hardware after reset: the key cache
1856 	 * is filled as needed and the receive engine is
1857 	 * set going.  Frame transmit is handled entirely
1858 	 * in the frame output path; there's nothing to do
1859 	 * here except setup the interrupt mask.
1860 	 */
1861 	if (ath_startrecv(sc) != 0) {
1862 		if_printf(ifp, "unable to start recv logic\n");
1863 		ATH_UNLOCK(sc);
1864 		return;
1865 	}
1866 
1867 	/*
1868 	 * Enable interrupts.
1869 	 */
1870 	sc->sc_imask = HAL_INT_RX | HAL_INT_TX
1871 		  | HAL_INT_RXEOL | HAL_INT_RXORN
1872 		  | HAL_INT_FATAL | HAL_INT_GLOBAL;
1873 	/*
1874 	 * Enable MIB interrupts when there are hardware phy counters.
1875 	 * Note we only do this (at the moment) for station mode.
1876 	 */
1877 	if (sc->sc_needmib && ic->ic_opmode == IEEE80211_M_STA)
1878 		sc->sc_imask |= HAL_INT_MIB;
1879 
1880 	/* Enable global TX timeout and carrier sense timeout if available */
1881 	if (ath_hal_gtxto_supported(ah))
1882 		sc->sc_imask |= HAL_INT_GTT;
1883 
1884 	DPRINTF(sc, ATH_DEBUG_RESET, "%s: imask=0x%x\n",
1885 		__func__, sc->sc_imask);
1886 
1887 	ifp->if_drv_flags |= IFF_DRV_RUNNING;
1888 	callout_reset(&sc->sc_wd_ch, hz, ath_watchdog, sc);
1889 	ath_hal_intrset(ah, sc->sc_imask);
1890 
1891 	ATH_UNLOCK(sc);
1892 
1893 #ifdef ATH_TX99_DIAG
1894 	if (sc->sc_tx99 != NULL)
1895 		sc->sc_tx99->start(sc->sc_tx99);
1896 	else
1897 #endif
1898 	ieee80211_start_all(ic);		/* start all vap's */
1899 }
1900 
1901 static void
1902 ath_stop_locked(struct ifnet *ifp)
1903 {
1904 	struct ath_softc *sc = ifp->if_softc;
1905 	struct ath_hal *ah = sc->sc_ah;
1906 
1907 	DPRINTF(sc, ATH_DEBUG_ANY, "%s: invalid %u if_flags 0x%x\n",
1908 		__func__, sc->sc_invalid, ifp->if_flags);
1909 
1910 	ATH_LOCK_ASSERT(sc);
1911 	if (ifp->if_drv_flags & IFF_DRV_RUNNING) {
1912 		/*
1913 		 * Shutdown the hardware and driver:
1914 		 *    reset 802.11 state machine
1915 		 *    turn off timers
1916 		 *    disable interrupts
1917 		 *    turn off the radio
1918 		 *    clear transmit machinery
1919 		 *    clear receive machinery
1920 		 *    drain and release tx queues
1921 		 *    reclaim beacon resources
1922 		 *    power down hardware
1923 		 *
1924 		 * Note that some of this work is not possible if the
1925 		 * hardware is gone (invalid).
1926 		 */
1927 #ifdef ATH_TX99_DIAG
1928 		if (sc->sc_tx99 != NULL)
1929 			sc->sc_tx99->stop(sc->sc_tx99);
1930 #endif
1931 		callout_stop(&sc->sc_wd_ch);
1932 		sc->sc_wd_timer = 0;
1933 		ifp->if_drv_flags &= ~IFF_DRV_RUNNING;
1934 		if (!sc->sc_invalid) {
1935 			if (sc->sc_softled) {
1936 				callout_stop(&sc->sc_ledtimer);
1937 				ath_hal_gpioset(ah, sc->sc_ledpin,
1938 					!sc->sc_ledon);
1939 				sc->sc_blinking = 0;
1940 			}
1941 			ath_hal_intrset(ah, 0);
1942 		}
1943 		ath_draintxq(sc, ATH_RESET_DEFAULT);
1944 		if (!sc->sc_invalid) {
1945 			ath_stoprecv(sc, 1);
1946 			ath_hal_phydisable(ah);
1947 		} else
1948 			sc->sc_rxlink = NULL;
1949 		ath_beacon_free(sc);	/* XXX not needed */
1950 	}
1951 }
1952 
1953 #define	MAX_TXRX_ITERATIONS	1000
1954 static void
1955 ath_txrx_stop_locked(struct ath_softc *sc)
1956 {
1957 	int i = MAX_TXRX_ITERATIONS;
1958 
1959 	ATH_UNLOCK_ASSERT(sc);
1960 	ATH_PCU_LOCK_ASSERT(sc);
1961 
1962 	/*
1963 	 * Sleep until all the pending operations have completed.
1964 	 *
1965 	 * The caller must ensure that reset has been incremented
1966 	 * or the pending operations may continue being queued.
1967 	 */
1968 	while (sc->sc_rxproc_cnt || sc->sc_txproc_cnt ||
1969 	    sc->sc_txstart_cnt || sc->sc_intr_cnt) {
1970 		if (i <= 0)
1971 			break;
1972 		msleep(sc, &sc->sc_pcu_mtx, 0, "ath_txrx_stop", 1);
1973 		i--;
1974 	}
1975 
1976 	if (i <= 0)
1977 		device_printf(sc->sc_dev,
1978 		    "%s: didn't finish after %d iterations\n",
1979 		    __func__, MAX_TXRX_ITERATIONS);
1980 }
1981 #undef	MAX_TXRX_ITERATIONS
1982 
1983 #if 0
1984 static void
1985 ath_txrx_stop(struct ath_softc *sc)
1986 {
1987 	ATH_UNLOCK_ASSERT(sc);
1988 	ATH_PCU_UNLOCK_ASSERT(sc);
1989 
1990 	ATH_PCU_LOCK(sc);
1991 	ath_txrx_stop_locked(sc);
1992 	ATH_PCU_UNLOCK(sc);
1993 }
1994 #endif
1995 
1996 static void
1997 ath_txrx_start(struct ath_softc *sc)
1998 {
1999 
2000 	taskqueue_unblock(sc->sc_tq);
2001 }
2002 
2003 /*
2004  * Grab the reset lock, and wait around until noone else
2005  * is trying to do anything with it.
2006  *
2007  * This is totally horrible but we can't hold this lock for
2008  * long enough to do TX/RX or we end up with net80211/ip stack
2009  * LORs and eventual deadlock.
2010  *
2011  * "dowait" signals whether to spin, waiting for the reset
2012  * lock count to reach 0. This should (for now) only be used
2013  * during the reset path, as the rest of the code may not
2014  * be locking-reentrant enough to behave correctly.
2015  *
2016  * Another, cleaner way should be found to serialise all of
2017  * these operations.
2018  */
2019 #define	MAX_RESET_ITERATIONS	10
2020 static int
2021 ath_reset_grablock(struct ath_softc *sc, int dowait)
2022 {
2023 	int w = 0;
2024 	int i = MAX_RESET_ITERATIONS;
2025 
2026 	ATH_PCU_LOCK_ASSERT(sc);
2027 	do {
2028 		if (sc->sc_inreset_cnt == 0) {
2029 			w = 1;
2030 			break;
2031 		}
2032 		if (dowait == 0) {
2033 			w = 0;
2034 			break;
2035 		}
2036 		ATH_PCU_UNLOCK(sc);
2037 		pause("ath_reset_grablock", 1);
2038 		i--;
2039 		ATH_PCU_LOCK(sc);
2040 	} while (i > 0);
2041 
2042 	/*
2043 	 * We always increment the refcounter, regardless
2044 	 * of whether we succeeded to get it in an exclusive
2045 	 * way.
2046 	 */
2047 	sc->sc_inreset_cnt++;
2048 
2049 	if (i <= 0)
2050 		device_printf(sc->sc_dev,
2051 		    "%s: didn't finish after %d iterations\n",
2052 		    __func__, MAX_RESET_ITERATIONS);
2053 
2054 	if (w == 0)
2055 		device_printf(sc->sc_dev,
2056 		    "%s: warning, recursive reset path!\n",
2057 		    __func__);
2058 
2059 	return w;
2060 }
2061 #undef MAX_RESET_ITERATIONS
2062 
2063 /*
2064  * XXX TODO: write ath_reset_releaselock
2065  */
2066 
2067 static void
2068 ath_stop(struct ifnet *ifp)
2069 {
2070 	struct ath_softc *sc = ifp->if_softc;
2071 
2072 	ATH_LOCK(sc);
2073 	ath_stop_locked(ifp);
2074 	ATH_UNLOCK(sc);
2075 }
2076 
2077 /*
2078  * Reset the hardware w/o losing operational state.  This is
2079  * basically a more efficient way of doing ath_stop, ath_init,
2080  * followed by state transitions to the current 802.11
2081  * operational state.  Used to recover from various errors and
2082  * to reset or reload hardware state.
2083  */
2084 int
2085 ath_reset(struct ifnet *ifp, ATH_RESET_TYPE reset_type)
2086 {
2087 	struct ath_softc *sc = ifp->if_softc;
2088 	struct ieee80211com *ic = ifp->if_l2com;
2089 	struct ath_hal *ah = sc->sc_ah;
2090 	HAL_STATUS status;
2091 	int i;
2092 
2093 	DPRINTF(sc, ATH_DEBUG_RESET, "%s: called\n", __func__);
2094 
2095 	/* Ensure ATH_LOCK isn't held; ath_rx_proc can't be locked */
2096 	ATH_PCU_UNLOCK_ASSERT(sc);
2097 	ATH_UNLOCK_ASSERT(sc);
2098 
2099 	/* Try to (stop any further TX/RX from occuring */
2100 	taskqueue_block(sc->sc_tq);
2101 
2102 	ATH_PCU_LOCK(sc);
2103 	ath_hal_intrset(ah, 0);		/* disable interrupts */
2104 	ath_txrx_stop_locked(sc);	/* Ensure TX/RX is stopped */
2105 	if (ath_reset_grablock(sc, 1) == 0) {
2106 		device_printf(sc->sc_dev, "%s: concurrent reset! Danger!\n",
2107 		    __func__);
2108 	}
2109 	ATH_PCU_UNLOCK(sc);
2110 
2111 	/*
2112 	 * Should now wait for pending TX/RX to complete
2113 	 * and block future ones from occuring. This needs to be
2114 	 * done before the TX queue is drained.
2115 	 */
2116 	ath_draintxq(sc, reset_type);	/* stop xmit side */
2117 
2118 	/*
2119 	 * Regardless of whether we're doing a no-loss flush or
2120 	 * not, stop the PCU and handle what's in the RX queue.
2121 	 * That way frames aren't dropped which shouldn't be.
2122 	 */
2123 	ath_stoprecv(sc, (reset_type != ATH_RESET_NOLOSS));
2124 	ath_rx_flush(sc);
2125 
2126 	ath_settkipmic(sc);		/* configure TKIP MIC handling */
2127 	/* NB: indicate channel change so we do a full reset */
2128 	if (!ath_hal_reset(ah, sc->sc_opmode, ic->ic_curchan, AH_TRUE, &status))
2129 		if_printf(ifp, "%s: unable to reset hardware; hal status %u\n",
2130 			__func__, status);
2131 	sc->sc_diversity = ath_hal_getdiversity(ah);
2132 
2133 	/* Let DFS at it in case it's a DFS channel */
2134 	ath_dfs_radar_enable(sc, ic->ic_curchan);
2135 
2136 	if (ath_startrecv(sc) != 0)	/* restart recv */
2137 		if_printf(ifp, "%s: unable to start recv logic\n", __func__);
2138 	/*
2139 	 * We may be doing a reset in response to an ioctl
2140 	 * that changes the channel so update any state that
2141 	 * might change as a result.
2142 	 */
2143 	ath_chan_change(sc, ic->ic_curchan);
2144 	if (sc->sc_beacons) {		/* restart beacons */
2145 #ifdef IEEE80211_SUPPORT_TDMA
2146 		if (sc->sc_tdma)
2147 			ath_tdma_config(sc, NULL);
2148 		else
2149 #endif
2150 			ath_beacon_config(sc, NULL);
2151 	}
2152 
2153 	/*
2154 	 * Release the reset lock and re-enable interrupts here.
2155 	 * If an interrupt was being processed in ath_intr(),
2156 	 * it would disable interrupts at this point. So we have
2157 	 * to atomically enable interrupts and decrement the
2158 	 * reset counter - this way ath_intr() doesn't end up
2159 	 * disabling interrupts without a corresponding enable
2160 	 * in the rest or channel change path.
2161 	 */
2162 	ATH_PCU_LOCK(sc);
2163 	sc->sc_inreset_cnt--;
2164 	/* XXX only do this if sc_inreset_cnt == 0? */
2165 	ath_hal_intrset(ah, sc->sc_imask);
2166 	ATH_PCU_UNLOCK(sc);
2167 
2168 	/*
2169 	 * TX and RX can be started here. If it were started with
2170 	 * sc_inreset_cnt > 0, the TX and RX path would abort.
2171 	 * Thus if this is a nested call through the reset or
2172 	 * channel change code, TX completion will occur but
2173 	 * RX completion and ath_start / ath_tx_start will not
2174 	 * run.
2175 	 */
2176 
2177 	/* Restart TX/RX as needed */
2178 	ath_txrx_start(sc);
2179 
2180 	/* XXX Restart TX completion and pending TX */
2181 	if (reset_type == ATH_RESET_NOLOSS) {
2182 		for (i = 0; i < HAL_NUM_TX_QUEUES; i++) {
2183 			if (ATH_TXQ_SETUP(sc, i)) {
2184 				ATH_TXQ_LOCK(&sc->sc_txq[i]);
2185 				ath_txq_restart_dma(sc, &sc->sc_txq[i]);
2186 				ath_txq_sched(sc, &sc->sc_txq[i]);
2187 				ATH_TXQ_UNLOCK(&sc->sc_txq[i]);
2188 			}
2189 		}
2190 	}
2191 
2192 	/*
2193 	 * This may have been set during an ath_start() call which
2194 	 * set this once it detected a concurrent TX was going on.
2195 	 * So, clear it.
2196 	 */
2197 	IF_LOCK(&ifp->if_snd);
2198 	ifp->if_drv_flags &= ~IFF_DRV_OACTIVE;
2199 	IF_UNLOCK(&ifp->if_snd);
2200 
2201 	/* Handle any frames in the TX queue */
2202 	/*
2203 	 * XXX should this be done by the caller, rather than
2204 	 * ath_reset() ?
2205 	 */
2206 	ath_start(ifp);			/* restart xmit */
2207 	return 0;
2208 }
2209 
2210 static int
2211 ath_reset_vap(struct ieee80211vap *vap, u_long cmd)
2212 {
2213 	struct ieee80211com *ic = vap->iv_ic;
2214 	struct ifnet *ifp = ic->ic_ifp;
2215 	struct ath_softc *sc = ifp->if_softc;
2216 	struct ath_hal *ah = sc->sc_ah;
2217 
2218 	switch (cmd) {
2219 	case IEEE80211_IOC_TXPOWER:
2220 		/*
2221 		 * If per-packet TPC is enabled, then we have nothing
2222 		 * to do; otherwise we need to force the global limit.
2223 		 * All this can happen directly; no need to reset.
2224 		 */
2225 		if (!ath_hal_gettpc(ah))
2226 			ath_hal_settxpowlimit(ah, ic->ic_txpowlimit);
2227 		return 0;
2228 	}
2229 	/* XXX? Full or NOLOSS? */
2230 	return ath_reset(ifp, ATH_RESET_FULL);
2231 }
2232 
2233 struct ath_buf *
2234 _ath_getbuf_locked(struct ath_softc *sc, ath_buf_type_t btype)
2235 {
2236 	struct ath_buf *bf;
2237 
2238 	ATH_TXBUF_LOCK_ASSERT(sc);
2239 
2240 	if (btype == ATH_BUFTYPE_MGMT)
2241 		bf = TAILQ_FIRST(&sc->sc_txbuf_mgmt);
2242 	else
2243 		bf = TAILQ_FIRST(&sc->sc_txbuf);
2244 
2245 	if (bf == NULL) {
2246 		sc->sc_stats.ast_tx_getnobuf++;
2247 	} else {
2248 		if (bf->bf_flags & ATH_BUF_BUSY) {
2249 			sc->sc_stats.ast_tx_getbusybuf++;
2250 			bf = NULL;
2251 		}
2252 	}
2253 
2254 	if (bf != NULL && (bf->bf_flags & ATH_BUF_BUSY) == 0) {
2255 		if (btype == ATH_BUFTYPE_MGMT)
2256 			TAILQ_REMOVE(&sc->sc_txbuf_mgmt, bf, bf_list);
2257 		else {
2258 			TAILQ_REMOVE(&sc->sc_txbuf, bf, bf_list);
2259 			sc->sc_txbuf_cnt--;
2260 
2261 			/*
2262 			 * This shuldn't happen; however just to be
2263 			 * safe print a warning and fudge the txbuf
2264 			 * count.
2265 			 */
2266 			if (sc->sc_txbuf_cnt < 0) {
2267 				device_printf(sc->sc_dev,
2268 				    "%s: sc_txbuf_cnt < 0?\n",
2269 				    __func__);
2270 				sc->sc_txbuf_cnt = 0;
2271 			}
2272 		}
2273 	} else
2274 		bf = NULL;
2275 
2276 	if (bf == NULL) {
2277 		/* XXX should check which list, mgmt or otherwise */
2278 		DPRINTF(sc, ATH_DEBUG_XMIT, "%s: %s\n", __func__,
2279 		    TAILQ_FIRST(&sc->sc_txbuf) == NULL ?
2280 			"out of xmit buffers" : "xmit buffer busy");
2281 		return NULL;
2282 	}
2283 
2284 	/* XXX TODO: should do this at buffer list initialisation */
2285 	/* XXX (then, ensure the buffer has the right flag set) */
2286 	if (btype == ATH_BUFTYPE_MGMT)
2287 		bf->bf_flags |= ATH_BUF_MGMT;
2288 	else
2289 		bf->bf_flags &= (~ATH_BUF_MGMT);
2290 
2291 	/* Valid bf here; clear some basic fields */
2292 	bf->bf_next = NULL;	/* XXX just to be sure */
2293 	bf->bf_last = NULL;	/* XXX again, just to be sure */
2294 	bf->bf_comp = NULL;	/* XXX again, just to be sure */
2295 	bzero(&bf->bf_state, sizeof(bf->bf_state));
2296 
2297 	return bf;
2298 }
2299 
2300 /*
2301  * When retrying a software frame, buffers marked ATH_BUF_BUSY
2302  * can't be thrown back on the queue as they could still be
2303  * in use by the hardware.
2304  *
2305  * This duplicates the buffer, or returns NULL.
2306  *
2307  * The descriptor is also copied but the link pointers and
2308  * the DMA segments aren't copied; this frame should thus
2309  * be again passed through the descriptor setup/chain routines
2310  * so the link is correct.
2311  *
2312  * The caller must free the buffer using ath_freebuf().
2313  *
2314  * XXX TODO: this call shouldn't fail as it'll cause packet loss
2315  * XXX in the TX pathway when retries are needed.
2316  * XXX Figure out how to keep some buffers free, or factor the
2317  * XXX number of busy buffers into the xmit path (ath_start())
2318  * XXX so we don't over-commit.
2319  */
2320 struct ath_buf *
2321 ath_buf_clone(struct ath_softc *sc, const struct ath_buf *bf)
2322 {
2323 	struct ath_buf *tbf;
2324 
2325 	tbf = ath_getbuf(sc,
2326 	    (bf->bf_flags & ATH_BUF_MGMT) ?
2327 	     ATH_BUFTYPE_MGMT : ATH_BUFTYPE_NORMAL);
2328 	if (tbf == NULL)
2329 		return NULL;	/* XXX failure? Why? */
2330 
2331 	/* Copy basics */
2332 	tbf->bf_next = NULL;
2333 	tbf->bf_nseg = bf->bf_nseg;
2334 	tbf->bf_flags = bf->bf_flags & ~ATH_BUF_BUSY;
2335 	tbf->bf_status = bf->bf_status;
2336 	tbf->bf_m = bf->bf_m;
2337 	tbf->bf_node = bf->bf_node;
2338 	/* will be setup by the chain/setup function */
2339 	tbf->bf_lastds = NULL;
2340 	/* for now, last == self */
2341 	tbf->bf_last = tbf;
2342 	tbf->bf_comp = bf->bf_comp;
2343 
2344 	/* NOTE: DMA segments will be setup by the setup/chain functions */
2345 
2346 	/* The caller has to re-init the descriptor + links */
2347 
2348 	/* Copy state */
2349 	memcpy(&tbf->bf_state, &bf->bf_state, sizeof(bf->bf_state));
2350 
2351 	return tbf;
2352 }
2353 
2354 struct ath_buf *
2355 ath_getbuf(struct ath_softc *sc, ath_buf_type_t btype)
2356 {
2357 	struct ath_buf *bf;
2358 
2359 	ATH_TXBUF_LOCK(sc);
2360 	bf = _ath_getbuf_locked(sc, btype);
2361 	/*
2362 	 * If a mgmt buffer was requested but we're out of those,
2363 	 * try requesting a normal one.
2364 	 */
2365 	if (bf == NULL && btype == ATH_BUFTYPE_MGMT)
2366 		bf = _ath_getbuf_locked(sc, ATH_BUFTYPE_NORMAL);
2367 	ATH_TXBUF_UNLOCK(sc);
2368 	if (bf == NULL) {
2369 		struct ifnet *ifp = sc->sc_ifp;
2370 
2371 		DPRINTF(sc, ATH_DEBUG_XMIT, "%s: stop queue\n", __func__);
2372 		sc->sc_stats.ast_tx_qstop++;
2373 		IF_LOCK(&ifp->if_snd);
2374 		ifp->if_drv_flags |= IFF_DRV_OACTIVE;
2375 		IF_UNLOCK(&ifp->if_snd);
2376 	}
2377 	return bf;
2378 }
2379 
2380 void
2381 ath_start(struct ifnet *ifp)
2382 {
2383 	struct ath_softc *sc = ifp->if_softc;
2384 	struct ieee80211_node *ni;
2385 	struct ath_buf *bf;
2386 	struct mbuf *m, *next;
2387 	ath_bufhead frags;
2388 
2389 	if ((ifp->if_drv_flags & IFF_DRV_RUNNING) == 0 || sc->sc_invalid)
2390 		return;
2391 
2392 	/* XXX is it ok to hold the ATH_LOCK here? */
2393 	ATH_PCU_LOCK(sc);
2394 	if (sc->sc_inreset_cnt > 0) {
2395 		device_printf(sc->sc_dev,
2396 		    "%s: sc_inreset_cnt > 0; bailing\n", __func__);
2397 		ATH_PCU_UNLOCK(sc);
2398 		IF_LOCK(&ifp->if_snd);
2399 		sc->sc_stats.ast_tx_qstop++;
2400 		ifp->if_drv_flags |= IFF_DRV_OACTIVE;
2401 		IF_UNLOCK(&ifp->if_snd);
2402 		return;
2403 	}
2404 	sc->sc_txstart_cnt++;
2405 	ATH_PCU_UNLOCK(sc);
2406 
2407 	for (;;) {
2408 		ATH_TXBUF_LOCK(sc);
2409 		if (sc->sc_txbuf_cnt <= sc->sc_txq_data_minfree) {
2410 			/* XXX increment counter? */
2411 			ATH_TXBUF_UNLOCK(sc);
2412 			IF_LOCK(&ifp->if_snd);
2413 			ifp->if_drv_flags |= IFF_DRV_OACTIVE;
2414 			IF_UNLOCK(&ifp->if_snd);
2415 			break;
2416 		}
2417 		ATH_TXBUF_UNLOCK(sc);
2418 
2419 		/*
2420 		 * Grab a TX buffer and associated resources.
2421 		 */
2422 		bf = ath_getbuf(sc, ATH_BUFTYPE_NORMAL);
2423 		if (bf == NULL)
2424 			break;
2425 
2426 		IFQ_DEQUEUE(&ifp->if_snd, m);
2427 		if (m == NULL) {
2428 			ATH_TXBUF_LOCK(sc);
2429 			ath_returnbuf_head(sc, bf);
2430 			ATH_TXBUF_UNLOCK(sc);
2431 			break;
2432 		}
2433 		ni = (struct ieee80211_node *) m->m_pkthdr.rcvif;
2434 		/*
2435 		 * Check for fragmentation.  If this frame
2436 		 * has been broken up verify we have enough
2437 		 * buffers to send all the fragments so all
2438 		 * go out or none...
2439 		 */
2440 		TAILQ_INIT(&frags);
2441 		if ((m->m_flags & M_FRAG) &&
2442 		    !ath_txfrag_setup(sc, &frags, m, ni)) {
2443 			DPRINTF(sc, ATH_DEBUG_XMIT,
2444 			    "%s: out of txfrag buffers\n", __func__);
2445 			sc->sc_stats.ast_tx_nofrag++;
2446 			ifp->if_oerrors++;
2447 			ath_freetx(m);
2448 			goto bad;
2449 		}
2450 		ifp->if_opackets++;
2451 	nextfrag:
2452 		/*
2453 		 * Pass the frame to the h/w for transmission.
2454 		 * Fragmented frames have each frag chained together
2455 		 * with m_nextpkt.  We know there are sufficient ath_buf's
2456 		 * to send all the frags because of work done by
2457 		 * ath_txfrag_setup.  We leave m_nextpkt set while
2458 		 * calling ath_tx_start so it can use it to extend the
2459 		 * the tx duration to cover the subsequent frag and
2460 		 * so it can reclaim all the mbufs in case of an error;
2461 		 * ath_tx_start clears m_nextpkt once it commits to
2462 		 * handing the frame to the hardware.
2463 		 */
2464 		next = m->m_nextpkt;
2465 		if (ath_tx_start(sc, ni, bf, m)) {
2466 	bad:
2467 			ifp->if_oerrors++;
2468 	reclaim:
2469 			bf->bf_m = NULL;
2470 			bf->bf_node = NULL;
2471 			ATH_TXBUF_LOCK(sc);
2472 			ath_returnbuf_head(sc, bf);
2473 			ath_txfrag_cleanup(sc, &frags, ni);
2474 			ATH_TXBUF_UNLOCK(sc);
2475 			if (ni != NULL)
2476 				ieee80211_free_node(ni);
2477 			continue;
2478 		}
2479 		if (next != NULL) {
2480 			/*
2481 			 * Beware of state changing between frags.
2482 			 * XXX check sta power-save state?
2483 			 */
2484 			if (ni->ni_vap->iv_state != IEEE80211_S_RUN) {
2485 				DPRINTF(sc, ATH_DEBUG_XMIT,
2486 				    "%s: flush fragmented packet, state %s\n",
2487 				    __func__,
2488 				    ieee80211_state_name[ni->ni_vap->iv_state]);
2489 				ath_freetx(next);
2490 				goto reclaim;
2491 			}
2492 			m = next;
2493 			bf = TAILQ_FIRST(&frags);
2494 			KASSERT(bf != NULL, ("no buf for txfrag"));
2495 			TAILQ_REMOVE(&frags, bf, bf_list);
2496 			goto nextfrag;
2497 		}
2498 
2499 		sc->sc_wd_timer = 5;
2500 	}
2501 
2502 	ATH_PCU_LOCK(sc);
2503 	sc->sc_txstart_cnt--;
2504 	ATH_PCU_UNLOCK(sc);
2505 }
2506 
2507 static int
2508 ath_media_change(struct ifnet *ifp)
2509 {
2510 	int error = ieee80211_media_change(ifp);
2511 	/* NB: only the fixed rate can change and that doesn't need a reset */
2512 	return (error == ENETRESET ? 0 : error);
2513 }
2514 
2515 /*
2516  * Block/unblock tx+rx processing while a key change is done.
2517  * We assume the caller serializes key management operations
2518  * so we only need to worry about synchronization with other
2519  * uses that originate in the driver.
2520  */
2521 static void
2522 ath_key_update_begin(struct ieee80211vap *vap)
2523 {
2524 	struct ifnet *ifp = vap->iv_ic->ic_ifp;
2525 	struct ath_softc *sc = ifp->if_softc;
2526 
2527 	DPRINTF(sc, ATH_DEBUG_KEYCACHE, "%s:\n", __func__);
2528 	taskqueue_block(sc->sc_tq);
2529 	IF_LOCK(&ifp->if_snd);		/* NB: doesn't block mgmt frames */
2530 }
2531 
2532 static void
2533 ath_key_update_end(struct ieee80211vap *vap)
2534 {
2535 	struct ifnet *ifp = vap->iv_ic->ic_ifp;
2536 	struct ath_softc *sc = ifp->if_softc;
2537 
2538 	DPRINTF(sc, ATH_DEBUG_KEYCACHE, "%s:\n", __func__);
2539 	IF_UNLOCK(&ifp->if_snd);
2540 	taskqueue_unblock(sc->sc_tq);
2541 }
2542 
2543 static void
2544 ath_update_promisc(struct ifnet *ifp)
2545 {
2546 	struct ath_softc *sc = ifp->if_softc;
2547 	u_int32_t rfilt;
2548 
2549 	/* configure rx filter */
2550 	rfilt = ath_calcrxfilter(sc);
2551 	ath_hal_setrxfilter(sc->sc_ah, rfilt);
2552 
2553 	DPRINTF(sc, ATH_DEBUG_MODE, "%s: RX filter 0x%x\n", __func__, rfilt);
2554 }
2555 
2556 static void
2557 ath_update_mcast(struct ifnet *ifp)
2558 {
2559 	struct ath_softc *sc = ifp->if_softc;
2560 	u_int32_t mfilt[2];
2561 
2562 	/* calculate and install multicast filter */
2563 	if ((ifp->if_flags & IFF_ALLMULTI) == 0) {
2564 		struct ifmultiaddr *ifma;
2565 		/*
2566 		 * Merge multicast addresses to form the hardware filter.
2567 		 */
2568 		mfilt[0] = mfilt[1] = 0;
2569 		if_maddr_rlock(ifp);	/* XXX need some fiddling to remove? */
2570 		TAILQ_FOREACH(ifma, &ifp->if_multiaddrs, ifma_link) {
2571 			caddr_t dl;
2572 			u_int32_t val;
2573 			u_int8_t pos;
2574 
2575 			/* calculate XOR of eight 6bit values */
2576 			dl = LLADDR((struct sockaddr_dl *) ifma->ifma_addr);
2577 			val = LE_READ_4(dl + 0);
2578 			pos = (val >> 18) ^ (val >> 12) ^ (val >> 6) ^ val;
2579 			val = LE_READ_4(dl + 3);
2580 			pos ^= (val >> 18) ^ (val >> 12) ^ (val >> 6) ^ val;
2581 			pos &= 0x3f;
2582 			mfilt[pos / 32] |= (1 << (pos % 32));
2583 		}
2584 		if_maddr_runlock(ifp);
2585 	} else
2586 		mfilt[0] = mfilt[1] = ~0;
2587 	ath_hal_setmcastfilter(sc->sc_ah, mfilt[0], mfilt[1]);
2588 	DPRINTF(sc, ATH_DEBUG_MODE, "%s: MC filter %08x:%08x\n",
2589 		__func__, mfilt[0], mfilt[1]);
2590 }
2591 
2592 void
2593 ath_mode_init(struct ath_softc *sc)
2594 {
2595 	struct ifnet *ifp = sc->sc_ifp;
2596 	struct ath_hal *ah = sc->sc_ah;
2597 	u_int32_t rfilt;
2598 
2599 	/* configure rx filter */
2600 	rfilt = ath_calcrxfilter(sc);
2601 	ath_hal_setrxfilter(ah, rfilt);
2602 
2603 	/* configure operational mode */
2604 	ath_hal_setopmode(ah);
2605 
2606 	DPRINTF(sc, ATH_DEBUG_STATE | ATH_DEBUG_MODE,
2607 	    "%s: ah=%p, ifp=%p, if_addr=%p\n",
2608 	    __func__,
2609 	    ah,
2610 	    ifp,
2611 	    (ifp == NULL) ? NULL : ifp->if_addr);
2612 
2613 	/* handle any link-level address change */
2614 	ath_hal_setmac(ah, IF_LLADDR(ifp));
2615 
2616 	/* calculate and install multicast filter */
2617 	ath_update_mcast(ifp);
2618 }
2619 
2620 /*
2621  * Set the slot time based on the current setting.
2622  */
2623 void
2624 ath_setslottime(struct ath_softc *sc)
2625 {
2626 	struct ieee80211com *ic = sc->sc_ifp->if_l2com;
2627 	struct ath_hal *ah = sc->sc_ah;
2628 	u_int usec;
2629 
2630 	if (IEEE80211_IS_CHAN_HALF(ic->ic_curchan))
2631 		usec = 13;
2632 	else if (IEEE80211_IS_CHAN_QUARTER(ic->ic_curchan))
2633 		usec = 21;
2634 	else if (IEEE80211_IS_CHAN_ANYG(ic->ic_curchan)) {
2635 		/* honor short/long slot time only in 11g */
2636 		/* XXX shouldn't honor on pure g or turbo g channel */
2637 		if (ic->ic_flags & IEEE80211_F_SHSLOT)
2638 			usec = HAL_SLOT_TIME_9;
2639 		else
2640 			usec = HAL_SLOT_TIME_20;
2641 	} else
2642 		usec = HAL_SLOT_TIME_9;
2643 
2644 	DPRINTF(sc, ATH_DEBUG_RESET,
2645 	    "%s: chan %u MHz flags 0x%x %s slot, %u usec\n",
2646 	    __func__, ic->ic_curchan->ic_freq, ic->ic_curchan->ic_flags,
2647 	    ic->ic_flags & IEEE80211_F_SHSLOT ? "short" : "long", usec);
2648 
2649 	ath_hal_setslottime(ah, usec);
2650 	sc->sc_updateslot = OK;
2651 }
2652 
2653 /*
2654  * Callback from the 802.11 layer to update the
2655  * slot time based on the current setting.
2656  */
2657 static void
2658 ath_updateslot(struct ifnet *ifp)
2659 {
2660 	struct ath_softc *sc = ifp->if_softc;
2661 	struct ieee80211com *ic = ifp->if_l2com;
2662 
2663 	/*
2664 	 * When not coordinating the BSS, change the hardware
2665 	 * immediately.  For other operation we defer the change
2666 	 * until beacon updates have propagated to the stations.
2667 	 */
2668 	if (ic->ic_opmode == IEEE80211_M_HOSTAP ||
2669 	    ic->ic_opmode == IEEE80211_M_MBSS)
2670 		sc->sc_updateslot = UPDATE;
2671 	else
2672 		ath_setslottime(sc);
2673 }
2674 
2675 /*
2676  * Append the contents of src to dst; both queues
2677  * are assumed to be locked.
2678  */
2679 void
2680 ath_txqmove(struct ath_txq *dst, struct ath_txq *src)
2681 {
2682 
2683 	ATH_TXQ_LOCK_ASSERT(dst);
2684 	ATH_TXQ_LOCK_ASSERT(src);
2685 
2686 	TAILQ_CONCAT(&dst->axq_q, &src->axq_q, bf_list);
2687 	dst->axq_link = src->axq_link;
2688 	src->axq_link = NULL;
2689 	dst->axq_depth += src->axq_depth;
2690 	dst->axq_aggr_depth += src->axq_aggr_depth;
2691 	src->axq_depth = 0;
2692 	src->axq_aggr_depth = 0;
2693 }
2694 
2695 /*
2696  * Reset the hardware, with no loss.
2697  *
2698  * This can't be used for a general case reset.
2699  */
2700 static void
2701 ath_reset_proc(void *arg, int pending)
2702 {
2703 	struct ath_softc *sc = arg;
2704 	struct ifnet *ifp = sc->sc_ifp;
2705 
2706 #if 0
2707 	if_printf(ifp, "%s: resetting\n", __func__);
2708 #endif
2709 	ath_reset(ifp, ATH_RESET_NOLOSS);
2710 }
2711 
2712 /*
2713  * Reset the hardware after detecting beacons have stopped.
2714  */
2715 static void
2716 ath_bstuck_proc(void *arg, int pending)
2717 {
2718 	struct ath_softc *sc = arg;
2719 	struct ifnet *ifp = sc->sc_ifp;
2720 	uint32_t hangs = 0;
2721 
2722 	if (ath_hal_gethangstate(sc->sc_ah, 0xff, &hangs) && hangs != 0)
2723 		if_printf(ifp, "bb hang detected (0x%x)\n", hangs);
2724 
2725 	if_printf(ifp, "stuck beacon; resetting (bmiss count %u)\n",
2726 		sc->sc_bmisscount);
2727 	sc->sc_stats.ast_bstuck++;
2728 	/*
2729 	 * This assumes that there's no simultaneous channel mode change
2730 	 * occuring.
2731 	 */
2732 	ath_reset(ifp, ATH_RESET_NOLOSS);
2733 }
2734 
2735 static void
2736 ath_load_cb(void *arg, bus_dma_segment_t *segs, int nsegs, int error)
2737 {
2738 	bus_addr_t *paddr = (bus_addr_t*) arg;
2739 	KASSERT(error == 0, ("error %u on bus_dma callback", error));
2740 	*paddr = segs->ds_addr;
2741 }
2742 
2743 int
2744 ath_descdma_setup(struct ath_softc *sc,
2745 	struct ath_descdma *dd, ath_bufhead *head,
2746 	const char *name, int nbuf, int ndesc)
2747 {
2748 #define	DS2PHYS(_dd, _ds) \
2749 	((_dd)->dd_desc_paddr + ((caddr_t)(_ds) - (caddr_t)(_dd)->dd_desc))
2750 #define	ATH_DESC_4KB_BOUND_CHECK(_daddr, _len) \
2751 	((((u_int32_t)(_daddr) & 0xFFF) > (0x1000 - (_len))) ? 1 : 0)
2752 	struct ifnet *ifp = sc->sc_ifp;
2753 	uint8_t *ds;
2754 	struct ath_buf *bf;
2755 	int i, bsize, error;
2756 	int desc_len;
2757 
2758 	desc_len = sizeof(struct ath_desc);
2759 
2760 	DPRINTF(sc, ATH_DEBUG_RESET, "%s: %s DMA: %u buffers %u desc/buf\n",
2761 	    __func__, name, nbuf, ndesc);
2762 
2763 	dd->dd_name = name;
2764 	dd->dd_desc_len = desc_len * nbuf * ndesc;
2765 
2766 	/*
2767 	 * Merlin work-around:
2768 	 * Descriptors that cross the 4KB boundary can't be used.
2769 	 * Assume one skipped descriptor per 4KB page.
2770 	 */
2771 	if (! ath_hal_split4ktrans(sc->sc_ah)) {
2772 		int numdescpage = 4096 / (desc_len * ndesc);
2773 		dd->dd_desc_len = (nbuf / numdescpage + 1) * 4096;
2774 	}
2775 
2776 	/*
2777 	 * Setup DMA descriptor area.
2778 	 */
2779 	error = bus_dma_tag_create(bus_get_dma_tag(sc->sc_dev),	/* parent */
2780 		       PAGE_SIZE, 0,		/* alignment, bounds */
2781 		       BUS_SPACE_MAXADDR_32BIT,	/* lowaddr */
2782 		       BUS_SPACE_MAXADDR,	/* highaddr */
2783 		       NULL, NULL,		/* filter, filterarg */
2784 		       dd->dd_desc_len,		/* maxsize */
2785 		       1,			/* nsegments */
2786 		       dd->dd_desc_len,		/* maxsegsize */
2787 		       BUS_DMA_ALLOCNOW,	/* flags */
2788 		       NULL,			/* lockfunc */
2789 		       NULL,			/* lockarg */
2790 		       &dd->dd_dmat);
2791 	if (error != 0) {
2792 		if_printf(ifp, "cannot allocate %s DMA tag\n", dd->dd_name);
2793 		return error;
2794 	}
2795 
2796 	/* allocate descriptors */
2797 	error = bus_dmamap_create(dd->dd_dmat, BUS_DMA_NOWAIT, &dd->dd_dmamap);
2798 	if (error != 0) {
2799 		if_printf(ifp, "unable to create dmamap for %s descriptors, "
2800 			"error %u\n", dd->dd_name, error);
2801 		goto fail0;
2802 	}
2803 
2804 	error = bus_dmamem_alloc(dd->dd_dmat, (void**) &dd->dd_desc,
2805 				 BUS_DMA_NOWAIT | BUS_DMA_COHERENT,
2806 				 &dd->dd_dmamap);
2807 	if (error != 0) {
2808 		if_printf(ifp, "unable to alloc memory for %u %s descriptors, "
2809 			"error %u\n", nbuf * ndesc, dd->dd_name, error);
2810 		goto fail1;
2811 	}
2812 
2813 	error = bus_dmamap_load(dd->dd_dmat, dd->dd_dmamap,
2814 				dd->dd_desc, dd->dd_desc_len,
2815 				ath_load_cb, &dd->dd_desc_paddr,
2816 				BUS_DMA_NOWAIT);
2817 	if (error != 0) {
2818 		if_printf(ifp, "unable to map %s descriptors, error %u\n",
2819 			dd->dd_name, error);
2820 		goto fail2;
2821 	}
2822 
2823 	ds = (uint8_t *) dd->dd_desc;
2824 	DPRINTF(sc, ATH_DEBUG_RESET, "%s: %s DMA map: %p (%lu) -> %p (%lu)\n",
2825 	    __func__, dd->dd_name, ds, (u_long) dd->dd_desc_len,
2826 	    (caddr_t) dd->dd_desc_paddr, /*XXX*/ (u_long) dd->dd_desc_len);
2827 
2828 	/* allocate rx buffers */
2829 	bsize = sizeof(struct ath_buf) * nbuf;
2830 	bf = malloc(bsize, M_ATHDEV, M_NOWAIT | M_ZERO);
2831 	if (bf == NULL) {
2832 		if_printf(ifp, "malloc of %s buffers failed, size %u\n",
2833 			dd->dd_name, bsize);
2834 		goto fail3;
2835 	}
2836 	dd->dd_bufptr = bf;
2837 
2838 	TAILQ_INIT(head);
2839 	for (i = 0; i < nbuf; i++, bf++, ds += (ndesc * desc_len)) {
2840 		bf->bf_desc = (struct ath_desc *) ds;
2841 		bf->bf_daddr = DS2PHYS(dd, ds);
2842 		if (! ath_hal_split4ktrans(sc->sc_ah)) {
2843 			/*
2844 			 * Merlin WAR: Skip descriptor addresses which
2845 			 * cause 4KB boundary crossing along any point
2846 			 * in the descriptor.
2847 			 */
2848 			 if (ATH_DESC_4KB_BOUND_CHECK(bf->bf_daddr,
2849 			     desc_len * ndesc)) {
2850 				/* Start at the next page */
2851 				ds += 0x1000 - (bf->bf_daddr & 0xFFF);
2852 				bf->bf_desc = (struct ath_desc *) ds;
2853 				bf->bf_daddr = DS2PHYS(dd, ds);
2854 			}
2855 		}
2856 		error = bus_dmamap_create(sc->sc_dmat, BUS_DMA_NOWAIT,
2857 				&bf->bf_dmamap);
2858 		if (error != 0) {
2859 			if_printf(ifp, "unable to create dmamap for %s "
2860 				"buffer %u, error %u\n", dd->dd_name, i, error);
2861 			ath_descdma_cleanup(sc, dd, head);
2862 			return error;
2863 		}
2864 		bf->bf_lastds = bf->bf_desc;	/* Just an initial value */
2865 		TAILQ_INSERT_TAIL(head, bf, bf_list);
2866 	}
2867 	return 0;
2868 fail3:
2869 	bus_dmamap_unload(dd->dd_dmat, dd->dd_dmamap);
2870 fail2:
2871 	bus_dmamem_free(dd->dd_dmat, dd->dd_desc, dd->dd_dmamap);
2872 fail1:
2873 	bus_dmamap_destroy(dd->dd_dmat, dd->dd_dmamap);
2874 fail0:
2875 	bus_dma_tag_destroy(dd->dd_dmat);
2876 	memset(dd, 0, sizeof(*dd));
2877 	return error;
2878 #undef DS2PHYS
2879 #undef ATH_DESC_4KB_BOUND_CHECK
2880 }
2881 
2882 void
2883 ath_descdma_cleanup(struct ath_softc *sc,
2884 	struct ath_descdma *dd, ath_bufhead *head)
2885 {
2886 	struct ath_buf *bf;
2887 	struct ieee80211_node *ni;
2888 
2889 	bus_dmamap_unload(dd->dd_dmat, dd->dd_dmamap);
2890 	bus_dmamem_free(dd->dd_dmat, dd->dd_desc, dd->dd_dmamap);
2891 	bus_dmamap_destroy(dd->dd_dmat, dd->dd_dmamap);
2892 	bus_dma_tag_destroy(dd->dd_dmat);
2893 
2894 	TAILQ_FOREACH(bf, head, bf_list) {
2895 		if (bf->bf_m) {
2896 			m_freem(bf->bf_m);
2897 			bf->bf_m = NULL;
2898 		}
2899 		if (bf->bf_dmamap != NULL) {
2900 			bus_dmamap_destroy(sc->sc_dmat, bf->bf_dmamap);
2901 			bf->bf_dmamap = NULL;
2902 		}
2903 		ni = bf->bf_node;
2904 		bf->bf_node = NULL;
2905 		if (ni != NULL) {
2906 			/*
2907 			 * Reclaim node reference.
2908 			 */
2909 			ieee80211_free_node(ni);
2910 		}
2911 	}
2912 
2913 	TAILQ_INIT(head);
2914 	free(dd->dd_bufptr, M_ATHDEV);
2915 	memset(dd, 0, sizeof(*dd));
2916 }
2917 
2918 static int
2919 ath_desc_alloc(struct ath_softc *sc)
2920 {
2921 	int error;
2922 
2923 	error = ath_descdma_setup(sc, &sc->sc_txdma, &sc->sc_txbuf,
2924 			"tx", ath_txbuf, ATH_TXDESC);
2925 	if (error != 0) {
2926 		return error;
2927 	}
2928 	sc->sc_txbuf_cnt = ath_txbuf;
2929 
2930 	error = ath_descdma_setup(sc, &sc->sc_txdma_mgmt, &sc->sc_txbuf_mgmt,
2931 			"tx_mgmt", ath_txbuf_mgmt, ATH_TXDESC);
2932 	if (error != 0) {
2933 		ath_descdma_cleanup(sc, &sc->sc_txdma, &sc->sc_txbuf);
2934 		return error;
2935 	}
2936 
2937 	/*
2938 	 * XXX mark txbuf_mgmt frames with ATH_BUF_MGMT, so the
2939 	 * flag doesn't have to be set in ath_getbuf_locked().
2940 	 */
2941 
2942 	error = ath_descdma_setup(sc, &sc->sc_bdma, &sc->sc_bbuf,
2943 			"beacon", ATH_BCBUF, 1);
2944 	if (error != 0) {
2945 		ath_descdma_cleanup(sc, &sc->sc_txdma, &sc->sc_txbuf);
2946 		ath_descdma_cleanup(sc, &sc->sc_txdma_mgmt,
2947 		    &sc->sc_txbuf_mgmt);
2948 		return error;
2949 	}
2950 	return 0;
2951 }
2952 
2953 static void
2954 ath_desc_free(struct ath_softc *sc)
2955 {
2956 
2957 	if (sc->sc_bdma.dd_desc_len != 0)
2958 		ath_descdma_cleanup(sc, &sc->sc_bdma, &sc->sc_bbuf);
2959 	if (sc->sc_txdma.dd_desc_len != 0)
2960 		ath_descdma_cleanup(sc, &sc->sc_txdma, &sc->sc_txbuf);
2961 	if (sc->sc_txdma_mgmt.dd_desc_len != 0)
2962 		ath_descdma_cleanup(sc, &sc->sc_txdma_mgmt,
2963 		    &sc->sc_txbuf_mgmt);
2964 }
2965 
2966 static struct ieee80211_node *
2967 ath_node_alloc(struct ieee80211vap *vap, const uint8_t mac[IEEE80211_ADDR_LEN])
2968 {
2969 	struct ieee80211com *ic = vap->iv_ic;
2970 	struct ath_softc *sc = ic->ic_ifp->if_softc;
2971 	const size_t space = sizeof(struct ath_node) + sc->sc_rc->arc_space;
2972 	struct ath_node *an;
2973 
2974 	an = malloc(space, M_80211_NODE, M_NOWAIT|M_ZERO);
2975 	if (an == NULL) {
2976 		/* XXX stat+msg */
2977 		return NULL;
2978 	}
2979 	ath_rate_node_init(sc, an);
2980 
2981 	/* Setup the mutex - there's no associd yet so set the name to NULL */
2982 	snprintf(an->an_name, sizeof(an->an_name), "%s: node %p",
2983 	    device_get_nameunit(sc->sc_dev), an);
2984 	mtx_init(&an->an_mtx, an->an_name, NULL, MTX_DEF);
2985 
2986 	/* XXX setup ath_tid */
2987 	ath_tx_tid_init(sc, an);
2988 
2989 	DPRINTF(sc, ATH_DEBUG_NODE, "%s: an %p\n", __func__, an);
2990 	return &an->an_node;
2991 }
2992 
2993 static void
2994 ath_node_cleanup(struct ieee80211_node *ni)
2995 {
2996 	struct ieee80211com *ic = ni->ni_ic;
2997 	struct ath_softc *sc = ic->ic_ifp->if_softc;
2998 
2999 	/* Cleanup ath_tid, free unused bufs, unlink bufs in TXQ */
3000 	ath_tx_node_flush(sc, ATH_NODE(ni));
3001 	ath_rate_node_cleanup(sc, ATH_NODE(ni));
3002 	sc->sc_node_cleanup(ni);
3003 }
3004 
3005 static void
3006 ath_node_free(struct ieee80211_node *ni)
3007 {
3008 	struct ieee80211com *ic = ni->ni_ic;
3009 	struct ath_softc *sc = ic->ic_ifp->if_softc;
3010 
3011 	DPRINTF(sc, ATH_DEBUG_NODE, "%s: ni %p\n", __func__, ni);
3012 	mtx_destroy(&ATH_NODE(ni)->an_mtx);
3013 	sc->sc_node_free(ni);
3014 }
3015 
3016 static void
3017 ath_node_getsignal(const struct ieee80211_node *ni, int8_t *rssi, int8_t *noise)
3018 {
3019 	struct ieee80211com *ic = ni->ni_ic;
3020 	struct ath_softc *sc = ic->ic_ifp->if_softc;
3021 	struct ath_hal *ah = sc->sc_ah;
3022 
3023 	*rssi = ic->ic_node_getrssi(ni);
3024 	if (ni->ni_chan != IEEE80211_CHAN_ANYC)
3025 		*noise = ath_hal_getchannoise(ah, ni->ni_chan);
3026 	else
3027 		*noise = -95;		/* nominally correct */
3028 }
3029 
3030 /*
3031  * Set the default antenna.
3032  */
3033 void
3034 ath_setdefantenna(struct ath_softc *sc, u_int antenna)
3035 {
3036 	struct ath_hal *ah = sc->sc_ah;
3037 
3038 	/* XXX block beacon interrupts */
3039 	ath_hal_setdefantenna(ah, antenna);
3040 	if (sc->sc_defant != antenna)
3041 		sc->sc_stats.ast_ant_defswitch++;
3042 	sc->sc_defant = antenna;
3043 	sc->sc_rxotherant = 0;
3044 }
3045 
3046 static void
3047 ath_txq_init(struct ath_softc *sc, struct ath_txq *txq, int qnum)
3048 {
3049 	txq->axq_qnum = qnum;
3050 	txq->axq_ac = 0;
3051 	txq->axq_depth = 0;
3052 	txq->axq_aggr_depth = 0;
3053 	txq->axq_intrcnt = 0;
3054 	txq->axq_link = NULL;
3055 	txq->axq_softc = sc;
3056 	TAILQ_INIT(&txq->axq_q);
3057 	TAILQ_INIT(&txq->axq_tidq);
3058 	ATH_TXQ_LOCK_INIT(sc, txq);
3059 }
3060 
3061 /*
3062  * Setup a h/w transmit queue.
3063  */
3064 static struct ath_txq *
3065 ath_txq_setup(struct ath_softc *sc, int qtype, int subtype)
3066 {
3067 #define	N(a)	(sizeof(a)/sizeof(a[0]))
3068 	struct ath_hal *ah = sc->sc_ah;
3069 	HAL_TXQ_INFO qi;
3070 	int qnum;
3071 
3072 	memset(&qi, 0, sizeof(qi));
3073 	qi.tqi_subtype = subtype;
3074 	qi.tqi_aifs = HAL_TXQ_USEDEFAULT;
3075 	qi.tqi_cwmin = HAL_TXQ_USEDEFAULT;
3076 	qi.tqi_cwmax = HAL_TXQ_USEDEFAULT;
3077 	/*
3078 	 * Enable interrupts only for EOL and DESC conditions.
3079 	 * We mark tx descriptors to receive a DESC interrupt
3080 	 * when a tx queue gets deep; otherwise waiting for the
3081 	 * EOL to reap descriptors.  Note that this is done to
3082 	 * reduce interrupt load and this only defers reaping
3083 	 * descriptors, never transmitting frames.  Aside from
3084 	 * reducing interrupts this also permits more concurrency.
3085 	 * The only potential downside is if the tx queue backs
3086 	 * up in which case the top half of the kernel may backup
3087 	 * due to a lack of tx descriptors.
3088 	 */
3089 	qi.tqi_qflags = HAL_TXQ_TXEOLINT_ENABLE | HAL_TXQ_TXDESCINT_ENABLE;
3090 	qnum = ath_hal_setuptxqueue(ah, qtype, &qi);
3091 	if (qnum == -1) {
3092 		/*
3093 		 * NB: don't print a message, this happens
3094 		 * normally on parts with too few tx queues
3095 		 */
3096 		return NULL;
3097 	}
3098 	if (qnum >= N(sc->sc_txq)) {
3099 		device_printf(sc->sc_dev,
3100 			"hal qnum %u out of range, max %zu!\n",
3101 			qnum, N(sc->sc_txq));
3102 		ath_hal_releasetxqueue(ah, qnum);
3103 		return NULL;
3104 	}
3105 	if (!ATH_TXQ_SETUP(sc, qnum)) {
3106 		ath_txq_init(sc, &sc->sc_txq[qnum], qnum);
3107 		sc->sc_txqsetup |= 1<<qnum;
3108 	}
3109 	return &sc->sc_txq[qnum];
3110 #undef N
3111 }
3112 
3113 /*
3114  * Setup a hardware data transmit queue for the specified
3115  * access control.  The hal may not support all requested
3116  * queues in which case it will return a reference to a
3117  * previously setup queue.  We record the mapping from ac's
3118  * to h/w queues for use by ath_tx_start and also track
3119  * the set of h/w queues being used to optimize work in the
3120  * transmit interrupt handler and related routines.
3121  */
3122 static int
3123 ath_tx_setup(struct ath_softc *sc, int ac, int haltype)
3124 {
3125 #define	N(a)	(sizeof(a)/sizeof(a[0]))
3126 	struct ath_txq *txq;
3127 
3128 	if (ac >= N(sc->sc_ac2q)) {
3129 		device_printf(sc->sc_dev, "AC %u out of range, max %zu!\n",
3130 			ac, N(sc->sc_ac2q));
3131 		return 0;
3132 	}
3133 	txq = ath_txq_setup(sc, HAL_TX_QUEUE_DATA, haltype);
3134 	if (txq != NULL) {
3135 		txq->axq_ac = ac;
3136 		sc->sc_ac2q[ac] = txq;
3137 		return 1;
3138 	} else
3139 		return 0;
3140 #undef N
3141 }
3142 
3143 /*
3144  * Update WME parameters for a transmit queue.
3145  */
3146 static int
3147 ath_txq_update(struct ath_softc *sc, int ac)
3148 {
3149 #define	ATH_EXPONENT_TO_VALUE(v)	((1<<v)-1)
3150 #define	ATH_TXOP_TO_US(v)		(v<<5)
3151 	struct ifnet *ifp = sc->sc_ifp;
3152 	struct ieee80211com *ic = ifp->if_l2com;
3153 	struct ath_txq *txq = sc->sc_ac2q[ac];
3154 	struct wmeParams *wmep = &ic->ic_wme.wme_chanParams.cap_wmeParams[ac];
3155 	struct ath_hal *ah = sc->sc_ah;
3156 	HAL_TXQ_INFO qi;
3157 
3158 	ath_hal_gettxqueueprops(ah, txq->axq_qnum, &qi);
3159 #ifdef IEEE80211_SUPPORT_TDMA
3160 	if (sc->sc_tdma) {
3161 		/*
3162 		 * AIFS is zero so there's no pre-transmit wait.  The
3163 		 * burst time defines the slot duration and is configured
3164 		 * through net80211.  The QCU is setup to not do post-xmit
3165 		 * back off, lockout all lower-priority QCU's, and fire
3166 		 * off the DMA beacon alert timer which is setup based
3167 		 * on the slot configuration.
3168 		 */
3169 		qi.tqi_qflags = HAL_TXQ_TXOKINT_ENABLE
3170 			      | HAL_TXQ_TXERRINT_ENABLE
3171 			      | HAL_TXQ_TXURNINT_ENABLE
3172 			      | HAL_TXQ_TXEOLINT_ENABLE
3173 			      | HAL_TXQ_DBA_GATED
3174 			      | HAL_TXQ_BACKOFF_DISABLE
3175 			      | HAL_TXQ_ARB_LOCKOUT_GLOBAL
3176 			      ;
3177 		qi.tqi_aifs = 0;
3178 		/* XXX +dbaprep? */
3179 		qi.tqi_readyTime = sc->sc_tdmaslotlen;
3180 		qi.tqi_burstTime = qi.tqi_readyTime;
3181 	} else {
3182 #endif
3183 		/*
3184 		 * XXX shouldn't this just use the default flags
3185 		 * used in the previous queue setup?
3186 		 */
3187 		qi.tqi_qflags = HAL_TXQ_TXOKINT_ENABLE
3188 			      | HAL_TXQ_TXERRINT_ENABLE
3189 			      | HAL_TXQ_TXDESCINT_ENABLE
3190 			      | HAL_TXQ_TXURNINT_ENABLE
3191 			      | HAL_TXQ_TXEOLINT_ENABLE
3192 			      ;
3193 		qi.tqi_aifs = wmep->wmep_aifsn;
3194 		qi.tqi_cwmin = ATH_EXPONENT_TO_VALUE(wmep->wmep_logcwmin);
3195 		qi.tqi_cwmax = ATH_EXPONENT_TO_VALUE(wmep->wmep_logcwmax);
3196 		qi.tqi_readyTime = 0;
3197 		qi.tqi_burstTime = ATH_TXOP_TO_US(wmep->wmep_txopLimit);
3198 #ifdef IEEE80211_SUPPORT_TDMA
3199 	}
3200 #endif
3201 
3202 	DPRINTF(sc, ATH_DEBUG_RESET,
3203 	    "%s: Q%u qflags 0x%x aifs %u cwmin %u cwmax %u burstTime %u\n",
3204 	    __func__, txq->axq_qnum, qi.tqi_qflags,
3205 	    qi.tqi_aifs, qi.tqi_cwmin, qi.tqi_cwmax, qi.tqi_burstTime);
3206 
3207 	if (!ath_hal_settxqueueprops(ah, txq->axq_qnum, &qi)) {
3208 		if_printf(ifp, "unable to update hardware queue "
3209 			"parameters for %s traffic!\n",
3210 			ieee80211_wme_acnames[ac]);
3211 		return 0;
3212 	} else {
3213 		ath_hal_resettxqueue(ah, txq->axq_qnum); /* push to h/w */
3214 		return 1;
3215 	}
3216 #undef ATH_TXOP_TO_US
3217 #undef ATH_EXPONENT_TO_VALUE
3218 }
3219 
3220 /*
3221  * Callback from the 802.11 layer to update WME parameters.
3222  */
3223 int
3224 ath_wme_update(struct ieee80211com *ic)
3225 {
3226 	struct ath_softc *sc = ic->ic_ifp->if_softc;
3227 
3228 	return !ath_txq_update(sc, WME_AC_BE) ||
3229 	    !ath_txq_update(sc, WME_AC_BK) ||
3230 	    !ath_txq_update(sc, WME_AC_VI) ||
3231 	    !ath_txq_update(sc, WME_AC_VO) ? EIO : 0;
3232 }
3233 
3234 /*
3235  * Reclaim resources for a setup queue.
3236  */
3237 static void
3238 ath_tx_cleanupq(struct ath_softc *sc, struct ath_txq *txq)
3239 {
3240 
3241 	ath_hal_releasetxqueue(sc->sc_ah, txq->axq_qnum);
3242 	ATH_TXQ_LOCK_DESTROY(txq);
3243 	sc->sc_txqsetup &= ~(1<<txq->axq_qnum);
3244 }
3245 
3246 /*
3247  * Reclaim all tx queue resources.
3248  */
3249 static void
3250 ath_tx_cleanup(struct ath_softc *sc)
3251 {
3252 	int i;
3253 
3254 	ATH_TXBUF_LOCK_DESTROY(sc);
3255 	for (i = 0; i < HAL_NUM_TX_QUEUES; i++)
3256 		if (ATH_TXQ_SETUP(sc, i))
3257 			ath_tx_cleanupq(sc, &sc->sc_txq[i]);
3258 }
3259 
3260 /*
3261  * Return h/w rate index for an IEEE rate (w/o basic rate bit)
3262  * using the current rates in sc_rixmap.
3263  */
3264 int
3265 ath_tx_findrix(const struct ath_softc *sc, uint8_t rate)
3266 {
3267 	int rix = sc->sc_rixmap[rate];
3268 	/* NB: return lowest rix for invalid rate */
3269 	return (rix == 0xff ? 0 : rix);
3270 }
3271 
3272 static void
3273 ath_tx_update_stats(struct ath_softc *sc, struct ath_tx_status *ts,
3274     struct ath_buf *bf)
3275 {
3276 	struct ieee80211_node *ni = bf->bf_node;
3277 	struct ifnet *ifp = sc->sc_ifp;
3278 	struct ieee80211com *ic = ifp->if_l2com;
3279 	int sr, lr, pri;
3280 
3281 	if (ts->ts_status == 0) {
3282 		u_int8_t txant = ts->ts_antenna;
3283 		sc->sc_stats.ast_ant_tx[txant]++;
3284 		sc->sc_ant_tx[txant]++;
3285 		if (ts->ts_finaltsi != 0)
3286 			sc->sc_stats.ast_tx_altrate++;
3287 		pri = M_WME_GETAC(bf->bf_m);
3288 		if (pri >= WME_AC_VO)
3289 			ic->ic_wme.wme_hipri_traffic++;
3290 		if ((bf->bf_state.bfs_txflags & HAL_TXDESC_NOACK) == 0)
3291 			ni->ni_inact = ni->ni_inact_reload;
3292 	} else {
3293 		if (ts->ts_status & HAL_TXERR_XRETRY)
3294 			sc->sc_stats.ast_tx_xretries++;
3295 		if (ts->ts_status & HAL_TXERR_FIFO)
3296 			sc->sc_stats.ast_tx_fifoerr++;
3297 		if (ts->ts_status & HAL_TXERR_FILT)
3298 			sc->sc_stats.ast_tx_filtered++;
3299 		if (ts->ts_status & HAL_TXERR_XTXOP)
3300 			sc->sc_stats.ast_tx_xtxop++;
3301 		if (ts->ts_status & HAL_TXERR_TIMER_EXPIRED)
3302 			sc->sc_stats.ast_tx_timerexpired++;
3303 
3304 		if (ts->ts_status & HAL_TX_DATA_UNDERRUN)
3305 			sc->sc_stats.ast_tx_data_underrun++;
3306 		if (ts->ts_status & HAL_TX_DELIM_UNDERRUN)
3307 			sc->sc_stats.ast_tx_delim_underrun++;
3308 
3309 		if (bf->bf_m->m_flags & M_FF)
3310 			sc->sc_stats.ast_ff_txerr++;
3311 	}
3312 	/* XXX when is this valid? */
3313 	if (ts->ts_status & HAL_TX_DESC_CFG_ERR)
3314 		sc->sc_stats.ast_tx_desccfgerr++;
3315 
3316 	sr = ts->ts_shortretry;
3317 	lr = ts->ts_longretry;
3318 	sc->sc_stats.ast_tx_shortretry += sr;
3319 	sc->sc_stats.ast_tx_longretry += lr;
3320 
3321 }
3322 
3323 /*
3324  * The default completion. If fail is 1, this means
3325  * "please don't retry the frame, and just return -1 status
3326  * to the net80211 stack.
3327  */
3328 void
3329 ath_tx_default_comp(struct ath_softc *sc, struct ath_buf *bf, int fail)
3330 {
3331 	struct ath_tx_status *ts = &bf->bf_status.ds_txstat;
3332 	int st;
3333 
3334 	if (fail == 1)
3335 		st = -1;
3336 	else
3337 		st = ((bf->bf_state.bfs_txflags & HAL_TXDESC_NOACK) == 0) ?
3338 		    ts->ts_status : HAL_TXERR_XRETRY;
3339 
3340 	if (bf->bf_state.bfs_dobaw)
3341 		device_printf(sc->sc_dev,
3342 		    "%s: bf %p: seqno %d: dobaw should've been cleared!\n",
3343 		    __func__,
3344 		    bf,
3345 		    SEQNO(bf->bf_state.bfs_seqno));
3346 	if (bf->bf_next != NULL)
3347 		device_printf(sc->sc_dev,
3348 		    "%s: bf %p: seqno %d: bf_next not NULL!\n",
3349 		    __func__,
3350 		    bf,
3351 		    SEQNO(bf->bf_state.bfs_seqno));
3352 
3353 	/*
3354 	 * Do any tx complete callback.  Note this must
3355 	 * be done before releasing the node reference.
3356 	 * This will free the mbuf, release the net80211
3357 	 * node and recycle the ath_buf.
3358 	 */
3359 	ath_tx_freebuf(sc, bf, st);
3360 }
3361 
3362 /*
3363  * Update rate control with the given completion status.
3364  */
3365 void
3366 ath_tx_update_ratectrl(struct ath_softc *sc, struct ieee80211_node *ni,
3367     struct ath_rc_series *rc, struct ath_tx_status *ts, int frmlen,
3368     int nframes, int nbad)
3369 {
3370 	struct ath_node *an;
3371 
3372 	/* Only for unicast frames */
3373 	if (ni == NULL)
3374 		return;
3375 
3376 	an = ATH_NODE(ni);
3377 
3378 	if ((ts->ts_status & HAL_TXERR_FILT) == 0) {
3379 		ATH_NODE_LOCK(an);
3380 		ath_rate_tx_complete(sc, an, rc, ts, frmlen, nframes, nbad);
3381 		ATH_NODE_UNLOCK(an);
3382 	}
3383 }
3384 
3385 /*
3386  * Update the busy status of the last frame on the free list.
3387  * When doing TDMA, the busy flag tracks whether the hardware
3388  * currently points to this buffer or not, and thus gated DMA
3389  * may restart by re-reading the last descriptor in this
3390  * buffer.
3391  *
3392  * This should be called in the completion function once one
3393  * of the buffers has been used.
3394  */
3395 static void
3396 ath_tx_update_busy(struct ath_softc *sc)
3397 {
3398 	struct ath_buf *last;
3399 
3400 	/*
3401 	 * Since the last frame may still be marked
3402 	 * as ATH_BUF_BUSY, unmark it here before
3403 	 * finishing the frame processing.
3404 	 * Since we've completed a frame (aggregate
3405 	 * or otherwise), the hardware has moved on
3406 	 * and is no longer referencing the previous
3407 	 * descriptor.
3408 	 */
3409 	ATH_TXBUF_LOCK_ASSERT(sc);
3410 	last = TAILQ_LAST(&sc->sc_txbuf_mgmt, ath_bufhead_s);
3411 	if (last != NULL)
3412 		last->bf_flags &= ~ATH_BUF_BUSY;
3413 	last = TAILQ_LAST(&sc->sc_txbuf, ath_bufhead_s);
3414 	if (last != NULL)
3415 		last->bf_flags &= ~ATH_BUF_BUSY;
3416 }
3417 
3418 /*
3419  * Process completed xmit descriptors from the specified queue.
3420  * Kick the packet scheduler if needed. This can occur from this
3421  * particular task.
3422  */
3423 static int
3424 ath_tx_processq(struct ath_softc *sc, struct ath_txq *txq, int dosched)
3425 {
3426 	struct ath_hal *ah = sc->sc_ah;
3427 	struct ath_buf *bf;
3428 	struct ath_desc *ds;
3429 	struct ath_tx_status *ts;
3430 	struct ieee80211_node *ni;
3431 	struct ath_node *an;
3432 #ifdef	IEEE80211_SUPPORT_SUPERG
3433 	struct ieee80211com *ic = sc->sc_ifp->if_l2com;
3434 #endif	/* IEEE80211_SUPPORT_SUPERG */
3435 	int nacked;
3436 	HAL_STATUS status;
3437 
3438 	DPRINTF(sc, ATH_DEBUG_TX_PROC, "%s: tx queue %u head %p link %p\n",
3439 		__func__, txq->axq_qnum,
3440 		(caddr_t)(uintptr_t) ath_hal_gettxbuf(sc->sc_ah, txq->axq_qnum),
3441 		txq->axq_link);
3442 	nacked = 0;
3443 	for (;;) {
3444 		ATH_TXQ_LOCK(txq);
3445 		txq->axq_intrcnt = 0;	/* reset periodic desc intr count */
3446 		bf = TAILQ_FIRST(&txq->axq_q);
3447 		if (bf == NULL) {
3448 			ATH_TXQ_UNLOCK(txq);
3449 			break;
3450 		}
3451 		ds = bf->bf_lastds;	/* XXX must be setup correctly! */
3452 		ts = &bf->bf_status.ds_txstat;
3453 		status = ath_hal_txprocdesc(ah, ds, ts);
3454 #ifdef ATH_DEBUG
3455 		if (sc->sc_debug & ATH_DEBUG_XMIT_DESC)
3456 			ath_printtxbuf(sc, bf, txq->axq_qnum, 0,
3457 			    status == HAL_OK);
3458 		else if ((sc->sc_debug & ATH_DEBUG_RESET) && (dosched == 0)) {
3459 			ath_printtxbuf(sc, bf, txq->axq_qnum, 0,
3460 			    status == HAL_OK);
3461 		}
3462 #endif
3463 		if (status == HAL_EINPROGRESS) {
3464 			ATH_TXQ_UNLOCK(txq);
3465 			break;
3466 		}
3467 		ATH_TXQ_REMOVE(txq, bf, bf_list);
3468 #ifdef IEEE80211_SUPPORT_TDMA
3469 		if (txq->axq_depth > 0) {
3470 			/*
3471 			 * More frames follow.  Mark the buffer busy
3472 			 * so it's not re-used while the hardware may
3473 			 * still re-read the link field in the descriptor.
3474 			 *
3475 			 * Use the last buffer in an aggregate as that
3476 			 * is where the hardware may be - intermediate
3477 			 * descriptors won't be "busy".
3478 			 */
3479 			bf->bf_last->bf_flags |= ATH_BUF_BUSY;
3480 		} else
3481 #else
3482 		if (txq->axq_depth == 0)
3483 #endif
3484 			txq->axq_link = NULL;
3485 		if (bf->bf_state.bfs_aggr)
3486 			txq->axq_aggr_depth--;
3487 
3488 		ni = bf->bf_node;
3489 		/*
3490 		 * If unicast frame was ack'd update RSSI,
3491 		 * including the last rx time used to
3492 		 * workaround phantom bmiss interrupts.
3493 		 */
3494 		if (ni != NULL && ts->ts_status == 0 &&
3495 		    ((bf->bf_state.bfs_txflags & HAL_TXDESC_NOACK) == 0)) {
3496 			nacked++;
3497 			sc->sc_stats.ast_tx_rssi = ts->ts_rssi;
3498 			ATH_RSSI_LPF(sc->sc_halstats.ns_avgtxrssi,
3499 				ts->ts_rssi);
3500 		}
3501 		ATH_TXQ_UNLOCK(txq);
3502 
3503 		/* If unicast frame, update general statistics */
3504 		if (ni != NULL) {
3505 			an = ATH_NODE(ni);
3506 			/* update statistics */
3507 			ath_tx_update_stats(sc, ts, bf);
3508 		}
3509 
3510 		/*
3511 		 * Call the completion handler.
3512 		 * The completion handler is responsible for
3513 		 * calling the rate control code.
3514 		 *
3515 		 * Frames with no completion handler get the
3516 		 * rate control code called here.
3517 		 */
3518 		if (bf->bf_comp == NULL) {
3519 			if ((ts->ts_status & HAL_TXERR_FILT) == 0 &&
3520 			    (bf->bf_state.bfs_txflags & HAL_TXDESC_NOACK) == 0) {
3521 				/*
3522 				 * XXX assume this isn't an aggregate
3523 				 * frame.
3524 				 */
3525 				ath_tx_update_ratectrl(sc, ni,
3526 				     bf->bf_state.bfs_rc, ts,
3527 				    bf->bf_state.bfs_pktlen, 1,
3528 				    (ts->ts_status == 0 ? 0 : 1));
3529 			}
3530 			ath_tx_default_comp(sc, bf, 0);
3531 		} else
3532 			bf->bf_comp(sc, bf, 0);
3533 	}
3534 #ifdef IEEE80211_SUPPORT_SUPERG
3535 	/*
3536 	 * Flush fast-frame staging queue when traffic slows.
3537 	 */
3538 	if (txq->axq_depth <= 1)
3539 		ieee80211_ff_flush(ic, txq->axq_ac);
3540 #endif
3541 
3542 	/* Kick the TXQ scheduler */
3543 	if (dosched) {
3544 		ATH_TXQ_LOCK(txq);
3545 		ath_txq_sched(sc, txq);
3546 		ATH_TXQ_UNLOCK(txq);
3547 	}
3548 
3549 	return nacked;
3550 }
3551 
3552 #define	TXQACTIVE(t, q)		( (t) & (1 << (q)))
3553 
3554 /*
3555  * Deferred processing of transmit interrupt; special-cased
3556  * for a single hardware transmit queue (e.g. 5210 and 5211).
3557  */
3558 static void
3559 ath_tx_proc_q0(void *arg, int npending)
3560 {
3561 	struct ath_softc *sc = arg;
3562 	struct ifnet *ifp = sc->sc_ifp;
3563 	uint32_t txqs;
3564 
3565 	ATH_PCU_LOCK(sc);
3566 	sc->sc_txproc_cnt++;
3567 	txqs = sc->sc_txq_active;
3568 	sc->sc_txq_active &= ~txqs;
3569 	ATH_PCU_UNLOCK(sc);
3570 
3571 	if (TXQACTIVE(txqs, 0) && ath_tx_processq(sc, &sc->sc_txq[0], 1))
3572 		/* XXX why is lastrx updated in tx code? */
3573 		sc->sc_lastrx = ath_hal_gettsf64(sc->sc_ah);
3574 	if (TXQACTIVE(txqs, sc->sc_cabq->axq_qnum))
3575 		ath_tx_processq(sc, sc->sc_cabq, 1);
3576 	IF_LOCK(&ifp->if_snd);
3577 	ifp->if_drv_flags &= ~IFF_DRV_OACTIVE;
3578 	IF_UNLOCK(&ifp->if_snd);
3579 	sc->sc_wd_timer = 0;
3580 
3581 	if (sc->sc_softled)
3582 		ath_led_event(sc, sc->sc_txrix);
3583 
3584 	ATH_PCU_LOCK(sc);
3585 	sc->sc_txproc_cnt--;
3586 	ATH_PCU_UNLOCK(sc);
3587 
3588 	ath_tx_kick(sc);
3589 }
3590 
3591 /*
3592  * Deferred processing of transmit interrupt; special-cased
3593  * for four hardware queues, 0-3 (e.g. 5212 w/ WME support).
3594  */
3595 static void
3596 ath_tx_proc_q0123(void *arg, int npending)
3597 {
3598 	struct ath_softc *sc = arg;
3599 	struct ifnet *ifp = sc->sc_ifp;
3600 	int nacked;
3601 	uint32_t txqs;
3602 
3603 	ATH_PCU_LOCK(sc);
3604 	sc->sc_txproc_cnt++;
3605 	txqs = sc->sc_txq_active;
3606 	sc->sc_txq_active &= ~txqs;
3607 	ATH_PCU_UNLOCK(sc);
3608 
3609 	/*
3610 	 * Process each active queue.
3611 	 */
3612 	nacked = 0;
3613 	if (TXQACTIVE(txqs, 0))
3614 		nacked += ath_tx_processq(sc, &sc->sc_txq[0], 1);
3615 	if (TXQACTIVE(txqs, 1))
3616 		nacked += ath_tx_processq(sc, &sc->sc_txq[1], 1);
3617 	if (TXQACTIVE(txqs, 2))
3618 		nacked += ath_tx_processq(sc, &sc->sc_txq[2], 1);
3619 	if (TXQACTIVE(txqs, 3))
3620 		nacked += ath_tx_processq(sc, &sc->sc_txq[3], 1);
3621 	if (TXQACTIVE(txqs, sc->sc_cabq->axq_qnum))
3622 		ath_tx_processq(sc, sc->sc_cabq, 1);
3623 	if (nacked)
3624 		sc->sc_lastrx = ath_hal_gettsf64(sc->sc_ah);
3625 
3626 	IF_LOCK(&ifp->if_snd);
3627 	ifp->if_drv_flags &= ~IFF_DRV_OACTIVE;
3628 	IF_UNLOCK(&ifp->if_snd);
3629 	sc->sc_wd_timer = 0;
3630 
3631 	if (sc->sc_softled)
3632 		ath_led_event(sc, sc->sc_txrix);
3633 
3634 	ATH_PCU_LOCK(sc);
3635 	sc->sc_txproc_cnt--;
3636 	ATH_PCU_UNLOCK(sc);
3637 
3638 	ath_tx_kick(sc);
3639 }
3640 
3641 /*
3642  * Deferred processing of transmit interrupt.
3643  */
3644 static void
3645 ath_tx_proc(void *arg, int npending)
3646 {
3647 	struct ath_softc *sc = arg;
3648 	struct ifnet *ifp = sc->sc_ifp;
3649 	int i, nacked;
3650 	uint32_t txqs;
3651 
3652 	ATH_PCU_LOCK(sc);
3653 	sc->sc_txproc_cnt++;
3654 	txqs = sc->sc_txq_active;
3655 	sc->sc_txq_active &= ~txqs;
3656 	ATH_PCU_UNLOCK(sc);
3657 
3658 	/*
3659 	 * Process each active queue.
3660 	 */
3661 	nacked = 0;
3662 	for (i = 0; i < HAL_NUM_TX_QUEUES; i++)
3663 		if (ATH_TXQ_SETUP(sc, i) && TXQACTIVE(txqs, i))
3664 			nacked += ath_tx_processq(sc, &sc->sc_txq[i], 1);
3665 	if (nacked)
3666 		sc->sc_lastrx = ath_hal_gettsf64(sc->sc_ah);
3667 
3668 	/* XXX check this inside of IF_LOCK? */
3669 	IF_LOCK(&ifp->if_snd);
3670 	ifp->if_drv_flags &= ~IFF_DRV_OACTIVE;
3671 	IF_UNLOCK(&ifp->if_snd);
3672 	sc->sc_wd_timer = 0;
3673 
3674 	if (sc->sc_softled)
3675 		ath_led_event(sc, sc->sc_txrix);
3676 
3677 	ATH_PCU_LOCK(sc);
3678 	sc->sc_txproc_cnt--;
3679 	ATH_PCU_UNLOCK(sc);
3680 
3681 	ath_tx_kick(sc);
3682 }
3683 #undef	TXQACTIVE
3684 
3685 /*
3686  * Deferred processing of TXQ rescheduling.
3687  */
3688 static void
3689 ath_txq_sched_tasklet(void *arg, int npending)
3690 {
3691 	struct ath_softc *sc = arg;
3692 	int i;
3693 
3694 	/* XXX is skipping ok? */
3695 	ATH_PCU_LOCK(sc);
3696 #if 0
3697 	if (sc->sc_inreset_cnt > 0) {
3698 		device_printf(sc->sc_dev,
3699 		    "%s: sc_inreset_cnt > 0; skipping\n", __func__);
3700 		ATH_PCU_UNLOCK(sc);
3701 		return;
3702 	}
3703 #endif
3704 	sc->sc_txproc_cnt++;
3705 	ATH_PCU_UNLOCK(sc);
3706 
3707 	for (i = 0; i < HAL_NUM_TX_QUEUES; i++) {
3708 		if (ATH_TXQ_SETUP(sc, i)) {
3709 			ATH_TXQ_LOCK(&sc->sc_txq[i]);
3710 			ath_txq_sched(sc, &sc->sc_txq[i]);
3711 			ATH_TXQ_UNLOCK(&sc->sc_txq[i]);
3712 		}
3713 	}
3714 
3715 	ATH_PCU_LOCK(sc);
3716 	sc->sc_txproc_cnt--;
3717 	ATH_PCU_UNLOCK(sc);
3718 }
3719 
3720 void
3721 ath_returnbuf_tail(struct ath_softc *sc, struct ath_buf *bf)
3722 {
3723 
3724 	ATH_TXBUF_LOCK_ASSERT(sc);
3725 
3726 	if (bf->bf_flags & ATH_BUF_MGMT)
3727 		TAILQ_INSERT_TAIL(&sc->sc_txbuf_mgmt, bf, bf_list);
3728 	else {
3729 		TAILQ_INSERT_TAIL(&sc->sc_txbuf, bf, bf_list);
3730 		sc->sc_txbuf_cnt++;
3731 		if (sc->sc_txbuf_cnt > ath_txbuf) {
3732 			device_printf(sc->sc_dev,
3733 			    "%s: sc_txbuf_cnt > %d?\n",
3734 			    __func__,
3735 			    ath_txbuf);
3736 			sc->sc_txbuf_cnt = ath_txbuf;
3737 		}
3738 	}
3739 }
3740 
3741 void
3742 ath_returnbuf_head(struct ath_softc *sc, struct ath_buf *bf)
3743 {
3744 
3745 	ATH_TXBUF_LOCK_ASSERT(sc);
3746 
3747 	if (bf->bf_flags & ATH_BUF_MGMT)
3748 		TAILQ_INSERT_HEAD(&sc->sc_txbuf_mgmt, bf, bf_list);
3749 	else {
3750 		TAILQ_INSERT_HEAD(&sc->sc_txbuf, bf, bf_list);
3751 		sc->sc_txbuf_cnt++;
3752 		if (sc->sc_txbuf_cnt > ATH_TXBUF) {
3753 			device_printf(sc->sc_dev,
3754 			    "%s: sc_txbuf_cnt > %d?\n",
3755 			    __func__,
3756 			    ATH_TXBUF);
3757 			sc->sc_txbuf_cnt = ATH_TXBUF;
3758 		}
3759 	}
3760 }
3761 
3762 /*
3763  * Return a buffer to the pool and update the 'busy' flag on the
3764  * previous 'tail' entry.
3765  *
3766  * This _must_ only be called when the buffer is involved in a completed
3767  * TX. The logic is that if it was part of an active TX, the previous
3768  * buffer on the list is now not involved in a halted TX DMA queue, waiting
3769  * for restart (eg for TDMA.)
3770  *
3771  * The caller must free the mbuf and recycle the node reference.
3772  */
3773 void
3774 ath_freebuf(struct ath_softc *sc, struct ath_buf *bf)
3775 {
3776 	bus_dmamap_unload(sc->sc_dmat, bf->bf_dmamap);
3777 	bus_dmamap_sync(sc->sc_dmat, bf->bf_dmamap, BUS_DMASYNC_POSTWRITE);
3778 
3779 	KASSERT((bf->bf_node == NULL), ("%s: bf->bf_node != NULL\n", __func__));
3780 	KASSERT((bf->bf_m == NULL), ("%s: bf->bf_m != NULL\n", __func__));
3781 
3782 	ATH_TXBUF_LOCK(sc);
3783 	ath_tx_update_busy(sc);
3784 	ath_returnbuf_tail(sc, bf);
3785 	ATH_TXBUF_UNLOCK(sc);
3786 }
3787 
3788 /*
3789  * This is currently used by ath_tx_draintxq() and
3790  * ath_tx_tid_free_pkts().
3791  *
3792  * It recycles a single ath_buf.
3793  */
3794 void
3795 ath_tx_freebuf(struct ath_softc *sc, struct ath_buf *bf, int status)
3796 {
3797 	struct ieee80211_node *ni = bf->bf_node;
3798 	struct mbuf *m0 = bf->bf_m;
3799 
3800 	bf->bf_node = NULL;
3801 	bf->bf_m = NULL;
3802 
3803 	/* Free the buffer, it's not needed any longer */
3804 	ath_freebuf(sc, bf);
3805 
3806 	if (ni != NULL) {
3807 		/*
3808 		 * Do any callback and reclaim the node reference.
3809 		 */
3810 		if (m0->m_flags & M_TXCB)
3811 			ieee80211_process_callback(ni, m0, status);
3812 		ieee80211_free_node(ni);
3813 	}
3814 	m_freem(m0);
3815 
3816 	/*
3817 	 * XXX the buffer used to be freed -after-, but the DMA map was
3818 	 * freed where ath_freebuf() now is. I've no idea what this
3819 	 * will do.
3820 	 */
3821 }
3822 
3823 void
3824 ath_tx_draintxq(struct ath_softc *sc, struct ath_txq *txq)
3825 {
3826 #ifdef ATH_DEBUG
3827 	struct ath_hal *ah = sc->sc_ah;
3828 #endif
3829 	struct ath_buf *bf;
3830 	u_int ix;
3831 
3832 	/*
3833 	 * NB: this assumes output has been stopped and
3834 	 *     we do not need to block ath_tx_proc
3835 	 */
3836 	ATH_TXBUF_LOCK(sc);
3837 	bf = TAILQ_LAST(&sc->sc_txbuf, ath_bufhead_s);
3838 	if (bf != NULL)
3839 		bf->bf_flags &= ~ATH_BUF_BUSY;
3840 	bf = TAILQ_LAST(&sc->sc_txbuf_mgmt, ath_bufhead_s);
3841 	if (bf != NULL)
3842 		bf->bf_flags &= ~ATH_BUF_BUSY;
3843 	ATH_TXBUF_UNLOCK(sc);
3844 
3845 	for (ix = 0;; ix++) {
3846 		ATH_TXQ_LOCK(txq);
3847 		bf = TAILQ_FIRST(&txq->axq_q);
3848 		if (bf == NULL) {
3849 			txq->axq_link = NULL;
3850 			ATH_TXQ_UNLOCK(txq);
3851 			break;
3852 		}
3853 		ATH_TXQ_REMOVE(txq, bf, bf_list);
3854 		if (bf->bf_state.bfs_aggr)
3855 			txq->axq_aggr_depth--;
3856 #ifdef ATH_DEBUG
3857 		if (sc->sc_debug & ATH_DEBUG_RESET) {
3858 			struct ieee80211com *ic = sc->sc_ifp->if_l2com;
3859 
3860 			ath_printtxbuf(sc, bf, txq->axq_qnum, ix,
3861 				ath_hal_txprocdesc(ah, bf->bf_lastds,
3862 				    &bf->bf_status.ds_txstat) == HAL_OK);
3863 			ieee80211_dump_pkt(ic, mtod(bf->bf_m, const uint8_t *),
3864 			    bf->bf_m->m_len, 0, -1);
3865 		}
3866 #endif /* ATH_DEBUG */
3867 		/*
3868 		 * Since we're now doing magic in the completion
3869 		 * functions, we -must- call it for aggregation
3870 		 * destinations or BAW tracking will get upset.
3871 		 */
3872 		/*
3873 		 * Clear ATH_BUF_BUSY; the completion handler
3874 		 * will free the buffer.
3875 		 */
3876 		ATH_TXQ_UNLOCK(txq);
3877 		bf->bf_flags &= ~ATH_BUF_BUSY;
3878 		if (bf->bf_comp)
3879 			bf->bf_comp(sc, bf, 1);
3880 		else
3881 			ath_tx_default_comp(sc, bf, 1);
3882 	}
3883 
3884 	/*
3885 	 * Drain software queued frames which are on
3886 	 * active TIDs.
3887 	 */
3888 	ath_tx_txq_drain(sc, txq);
3889 }
3890 
3891 static void
3892 ath_tx_stopdma(struct ath_softc *sc, struct ath_txq *txq)
3893 {
3894 	struct ath_hal *ah = sc->sc_ah;
3895 
3896 	DPRINTF(sc, ATH_DEBUG_RESET, "%s: tx queue [%u] %p, link %p\n",
3897 	    __func__, txq->axq_qnum,
3898 	    (caddr_t)(uintptr_t) ath_hal_gettxbuf(ah, txq->axq_qnum),
3899 	    txq->axq_link);
3900 	(void) ath_hal_stoptxdma(ah, txq->axq_qnum);
3901 }
3902 
3903 static int
3904 ath_stoptxdma(struct ath_softc *sc)
3905 {
3906 	struct ath_hal *ah = sc->sc_ah;
3907 	int i;
3908 
3909 	/* XXX return value */
3910 	if (sc->sc_invalid)
3911 		return 0;
3912 
3913 	if (!sc->sc_invalid) {
3914 		/* don't touch the hardware if marked invalid */
3915 		DPRINTF(sc, ATH_DEBUG_RESET, "%s: tx queue [%u] %p, link %p\n",
3916 		    __func__, sc->sc_bhalq,
3917 		    (caddr_t)(uintptr_t) ath_hal_gettxbuf(ah, sc->sc_bhalq),
3918 		    NULL);
3919 		(void) ath_hal_stoptxdma(ah, sc->sc_bhalq);
3920 		for (i = 0; i < HAL_NUM_TX_QUEUES; i++)
3921 			if (ATH_TXQ_SETUP(sc, i))
3922 				ath_tx_stopdma(sc, &sc->sc_txq[i]);
3923 	}
3924 
3925 	return 1;
3926 }
3927 
3928 /*
3929  * Drain the transmit queues and reclaim resources.
3930  */
3931 static void
3932 ath_draintxq(struct ath_softc *sc, ATH_RESET_TYPE reset_type)
3933 {
3934 #ifdef	ATH_DEBUG
3935 	struct ath_hal *ah = sc->sc_ah;
3936 #endif
3937 	struct ifnet *ifp = sc->sc_ifp;
3938 	int i;
3939 
3940 	(void) ath_stoptxdma(sc);
3941 
3942 	for (i = 0; i < HAL_NUM_TX_QUEUES; i++) {
3943 		/*
3944 		 * XXX TODO: should we just handle the completed TX frames
3945 		 * here, whether or not the reset is a full one or not?
3946 		 */
3947 		if (ATH_TXQ_SETUP(sc, i)) {
3948 			if (reset_type == ATH_RESET_NOLOSS)
3949 				ath_tx_processq(sc, &sc->sc_txq[i], 0);
3950 			else
3951 				ath_tx_draintxq(sc, &sc->sc_txq[i]);
3952 		}
3953 	}
3954 #ifdef ATH_DEBUG
3955 	if (sc->sc_debug & ATH_DEBUG_RESET) {
3956 		struct ath_buf *bf = TAILQ_FIRST(&sc->sc_bbuf);
3957 		if (bf != NULL && bf->bf_m != NULL) {
3958 			ath_printtxbuf(sc, bf, sc->sc_bhalq, 0,
3959 				ath_hal_txprocdesc(ah, bf->bf_lastds,
3960 				    &bf->bf_status.ds_txstat) == HAL_OK);
3961 			ieee80211_dump_pkt(ifp->if_l2com,
3962 			    mtod(bf->bf_m, const uint8_t *), bf->bf_m->m_len,
3963 			    0, -1);
3964 		}
3965 	}
3966 #endif /* ATH_DEBUG */
3967 	IF_LOCK(&ifp->if_snd);
3968 	ifp->if_drv_flags &= ~IFF_DRV_OACTIVE;
3969 	IF_UNLOCK(&ifp->if_snd);
3970 	sc->sc_wd_timer = 0;
3971 }
3972 
3973 /*
3974  * Update internal state after a channel change.
3975  */
3976 static void
3977 ath_chan_change(struct ath_softc *sc, struct ieee80211_channel *chan)
3978 {
3979 	enum ieee80211_phymode mode;
3980 
3981 	/*
3982 	 * Change channels and update the h/w rate map
3983 	 * if we're switching; e.g. 11a to 11b/g.
3984 	 */
3985 	mode = ieee80211_chan2mode(chan);
3986 	if (mode != sc->sc_curmode)
3987 		ath_setcurmode(sc, mode);
3988 	sc->sc_curchan = chan;
3989 }
3990 
3991 /*
3992  * Set/change channels.  If the channel is really being changed,
3993  * it's done by resetting the chip.  To accomplish this we must
3994  * first cleanup any pending DMA, then restart stuff after a la
3995  * ath_init.
3996  */
3997 static int
3998 ath_chan_set(struct ath_softc *sc, struct ieee80211_channel *chan)
3999 {
4000 	struct ifnet *ifp = sc->sc_ifp;
4001 	struct ieee80211com *ic = ifp->if_l2com;
4002 	struct ath_hal *ah = sc->sc_ah;
4003 	int ret = 0;
4004 
4005 	/* Treat this as an interface reset */
4006 	ATH_PCU_UNLOCK_ASSERT(sc);
4007 	ATH_UNLOCK_ASSERT(sc);
4008 
4009 	/* (Try to) stop TX/RX from occuring */
4010 	taskqueue_block(sc->sc_tq);
4011 
4012 	ATH_PCU_LOCK(sc);
4013 	ath_hal_intrset(ah, 0);		/* Stop new RX/TX completion */
4014 	ath_txrx_stop_locked(sc);	/* Stop pending RX/TX completion */
4015 	if (ath_reset_grablock(sc, 1) == 0) {
4016 		device_printf(sc->sc_dev, "%s: concurrent reset! Danger!\n",
4017 		    __func__);
4018 	}
4019 	ATH_PCU_UNLOCK(sc);
4020 
4021 	DPRINTF(sc, ATH_DEBUG_RESET, "%s: %u (%u MHz, flags 0x%x)\n",
4022 	    __func__, ieee80211_chan2ieee(ic, chan),
4023 	    chan->ic_freq, chan->ic_flags);
4024 	if (chan != sc->sc_curchan) {
4025 		HAL_STATUS status;
4026 		/*
4027 		 * To switch channels clear any pending DMA operations;
4028 		 * wait long enough for the RX fifo to drain, reset the
4029 		 * hardware at the new frequency, and then re-enable
4030 		 * the relevant bits of the h/w.
4031 		 */
4032 #if 0
4033 		ath_hal_intrset(ah, 0);		/* disable interrupts */
4034 #endif
4035 		ath_stoprecv(sc, 1);		/* turn off frame recv */
4036 		/*
4037 		 * First, handle completed TX/RX frames.
4038 		 */
4039 		ath_rx_flush(sc);
4040 		ath_draintxq(sc, ATH_RESET_NOLOSS);
4041 		/*
4042 		 * Next, flush the non-scheduled frames.
4043 		 */
4044 		ath_draintxq(sc, ATH_RESET_FULL);	/* clear pending tx frames */
4045 
4046 		if (!ath_hal_reset(ah, sc->sc_opmode, chan, AH_TRUE, &status)) {
4047 			if_printf(ifp, "%s: unable to reset "
4048 			    "channel %u (%u MHz, flags 0x%x), hal status %u\n",
4049 			    __func__, ieee80211_chan2ieee(ic, chan),
4050 			    chan->ic_freq, chan->ic_flags, status);
4051 			ret = EIO;
4052 			goto finish;
4053 		}
4054 		sc->sc_diversity = ath_hal_getdiversity(ah);
4055 
4056 		/* Let DFS at it in case it's a DFS channel */
4057 		ath_dfs_radar_enable(sc, chan);
4058 
4059 		/*
4060 		 * Re-enable rx framework.
4061 		 */
4062 		if (ath_startrecv(sc) != 0) {
4063 			if_printf(ifp, "%s: unable to restart recv logic\n",
4064 			    __func__);
4065 			ret = EIO;
4066 			goto finish;
4067 		}
4068 
4069 		/*
4070 		 * Change channels and update the h/w rate map
4071 		 * if we're switching; e.g. 11a to 11b/g.
4072 		 */
4073 		ath_chan_change(sc, chan);
4074 
4075 		/*
4076 		 * Reset clears the beacon timers; reset them
4077 		 * here if needed.
4078 		 */
4079 		if (sc->sc_beacons) {		/* restart beacons */
4080 #ifdef IEEE80211_SUPPORT_TDMA
4081 			if (sc->sc_tdma)
4082 				ath_tdma_config(sc, NULL);
4083 			else
4084 #endif
4085 			ath_beacon_config(sc, NULL);
4086 		}
4087 
4088 		/*
4089 		 * Re-enable interrupts.
4090 		 */
4091 #if 0
4092 		ath_hal_intrset(ah, sc->sc_imask);
4093 #endif
4094 	}
4095 
4096 finish:
4097 	ATH_PCU_LOCK(sc);
4098 	sc->sc_inreset_cnt--;
4099 	/* XXX only do this if sc_inreset_cnt == 0? */
4100 	ath_hal_intrset(ah, sc->sc_imask);
4101 	ATH_PCU_UNLOCK(sc);
4102 
4103 	IF_LOCK(&ifp->if_snd);
4104 	ifp->if_drv_flags &= ~IFF_DRV_OACTIVE;
4105 	IF_UNLOCK(&ifp->if_snd);
4106 	ath_txrx_start(sc);
4107 	/* XXX ath_start? */
4108 
4109 	return ret;
4110 }
4111 
4112 /*
4113  * Periodically recalibrate the PHY to account
4114  * for temperature/environment changes.
4115  */
4116 static void
4117 ath_calibrate(void *arg)
4118 {
4119 	struct ath_softc *sc = arg;
4120 	struct ath_hal *ah = sc->sc_ah;
4121 	struct ifnet *ifp = sc->sc_ifp;
4122 	struct ieee80211com *ic = ifp->if_l2com;
4123 	HAL_BOOL longCal, isCalDone;
4124 	HAL_BOOL aniCal, shortCal = AH_FALSE;
4125 	int nextcal;
4126 
4127 	if (ic->ic_flags & IEEE80211_F_SCAN)	/* defer, off channel */
4128 		goto restart;
4129 	longCal = (ticks - sc->sc_lastlongcal >= ath_longcalinterval*hz);
4130 	aniCal = (ticks - sc->sc_lastani >= ath_anicalinterval*hz/1000);
4131 	if (sc->sc_doresetcal)
4132 		shortCal = (ticks - sc->sc_lastshortcal >= ath_shortcalinterval*hz/1000);
4133 
4134 	DPRINTF(sc, ATH_DEBUG_CALIBRATE, "%s: shortCal=%d; longCal=%d; aniCal=%d\n", __func__, shortCal, longCal, aniCal);
4135 	if (aniCal) {
4136 		sc->sc_stats.ast_ani_cal++;
4137 		sc->sc_lastani = ticks;
4138 		ath_hal_ani_poll(ah, sc->sc_curchan);
4139 	}
4140 
4141 	if (longCal) {
4142 		sc->sc_stats.ast_per_cal++;
4143 		sc->sc_lastlongcal = ticks;
4144 		if (ath_hal_getrfgain(ah) == HAL_RFGAIN_NEED_CHANGE) {
4145 			/*
4146 			 * Rfgain is out of bounds, reset the chip
4147 			 * to load new gain values.
4148 			 */
4149 			DPRINTF(sc, ATH_DEBUG_CALIBRATE,
4150 				"%s: rfgain change\n", __func__);
4151 			sc->sc_stats.ast_per_rfgain++;
4152 			sc->sc_resetcal = 0;
4153 			sc->sc_doresetcal = AH_TRUE;
4154 			taskqueue_enqueue(sc->sc_tq, &sc->sc_resettask);
4155 			callout_reset(&sc->sc_cal_ch, 1, ath_calibrate, sc);
4156 			return;
4157 		}
4158 		/*
4159 		 * If this long cal is after an idle period, then
4160 		 * reset the data collection state so we start fresh.
4161 		 */
4162 		if (sc->sc_resetcal) {
4163 			(void) ath_hal_calreset(ah, sc->sc_curchan);
4164 			sc->sc_lastcalreset = ticks;
4165 			sc->sc_lastshortcal = ticks;
4166 			sc->sc_resetcal = 0;
4167 			sc->sc_doresetcal = AH_TRUE;
4168 		}
4169 	}
4170 
4171 	/* Only call if we're doing a short/long cal, not for ANI calibration */
4172 	if (shortCal || longCal) {
4173 		if (ath_hal_calibrateN(ah, sc->sc_curchan, longCal, &isCalDone)) {
4174 			if (longCal) {
4175 				/*
4176 				 * Calibrate noise floor data again in case of change.
4177 				 */
4178 				ath_hal_process_noisefloor(ah);
4179 			}
4180 		} else {
4181 			DPRINTF(sc, ATH_DEBUG_ANY,
4182 				"%s: calibration of channel %u failed\n",
4183 				__func__, sc->sc_curchan->ic_freq);
4184 			sc->sc_stats.ast_per_calfail++;
4185 		}
4186 		if (shortCal)
4187 			sc->sc_lastshortcal = ticks;
4188 	}
4189 	if (!isCalDone) {
4190 restart:
4191 		/*
4192 		 * Use a shorter interval to potentially collect multiple
4193 		 * data samples required to complete calibration.  Once
4194 		 * we're told the work is done we drop back to a longer
4195 		 * interval between requests.  We're more aggressive doing
4196 		 * work when operating as an AP to improve operation right
4197 		 * after startup.
4198 		 */
4199 		sc->sc_lastshortcal = ticks;
4200 		nextcal = ath_shortcalinterval*hz/1000;
4201 		if (sc->sc_opmode != HAL_M_HOSTAP)
4202 			nextcal *= 10;
4203 		sc->sc_doresetcal = AH_TRUE;
4204 	} else {
4205 		/* nextcal should be the shortest time for next event */
4206 		nextcal = ath_longcalinterval*hz;
4207 		if (sc->sc_lastcalreset == 0)
4208 			sc->sc_lastcalreset = sc->sc_lastlongcal;
4209 		else if (ticks - sc->sc_lastcalreset >= ath_resetcalinterval*hz)
4210 			sc->sc_resetcal = 1;	/* setup reset next trip */
4211 		sc->sc_doresetcal = AH_FALSE;
4212 	}
4213 	/* ANI calibration may occur more often than short/long/resetcal */
4214 	if (ath_anicalinterval > 0)
4215 		nextcal = MIN(nextcal, ath_anicalinterval*hz/1000);
4216 
4217 	if (nextcal != 0) {
4218 		DPRINTF(sc, ATH_DEBUG_CALIBRATE, "%s: next +%u (%sisCalDone)\n",
4219 		    __func__, nextcal, isCalDone ? "" : "!");
4220 		callout_reset(&sc->sc_cal_ch, nextcal, ath_calibrate, sc);
4221 	} else {
4222 		DPRINTF(sc, ATH_DEBUG_CALIBRATE, "%s: calibration disabled\n",
4223 		    __func__);
4224 		/* NB: don't rearm timer */
4225 	}
4226 }
4227 
4228 static void
4229 ath_scan_start(struct ieee80211com *ic)
4230 {
4231 	struct ifnet *ifp = ic->ic_ifp;
4232 	struct ath_softc *sc = ifp->if_softc;
4233 	struct ath_hal *ah = sc->sc_ah;
4234 	u_int32_t rfilt;
4235 
4236 	/* XXX calibration timer? */
4237 
4238 	ATH_LOCK(sc);
4239 	sc->sc_scanning = 1;
4240 	sc->sc_syncbeacon = 0;
4241 	rfilt = ath_calcrxfilter(sc);
4242 	ATH_UNLOCK(sc);
4243 
4244 	ATH_PCU_LOCK(sc);
4245 	ath_hal_setrxfilter(ah, rfilt);
4246 	ath_hal_setassocid(ah, ifp->if_broadcastaddr, 0);
4247 	ATH_PCU_UNLOCK(sc);
4248 
4249 	DPRINTF(sc, ATH_DEBUG_STATE, "%s: RX filter 0x%x bssid %s aid 0\n",
4250 		 __func__, rfilt, ether_sprintf(ifp->if_broadcastaddr));
4251 }
4252 
4253 static void
4254 ath_scan_end(struct ieee80211com *ic)
4255 {
4256 	struct ifnet *ifp = ic->ic_ifp;
4257 	struct ath_softc *sc = ifp->if_softc;
4258 	struct ath_hal *ah = sc->sc_ah;
4259 	u_int32_t rfilt;
4260 
4261 	ATH_LOCK(sc);
4262 	sc->sc_scanning = 0;
4263 	rfilt = ath_calcrxfilter(sc);
4264 	ATH_UNLOCK(sc);
4265 
4266 	ATH_PCU_LOCK(sc);
4267 	ath_hal_setrxfilter(ah, rfilt);
4268 	ath_hal_setassocid(ah, sc->sc_curbssid, sc->sc_curaid);
4269 
4270 	ath_hal_process_noisefloor(ah);
4271 	ATH_PCU_UNLOCK(sc);
4272 
4273 	DPRINTF(sc, ATH_DEBUG_STATE, "%s: RX filter 0x%x bssid %s aid 0x%x\n",
4274 		 __func__, rfilt, ether_sprintf(sc->sc_curbssid),
4275 		 sc->sc_curaid);
4276 }
4277 
4278 #ifdef	ATH_ENABLE_11N
4279 /*
4280  * For now, just do a channel change.
4281  *
4282  * Later, we'll go through the hard slog of suspending tx/rx, changing rate
4283  * control state and resetting the hardware without dropping frames out
4284  * of the queue.
4285  *
4286  * The unfortunate trouble here is making absolutely sure that the
4287  * channel width change has propagated enough so the hardware
4288  * absolutely isn't handed bogus frames for it's current operating
4289  * mode. (Eg, 40MHz frames in 20MHz mode.) Since TX and RX can and
4290  * does occur in parallel, we need to make certain we've blocked
4291  * any further ongoing TX (and RX, that can cause raw TX)
4292  * before we do this.
4293  */
4294 static void
4295 ath_update_chw(struct ieee80211com *ic)
4296 {
4297 	struct ifnet *ifp = ic->ic_ifp;
4298 	struct ath_softc *sc = ifp->if_softc;
4299 
4300 	DPRINTF(sc, ATH_DEBUG_STATE, "%s: called\n", __func__);
4301 	ath_set_channel(ic);
4302 }
4303 #endif	/* ATH_ENABLE_11N */
4304 
4305 static void
4306 ath_set_channel(struct ieee80211com *ic)
4307 {
4308 	struct ifnet *ifp = ic->ic_ifp;
4309 	struct ath_softc *sc = ifp->if_softc;
4310 
4311 	(void) ath_chan_set(sc, ic->ic_curchan);
4312 	/*
4313 	 * If we are returning to our bss channel then mark state
4314 	 * so the next recv'd beacon's tsf will be used to sync the
4315 	 * beacon timers.  Note that since we only hear beacons in
4316 	 * sta/ibss mode this has no effect in other operating modes.
4317 	 */
4318 	ATH_LOCK(sc);
4319 	if (!sc->sc_scanning && ic->ic_curchan == ic->ic_bsschan)
4320 		sc->sc_syncbeacon = 1;
4321 	ATH_UNLOCK(sc);
4322 }
4323 
4324 /*
4325  * Walk the vap list and check if there any vap's in RUN state.
4326  */
4327 static int
4328 ath_isanyrunningvaps(struct ieee80211vap *this)
4329 {
4330 	struct ieee80211com *ic = this->iv_ic;
4331 	struct ieee80211vap *vap;
4332 
4333 	IEEE80211_LOCK_ASSERT(ic);
4334 
4335 	TAILQ_FOREACH(vap, &ic->ic_vaps, iv_next) {
4336 		if (vap != this && vap->iv_state >= IEEE80211_S_RUN)
4337 			return 1;
4338 	}
4339 	return 0;
4340 }
4341 
4342 static int
4343 ath_newstate(struct ieee80211vap *vap, enum ieee80211_state nstate, int arg)
4344 {
4345 	struct ieee80211com *ic = vap->iv_ic;
4346 	struct ath_softc *sc = ic->ic_ifp->if_softc;
4347 	struct ath_vap *avp = ATH_VAP(vap);
4348 	struct ath_hal *ah = sc->sc_ah;
4349 	struct ieee80211_node *ni = NULL;
4350 	int i, error, stamode;
4351 	u_int32_t rfilt;
4352 	int csa_run_transition = 0;
4353 	static const HAL_LED_STATE leds[] = {
4354 	    HAL_LED_INIT,	/* IEEE80211_S_INIT */
4355 	    HAL_LED_SCAN,	/* IEEE80211_S_SCAN */
4356 	    HAL_LED_AUTH,	/* IEEE80211_S_AUTH */
4357 	    HAL_LED_ASSOC, 	/* IEEE80211_S_ASSOC */
4358 	    HAL_LED_RUN, 	/* IEEE80211_S_CAC */
4359 	    HAL_LED_RUN, 	/* IEEE80211_S_RUN */
4360 	    HAL_LED_RUN, 	/* IEEE80211_S_CSA */
4361 	    HAL_LED_RUN, 	/* IEEE80211_S_SLEEP */
4362 	};
4363 
4364 	DPRINTF(sc, ATH_DEBUG_STATE, "%s: %s -> %s\n", __func__,
4365 		ieee80211_state_name[vap->iv_state],
4366 		ieee80211_state_name[nstate]);
4367 
4368 	/*
4369 	 * net80211 _should_ have the comlock asserted at this point.
4370 	 * There are some comments around the calls to vap->iv_newstate
4371 	 * which indicate that it (newstate) may end up dropping the
4372 	 * lock.  This and the subsequent lock assert check after newstate
4373 	 * are an attempt to catch these and figure out how/why.
4374 	 */
4375 	IEEE80211_LOCK_ASSERT(ic);
4376 
4377 	if (vap->iv_state == IEEE80211_S_CSA && nstate == IEEE80211_S_RUN)
4378 		csa_run_transition = 1;
4379 
4380 	callout_drain(&sc->sc_cal_ch);
4381 	ath_hal_setledstate(ah, leds[nstate]);	/* set LED */
4382 
4383 	if (nstate == IEEE80211_S_SCAN) {
4384 		/*
4385 		 * Scanning: turn off beacon miss and don't beacon.
4386 		 * Mark beacon state so when we reach RUN state we'll
4387 		 * [re]setup beacons.  Unblock the task q thread so
4388 		 * deferred interrupt processing is done.
4389 		 */
4390 		ath_hal_intrset(ah,
4391 		    sc->sc_imask &~ (HAL_INT_SWBA | HAL_INT_BMISS));
4392 		sc->sc_imask &= ~(HAL_INT_SWBA | HAL_INT_BMISS);
4393 		sc->sc_beacons = 0;
4394 		taskqueue_unblock(sc->sc_tq);
4395 	}
4396 
4397 	ni = ieee80211_ref_node(vap->iv_bss);
4398 	rfilt = ath_calcrxfilter(sc);
4399 	stamode = (vap->iv_opmode == IEEE80211_M_STA ||
4400 		   vap->iv_opmode == IEEE80211_M_AHDEMO ||
4401 		   vap->iv_opmode == IEEE80211_M_IBSS);
4402 	if (stamode && nstate == IEEE80211_S_RUN) {
4403 		sc->sc_curaid = ni->ni_associd;
4404 		IEEE80211_ADDR_COPY(sc->sc_curbssid, ni->ni_bssid);
4405 		ath_hal_setassocid(ah, sc->sc_curbssid, sc->sc_curaid);
4406 	}
4407 	DPRINTF(sc, ATH_DEBUG_STATE, "%s: RX filter 0x%x bssid %s aid 0x%x\n",
4408 	   __func__, rfilt, ether_sprintf(sc->sc_curbssid), sc->sc_curaid);
4409 	ath_hal_setrxfilter(ah, rfilt);
4410 
4411 	/* XXX is this to restore keycache on resume? */
4412 	if (vap->iv_opmode != IEEE80211_M_STA &&
4413 	    (vap->iv_flags & IEEE80211_F_PRIVACY)) {
4414 		for (i = 0; i < IEEE80211_WEP_NKID; i++)
4415 			if (ath_hal_keyisvalid(ah, i))
4416 				ath_hal_keysetmac(ah, i, ni->ni_bssid);
4417 	}
4418 
4419 	/*
4420 	 * Invoke the parent method to do net80211 work.
4421 	 */
4422 	error = avp->av_newstate(vap, nstate, arg);
4423 	if (error != 0)
4424 		goto bad;
4425 
4426 	/*
4427 	 * See above: ensure av_newstate() doesn't drop the lock
4428 	 * on us.
4429 	 */
4430 	IEEE80211_LOCK_ASSERT(ic);
4431 
4432 	if (nstate == IEEE80211_S_RUN) {
4433 		/* NB: collect bss node again, it may have changed */
4434 		ieee80211_free_node(ni);
4435 		ni = ieee80211_ref_node(vap->iv_bss);
4436 
4437 		DPRINTF(sc, ATH_DEBUG_STATE,
4438 		    "%s(RUN): iv_flags 0x%08x bintvl %d bssid %s "
4439 		    "capinfo 0x%04x chan %d\n", __func__,
4440 		    vap->iv_flags, ni->ni_intval, ether_sprintf(ni->ni_bssid),
4441 		    ni->ni_capinfo, ieee80211_chan2ieee(ic, ic->ic_curchan));
4442 
4443 		switch (vap->iv_opmode) {
4444 #ifdef IEEE80211_SUPPORT_TDMA
4445 		case IEEE80211_M_AHDEMO:
4446 			if ((vap->iv_caps & IEEE80211_C_TDMA) == 0)
4447 				break;
4448 			/* fall thru... */
4449 #endif
4450 		case IEEE80211_M_HOSTAP:
4451 		case IEEE80211_M_IBSS:
4452 		case IEEE80211_M_MBSS:
4453 			/*
4454 			 * Allocate and setup the beacon frame.
4455 			 *
4456 			 * Stop any previous beacon DMA.  This may be
4457 			 * necessary, for example, when an ibss merge
4458 			 * causes reconfiguration; there will be a state
4459 			 * transition from RUN->RUN that means we may
4460 			 * be called with beacon transmission active.
4461 			 */
4462 			ath_hal_stoptxdma(ah, sc->sc_bhalq);
4463 
4464 			error = ath_beacon_alloc(sc, ni);
4465 			if (error != 0)
4466 				goto bad;
4467 			/*
4468 			 * If joining an adhoc network defer beacon timer
4469 			 * configuration to the next beacon frame so we
4470 			 * have a current TSF to use.  Otherwise we're
4471 			 * starting an ibss/bss so there's no need to delay;
4472 			 * if this is the first vap moving to RUN state, then
4473 			 * beacon state needs to be [re]configured.
4474 			 */
4475 			if (vap->iv_opmode == IEEE80211_M_IBSS &&
4476 			    ni->ni_tstamp.tsf != 0) {
4477 				sc->sc_syncbeacon = 1;
4478 			} else if (!sc->sc_beacons) {
4479 #ifdef IEEE80211_SUPPORT_TDMA
4480 				if (vap->iv_caps & IEEE80211_C_TDMA)
4481 					ath_tdma_config(sc, vap);
4482 				else
4483 #endif
4484 					ath_beacon_config(sc, vap);
4485 				sc->sc_beacons = 1;
4486 			}
4487 			break;
4488 		case IEEE80211_M_STA:
4489 			/*
4490 			 * Defer beacon timer configuration to the next
4491 			 * beacon frame so we have a current TSF to use
4492 			 * (any TSF collected when scanning is likely old).
4493 			 * However if it's due to a CSA -> RUN transition,
4494 			 * force a beacon update so we pick up a lack of
4495 			 * beacons from an AP in CAC and thus force a
4496 			 * scan.
4497 			 */
4498 			sc->sc_syncbeacon = 1;
4499 			if (csa_run_transition)
4500 				ath_beacon_config(sc, vap);
4501 			break;
4502 		case IEEE80211_M_MONITOR:
4503 			/*
4504 			 * Monitor mode vaps have only INIT->RUN and RUN->RUN
4505 			 * transitions so we must re-enable interrupts here to
4506 			 * handle the case of a single monitor mode vap.
4507 			 */
4508 			ath_hal_intrset(ah, sc->sc_imask);
4509 			break;
4510 		case IEEE80211_M_WDS:
4511 			break;
4512 		default:
4513 			break;
4514 		}
4515 		/*
4516 		 * Let the hal process statistics collected during a
4517 		 * scan so it can provide calibrated noise floor data.
4518 		 */
4519 		ath_hal_process_noisefloor(ah);
4520 		/*
4521 		 * Reset rssi stats; maybe not the best place...
4522 		 */
4523 		sc->sc_halstats.ns_avgbrssi = ATH_RSSI_DUMMY_MARKER;
4524 		sc->sc_halstats.ns_avgrssi = ATH_RSSI_DUMMY_MARKER;
4525 		sc->sc_halstats.ns_avgtxrssi = ATH_RSSI_DUMMY_MARKER;
4526 		/*
4527 		 * Finally, start any timers and the task q thread
4528 		 * (in case we didn't go through SCAN state).
4529 		 */
4530 		if (ath_longcalinterval != 0) {
4531 			/* start periodic recalibration timer */
4532 			callout_reset(&sc->sc_cal_ch, 1, ath_calibrate, sc);
4533 		} else {
4534 			DPRINTF(sc, ATH_DEBUG_CALIBRATE,
4535 			    "%s: calibration disabled\n", __func__);
4536 		}
4537 		taskqueue_unblock(sc->sc_tq);
4538 	} else if (nstate == IEEE80211_S_INIT) {
4539 		/*
4540 		 * If there are no vaps left in RUN state then
4541 		 * shutdown host/driver operation:
4542 		 * o disable interrupts
4543 		 * o disable the task queue thread
4544 		 * o mark beacon processing as stopped
4545 		 */
4546 		if (!ath_isanyrunningvaps(vap)) {
4547 			sc->sc_imask &= ~(HAL_INT_SWBA | HAL_INT_BMISS);
4548 			/* disable interrupts  */
4549 			ath_hal_intrset(ah, sc->sc_imask &~ HAL_INT_GLOBAL);
4550 			taskqueue_block(sc->sc_tq);
4551 			sc->sc_beacons = 0;
4552 		}
4553 #ifdef IEEE80211_SUPPORT_TDMA
4554 		ath_hal_setcca(ah, AH_TRUE);
4555 #endif
4556 	}
4557 bad:
4558 	ieee80211_free_node(ni);
4559 	return error;
4560 }
4561 
4562 /*
4563  * Allocate a key cache slot to the station so we can
4564  * setup a mapping from key index to node. The key cache
4565  * slot is needed for managing antenna state and for
4566  * compression when stations do not use crypto.  We do
4567  * it uniliaterally here; if crypto is employed this slot
4568  * will be reassigned.
4569  */
4570 static void
4571 ath_setup_stationkey(struct ieee80211_node *ni)
4572 {
4573 	struct ieee80211vap *vap = ni->ni_vap;
4574 	struct ath_softc *sc = vap->iv_ic->ic_ifp->if_softc;
4575 	ieee80211_keyix keyix, rxkeyix;
4576 
4577 	/* XXX should take a locked ref to vap->iv_bss */
4578 	if (!ath_key_alloc(vap, &ni->ni_ucastkey, &keyix, &rxkeyix)) {
4579 		/*
4580 		 * Key cache is full; we'll fall back to doing
4581 		 * the more expensive lookup in software.  Note
4582 		 * this also means no h/w compression.
4583 		 */
4584 		/* XXX msg+statistic */
4585 	} else {
4586 		/* XXX locking? */
4587 		ni->ni_ucastkey.wk_keyix = keyix;
4588 		ni->ni_ucastkey.wk_rxkeyix = rxkeyix;
4589 		/* NB: must mark device key to get called back on delete */
4590 		ni->ni_ucastkey.wk_flags |= IEEE80211_KEY_DEVKEY;
4591 		IEEE80211_ADDR_COPY(ni->ni_ucastkey.wk_macaddr, ni->ni_macaddr);
4592 		/* NB: this will create a pass-thru key entry */
4593 		ath_keyset(sc, vap, &ni->ni_ucastkey, vap->iv_bss);
4594 	}
4595 }
4596 
4597 /*
4598  * Setup driver-specific state for a newly associated node.
4599  * Note that we're called also on a re-associate, the isnew
4600  * param tells us if this is the first time or not.
4601  */
4602 static void
4603 ath_newassoc(struct ieee80211_node *ni, int isnew)
4604 {
4605 	struct ath_node *an = ATH_NODE(ni);
4606 	struct ieee80211vap *vap = ni->ni_vap;
4607 	struct ath_softc *sc = vap->iv_ic->ic_ifp->if_softc;
4608 	const struct ieee80211_txparam *tp = ni->ni_txparms;
4609 
4610 	an->an_mcastrix = ath_tx_findrix(sc, tp->mcastrate);
4611 	an->an_mgmtrix = ath_tx_findrix(sc, tp->mgmtrate);
4612 
4613 	ath_rate_newassoc(sc, an, isnew);
4614 	if (isnew &&
4615 	    (vap->iv_flags & IEEE80211_F_PRIVACY) == 0 && sc->sc_hasclrkey &&
4616 	    ni->ni_ucastkey.wk_keyix == IEEE80211_KEYIX_NONE)
4617 		ath_setup_stationkey(ni);
4618 }
4619 
4620 static int
4621 ath_setregdomain(struct ieee80211com *ic, struct ieee80211_regdomain *reg,
4622 	int nchans, struct ieee80211_channel chans[])
4623 {
4624 	struct ath_softc *sc = ic->ic_ifp->if_softc;
4625 	struct ath_hal *ah = sc->sc_ah;
4626 	HAL_STATUS status;
4627 
4628 	DPRINTF(sc, ATH_DEBUG_REGDOMAIN,
4629 	    "%s: rd %u cc %u location %c%s\n",
4630 	    __func__, reg->regdomain, reg->country, reg->location,
4631 	    reg->ecm ? " ecm" : "");
4632 
4633 	status = ath_hal_set_channels(ah, chans, nchans,
4634 	    reg->country, reg->regdomain);
4635 	if (status != HAL_OK) {
4636 		DPRINTF(sc, ATH_DEBUG_REGDOMAIN, "%s: failed, status %u\n",
4637 		    __func__, status);
4638 		return EINVAL;		/* XXX */
4639 	}
4640 
4641 	return 0;
4642 }
4643 
4644 static void
4645 ath_getradiocaps(struct ieee80211com *ic,
4646 	int maxchans, int *nchans, struct ieee80211_channel chans[])
4647 {
4648 	struct ath_softc *sc = ic->ic_ifp->if_softc;
4649 	struct ath_hal *ah = sc->sc_ah;
4650 
4651 	DPRINTF(sc, ATH_DEBUG_REGDOMAIN, "%s: use rd %u cc %d\n",
4652 	    __func__, SKU_DEBUG, CTRY_DEFAULT);
4653 
4654 	/* XXX check return */
4655 	(void) ath_hal_getchannels(ah, chans, maxchans, nchans,
4656 	    HAL_MODE_ALL, CTRY_DEFAULT, SKU_DEBUG, AH_TRUE);
4657 
4658 }
4659 
4660 static int
4661 ath_getchannels(struct ath_softc *sc)
4662 {
4663 	struct ifnet *ifp = sc->sc_ifp;
4664 	struct ieee80211com *ic = ifp->if_l2com;
4665 	struct ath_hal *ah = sc->sc_ah;
4666 	HAL_STATUS status;
4667 
4668 	/*
4669 	 * Collect channel set based on EEPROM contents.
4670 	 */
4671 	status = ath_hal_init_channels(ah, ic->ic_channels, IEEE80211_CHAN_MAX,
4672 	    &ic->ic_nchans, HAL_MODE_ALL, CTRY_DEFAULT, SKU_NONE, AH_TRUE);
4673 	if (status != HAL_OK) {
4674 		if_printf(ifp, "%s: unable to collect channel list from hal, "
4675 		    "status %d\n", __func__, status);
4676 		return EINVAL;
4677 	}
4678 	(void) ath_hal_getregdomain(ah, &sc->sc_eerd);
4679 	ath_hal_getcountrycode(ah, &sc->sc_eecc);	/* NB: cannot fail */
4680 	/* XXX map Atheros sku's to net80211 SKU's */
4681 	/* XXX net80211 types too small */
4682 	ic->ic_regdomain.regdomain = (uint16_t) sc->sc_eerd;
4683 	ic->ic_regdomain.country = (uint16_t) sc->sc_eecc;
4684 	ic->ic_regdomain.isocc[0] = ' ';	/* XXX don't know */
4685 	ic->ic_regdomain.isocc[1] = ' ';
4686 
4687 	ic->ic_regdomain.ecm = 1;
4688 	ic->ic_regdomain.location = 'I';
4689 
4690 	DPRINTF(sc, ATH_DEBUG_REGDOMAIN,
4691 	    "%s: eeprom rd %u cc %u (mapped rd %u cc %u) location %c%s\n",
4692 	    __func__, sc->sc_eerd, sc->sc_eecc,
4693 	    ic->ic_regdomain.regdomain, ic->ic_regdomain.country,
4694 	    ic->ic_regdomain.location, ic->ic_regdomain.ecm ? " ecm" : "");
4695 	return 0;
4696 }
4697 
4698 static int
4699 ath_rate_setup(struct ath_softc *sc, u_int mode)
4700 {
4701 	struct ath_hal *ah = sc->sc_ah;
4702 	const HAL_RATE_TABLE *rt;
4703 
4704 	switch (mode) {
4705 	case IEEE80211_MODE_11A:
4706 		rt = ath_hal_getratetable(ah, HAL_MODE_11A);
4707 		break;
4708 	case IEEE80211_MODE_HALF:
4709 		rt = ath_hal_getratetable(ah, HAL_MODE_11A_HALF_RATE);
4710 		break;
4711 	case IEEE80211_MODE_QUARTER:
4712 		rt = ath_hal_getratetable(ah, HAL_MODE_11A_QUARTER_RATE);
4713 		break;
4714 	case IEEE80211_MODE_11B:
4715 		rt = ath_hal_getratetable(ah, HAL_MODE_11B);
4716 		break;
4717 	case IEEE80211_MODE_11G:
4718 		rt = ath_hal_getratetable(ah, HAL_MODE_11G);
4719 		break;
4720 	case IEEE80211_MODE_TURBO_A:
4721 		rt = ath_hal_getratetable(ah, HAL_MODE_108A);
4722 		break;
4723 	case IEEE80211_MODE_TURBO_G:
4724 		rt = ath_hal_getratetable(ah, HAL_MODE_108G);
4725 		break;
4726 	case IEEE80211_MODE_STURBO_A:
4727 		rt = ath_hal_getratetable(ah, HAL_MODE_TURBO);
4728 		break;
4729 	case IEEE80211_MODE_11NA:
4730 		rt = ath_hal_getratetable(ah, HAL_MODE_11NA_HT20);
4731 		break;
4732 	case IEEE80211_MODE_11NG:
4733 		rt = ath_hal_getratetable(ah, HAL_MODE_11NG_HT20);
4734 		break;
4735 	default:
4736 		DPRINTF(sc, ATH_DEBUG_ANY, "%s: invalid mode %u\n",
4737 			__func__, mode);
4738 		return 0;
4739 	}
4740 	sc->sc_rates[mode] = rt;
4741 	return (rt != NULL);
4742 }
4743 
4744 static void
4745 ath_setcurmode(struct ath_softc *sc, enum ieee80211_phymode mode)
4746 {
4747 #define	N(a)	(sizeof(a)/sizeof(a[0]))
4748 	/* NB: on/off times from the Atheros NDIS driver, w/ permission */
4749 	static const struct {
4750 		u_int		rate;		/* tx/rx 802.11 rate */
4751 		u_int16_t	timeOn;		/* LED on time (ms) */
4752 		u_int16_t	timeOff;	/* LED off time (ms) */
4753 	} blinkrates[] = {
4754 		{ 108,  40,  10 },
4755 		{  96,  44,  11 },
4756 		{  72,  50,  13 },
4757 		{  48,  57,  14 },
4758 		{  36,  67,  16 },
4759 		{  24,  80,  20 },
4760 		{  22, 100,  25 },
4761 		{  18, 133,  34 },
4762 		{  12, 160,  40 },
4763 		{  10, 200,  50 },
4764 		{   6, 240,  58 },
4765 		{   4, 267,  66 },
4766 		{   2, 400, 100 },
4767 		{   0, 500, 130 },
4768 		/* XXX half/quarter rates */
4769 	};
4770 	const HAL_RATE_TABLE *rt;
4771 	int i, j;
4772 
4773 	memset(sc->sc_rixmap, 0xff, sizeof(sc->sc_rixmap));
4774 	rt = sc->sc_rates[mode];
4775 	KASSERT(rt != NULL, ("no h/w rate set for phy mode %u", mode));
4776 	for (i = 0; i < rt->rateCount; i++) {
4777 		uint8_t ieeerate = rt->info[i].dot11Rate & IEEE80211_RATE_VAL;
4778 		if (rt->info[i].phy != IEEE80211_T_HT)
4779 			sc->sc_rixmap[ieeerate] = i;
4780 		else
4781 			sc->sc_rixmap[ieeerate | IEEE80211_RATE_MCS] = i;
4782 	}
4783 	memset(sc->sc_hwmap, 0, sizeof(sc->sc_hwmap));
4784 	for (i = 0; i < N(sc->sc_hwmap); i++) {
4785 		if (i >= rt->rateCount) {
4786 			sc->sc_hwmap[i].ledon = (500 * hz) / 1000;
4787 			sc->sc_hwmap[i].ledoff = (130 * hz) / 1000;
4788 			continue;
4789 		}
4790 		sc->sc_hwmap[i].ieeerate =
4791 			rt->info[i].dot11Rate & IEEE80211_RATE_VAL;
4792 		if (rt->info[i].phy == IEEE80211_T_HT)
4793 			sc->sc_hwmap[i].ieeerate |= IEEE80211_RATE_MCS;
4794 		sc->sc_hwmap[i].txflags = IEEE80211_RADIOTAP_F_DATAPAD;
4795 		if (rt->info[i].shortPreamble ||
4796 		    rt->info[i].phy == IEEE80211_T_OFDM)
4797 			sc->sc_hwmap[i].txflags |= IEEE80211_RADIOTAP_F_SHORTPRE;
4798 		sc->sc_hwmap[i].rxflags = sc->sc_hwmap[i].txflags;
4799 		for (j = 0; j < N(blinkrates)-1; j++)
4800 			if (blinkrates[j].rate == sc->sc_hwmap[i].ieeerate)
4801 				break;
4802 		/* NB: this uses the last entry if the rate isn't found */
4803 		/* XXX beware of overlow */
4804 		sc->sc_hwmap[i].ledon = (blinkrates[j].timeOn * hz) / 1000;
4805 		sc->sc_hwmap[i].ledoff = (blinkrates[j].timeOff * hz) / 1000;
4806 	}
4807 	sc->sc_currates = rt;
4808 	sc->sc_curmode = mode;
4809 	/*
4810 	 * All protection frames are transmited at 2Mb/s for
4811 	 * 11g, otherwise at 1Mb/s.
4812 	 */
4813 	if (mode == IEEE80211_MODE_11G)
4814 		sc->sc_protrix = ath_tx_findrix(sc, 2*2);
4815 	else
4816 		sc->sc_protrix = ath_tx_findrix(sc, 2*1);
4817 	/* NB: caller is responsible for resetting rate control state */
4818 #undef N
4819 }
4820 
4821 static void
4822 ath_watchdog(void *arg)
4823 {
4824 	struct ath_softc *sc = arg;
4825 	int do_reset = 0;
4826 
4827 	if (sc->sc_wd_timer != 0 && --sc->sc_wd_timer == 0) {
4828 		struct ifnet *ifp = sc->sc_ifp;
4829 		uint32_t hangs;
4830 
4831 		if (ath_hal_gethangstate(sc->sc_ah, 0xffff, &hangs) &&
4832 		    hangs != 0) {
4833 			if_printf(ifp, "%s hang detected (0x%x)\n",
4834 			    hangs & 0xff ? "bb" : "mac", hangs);
4835 		} else
4836 			if_printf(ifp, "device timeout\n");
4837 		do_reset = 1;
4838 		ifp->if_oerrors++;
4839 		sc->sc_stats.ast_watchdog++;
4840 	}
4841 
4842 	/*
4843 	 * We can't hold the lock across the ath_reset() call.
4844 	 *
4845 	 * And since this routine can't hold a lock and sleep,
4846 	 * do the reset deferred.
4847 	 */
4848 	if (do_reset) {
4849 		taskqueue_enqueue(sc->sc_tq, &sc->sc_resettask);
4850 	}
4851 
4852 	callout_schedule(&sc->sc_wd_ch, hz);
4853 }
4854 
4855 #ifdef ATH_DIAGAPI
4856 /*
4857  * Diagnostic interface to the HAL.  This is used by various
4858  * tools to do things like retrieve register contents for
4859  * debugging.  The mechanism is intentionally opaque so that
4860  * it can change frequently w/o concern for compatiblity.
4861  */
4862 static int
4863 ath_ioctl_diag(struct ath_softc *sc, struct ath_diag *ad)
4864 {
4865 	struct ath_hal *ah = sc->sc_ah;
4866 	u_int id = ad->ad_id & ATH_DIAG_ID;
4867 	void *indata = NULL;
4868 	void *outdata = NULL;
4869 	u_int32_t insize = ad->ad_in_size;
4870 	u_int32_t outsize = ad->ad_out_size;
4871 	int error = 0;
4872 
4873 	if (ad->ad_id & ATH_DIAG_IN) {
4874 		/*
4875 		 * Copy in data.
4876 		 */
4877 		indata = malloc(insize, M_TEMP, M_NOWAIT);
4878 		if (indata == NULL) {
4879 			error = ENOMEM;
4880 			goto bad;
4881 		}
4882 		error = copyin(ad->ad_in_data, indata, insize);
4883 		if (error)
4884 			goto bad;
4885 	}
4886 	if (ad->ad_id & ATH_DIAG_DYN) {
4887 		/*
4888 		 * Allocate a buffer for the results (otherwise the HAL
4889 		 * returns a pointer to a buffer where we can read the
4890 		 * results).  Note that we depend on the HAL leaving this
4891 		 * pointer for us to use below in reclaiming the buffer;
4892 		 * may want to be more defensive.
4893 		 */
4894 		outdata = malloc(outsize, M_TEMP, M_NOWAIT);
4895 		if (outdata == NULL) {
4896 			error = ENOMEM;
4897 			goto bad;
4898 		}
4899 	}
4900 	if (ath_hal_getdiagstate(ah, id, indata, insize, &outdata, &outsize)) {
4901 		if (outsize < ad->ad_out_size)
4902 			ad->ad_out_size = outsize;
4903 		if (outdata != NULL)
4904 			error = copyout(outdata, ad->ad_out_data,
4905 					ad->ad_out_size);
4906 	} else {
4907 		error = EINVAL;
4908 	}
4909 bad:
4910 	if ((ad->ad_id & ATH_DIAG_IN) && indata != NULL)
4911 		free(indata, M_TEMP);
4912 	if ((ad->ad_id & ATH_DIAG_DYN) && outdata != NULL)
4913 		free(outdata, M_TEMP);
4914 	return error;
4915 }
4916 #endif /* ATH_DIAGAPI */
4917 
4918 static int
4919 ath_ioctl(struct ifnet *ifp, u_long cmd, caddr_t data)
4920 {
4921 #define	IS_RUNNING(ifp) \
4922 	((ifp->if_flags & IFF_UP) && (ifp->if_drv_flags & IFF_DRV_RUNNING))
4923 	struct ath_softc *sc = ifp->if_softc;
4924 	struct ieee80211com *ic = ifp->if_l2com;
4925 	struct ifreq *ifr = (struct ifreq *)data;
4926 	const HAL_RATE_TABLE *rt;
4927 	int error = 0;
4928 
4929 	switch (cmd) {
4930 	case SIOCSIFFLAGS:
4931 		ATH_LOCK(sc);
4932 		if (IS_RUNNING(ifp)) {
4933 			/*
4934 			 * To avoid rescanning another access point,
4935 			 * do not call ath_init() here.  Instead,
4936 			 * only reflect promisc mode settings.
4937 			 */
4938 			ath_mode_init(sc);
4939 		} else if (ifp->if_flags & IFF_UP) {
4940 			/*
4941 			 * Beware of being called during attach/detach
4942 			 * to reset promiscuous mode.  In that case we
4943 			 * will still be marked UP but not RUNNING.
4944 			 * However trying to re-init the interface
4945 			 * is the wrong thing to do as we've already
4946 			 * torn down much of our state.  There's
4947 			 * probably a better way to deal with this.
4948 			 */
4949 			if (!sc->sc_invalid)
4950 				ath_init(sc);	/* XXX lose error */
4951 		} else {
4952 			ath_stop_locked(ifp);
4953 #ifdef notyet
4954 			/* XXX must wakeup in places like ath_vap_delete */
4955 			if (!sc->sc_invalid)
4956 				ath_hal_setpower(sc->sc_ah, HAL_PM_FULL_SLEEP);
4957 #endif
4958 		}
4959 		ATH_UNLOCK(sc);
4960 		break;
4961 	case SIOCGIFMEDIA:
4962 	case SIOCSIFMEDIA:
4963 		error = ifmedia_ioctl(ifp, ifr, &ic->ic_media, cmd);
4964 		break;
4965 	case SIOCGATHSTATS:
4966 		/* NB: embed these numbers to get a consistent view */
4967 		sc->sc_stats.ast_tx_packets = ifp->if_opackets;
4968 		sc->sc_stats.ast_rx_packets = ifp->if_ipackets;
4969 		sc->sc_stats.ast_tx_rssi = ATH_RSSI(sc->sc_halstats.ns_avgtxrssi);
4970 		sc->sc_stats.ast_rx_rssi = ATH_RSSI(sc->sc_halstats.ns_avgrssi);
4971 #ifdef IEEE80211_SUPPORT_TDMA
4972 		sc->sc_stats.ast_tdma_tsfadjp = TDMA_AVG(sc->sc_avgtsfdeltap);
4973 		sc->sc_stats.ast_tdma_tsfadjm = TDMA_AVG(sc->sc_avgtsfdeltam);
4974 #endif
4975 		rt = sc->sc_currates;
4976 		sc->sc_stats.ast_tx_rate =
4977 		    rt->info[sc->sc_txrix].dot11Rate &~ IEEE80211_RATE_BASIC;
4978 		if (rt->info[sc->sc_txrix].phy & IEEE80211_T_HT)
4979 			sc->sc_stats.ast_tx_rate |= IEEE80211_RATE_MCS;
4980 		return copyout(&sc->sc_stats,
4981 		    ifr->ifr_data, sizeof (sc->sc_stats));
4982 	case SIOCGATHAGSTATS:
4983 		return copyout(&sc->sc_aggr_stats,
4984 		    ifr->ifr_data, sizeof (sc->sc_aggr_stats));
4985 	case SIOCZATHSTATS:
4986 		error = priv_check(curthread, PRIV_DRIVER);
4987 		if (error == 0) {
4988 			memset(&sc->sc_stats, 0, sizeof(sc->sc_stats));
4989 			memset(&sc->sc_aggr_stats, 0,
4990 			    sizeof(sc->sc_aggr_stats));
4991 			memset(&sc->sc_intr_stats, 0,
4992 			    sizeof(sc->sc_intr_stats));
4993 		}
4994 		break;
4995 #ifdef ATH_DIAGAPI
4996 	case SIOCGATHDIAG:
4997 		error = ath_ioctl_diag(sc, (struct ath_diag *) ifr);
4998 		break;
4999 	case SIOCGATHPHYERR:
5000 		error = ath_ioctl_phyerr(sc,(struct ath_diag*) ifr);
5001 		break;
5002 #endif
5003 	case SIOCGIFADDR:
5004 		error = ether_ioctl(ifp, cmd, data);
5005 		break;
5006 	default:
5007 		error = EINVAL;
5008 		break;
5009 	}
5010 	return error;
5011 #undef IS_RUNNING
5012 }
5013 
5014 /*
5015  * Announce various information on device/driver attach.
5016  */
5017 static void
5018 ath_announce(struct ath_softc *sc)
5019 {
5020 	struct ifnet *ifp = sc->sc_ifp;
5021 	struct ath_hal *ah = sc->sc_ah;
5022 
5023 	if_printf(ifp, "AR%s mac %d.%d RF%s phy %d.%d\n",
5024 		ath_hal_mac_name(ah), ah->ah_macVersion, ah->ah_macRev,
5025 		ath_hal_rf_name(ah), ah->ah_phyRev >> 4, ah->ah_phyRev & 0xf);
5026 	if_printf(ifp, "2GHz radio: 0x%.4x; 5GHz radio: 0x%.4x\n",
5027 		ah->ah_analog2GhzRev, ah->ah_analog5GhzRev);
5028 	if (bootverbose) {
5029 		int i;
5030 		for (i = 0; i <= WME_AC_VO; i++) {
5031 			struct ath_txq *txq = sc->sc_ac2q[i];
5032 			if_printf(ifp, "Use hw queue %u for %s traffic\n",
5033 				txq->axq_qnum, ieee80211_wme_acnames[i]);
5034 		}
5035 		if_printf(ifp, "Use hw queue %u for CAB traffic\n",
5036 			sc->sc_cabq->axq_qnum);
5037 		if_printf(ifp, "Use hw queue %u for beacons\n", sc->sc_bhalq);
5038 	}
5039 	if (ath_rxbuf != ATH_RXBUF)
5040 		if_printf(ifp, "using %u rx buffers\n", ath_rxbuf);
5041 	if (ath_txbuf != ATH_TXBUF)
5042 		if_printf(ifp, "using %u tx buffers\n", ath_txbuf);
5043 	if (sc->sc_mcastkey && bootverbose)
5044 		if_printf(ifp, "using multicast key search\n");
5045 }
5046 
5047 static void
5048 ath_dfs_tasklet(void *p, int npending)
5049 {
5050 	struct ath_softc *sc = (struct ath_softc *) p;
5051 	struct ifnet *ifp = sc->sc_ifp;
5052 	struct ieee80211com *ic = ifp->if_l2com;
5053 
5054 	/*
5055 	 * If previous processing has found a radar event,
5056 	 * signal this to the net80211 layer to begin DFS
5057 	 * processing.
5058 	 */
5059 	if (ath_dfs_process_radar_event(sc, sc->sc_curchan)) {
5060 		/* DFS event found, initiate channel change */
5061 		/*
5062 		 * XXX doesn't currently tell us whether the event
5063 		 * XXX was found in the primary or extension
5064 		 * XXX channel!
5065 		 */
5066 		IEEE80211_LOCK(ic);
5067 		ieee80211_dfs_notify_radar(ic, sc->sc_curchan);
5068 		IEEE80211_UNLOCK(ic);
5069 	}
5070 }
5071 
5072 MODULE_VERSION(if_ath, 1);
5073 MODULE_DEPEND(if_ath, wlan, 1, 1, 1);          /* 802.11 media layer */
5074 #if	defined(IEEE80211_ALQ) || defined(AH_DEBUG_ALQ)
5075 MODULE_DEPEND(if_ath, alq, 1, 1, 1);
5076 #endif
5077