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