xref: /freebsd/sys/dev/ath/if_ath.c (revision 8d467c41b0f4f3a2065453d6bbf00def3bd76083)
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 /*
2892  * Allocate ath_buf entries but no descriptor contents.
2893  *
2894  * This is for RX EDMA where the descriptors are the header part of
2895  * the RX buffer.
2896  */
2897 int
2898 ath_descdma_setup_rx_edma(struct ath_softc *sc,
2899 	struct ath_descdma *dd, ath_bufhead *head,
2900 	const char *name, int nbuf, int rx_status_len)
2901 {
2902 	struct ifnet *ifp = sc->sc_ifp;
2903 	struct ath_buf *bf;
2904 	int i, bsize, error;
2905 
2906 	DPRINTF(sc, ATH_DEBUG_RESET, "%s: %s DMA: %u buffers\n",
2907 	    __func__, name, nbuf);
2908 
2909 	dd->dd_name = name;
2910 	/*
2911 	 * This is (mostly) purely for show.  We're not allocating any actual
2912 	 * descriptors here as EDMA RX has the descriptor be part
2913 	 * of the RX buffer.
2914 	 *
2915 	 * However, dd_desc_len is used by ath_descdma_free() to determine
2916 	 * whether we have already freed this DMA mapping.
2917 	 */
2918 	dd->dd_desc_len = rx_status_len;
2919 
2920 	/* allocate rx buffers */
2921 	bsize = sizeof(struct ath_buf) * nbuf;
2922 	bf = malloc(bsize, M_ATHDEV, M_NOWAIT | M_ZERO);
2923 	if (bf == NULL) {
2924 		if_printf(ifp, "malloc of %s buffers failed, size %u\n",
2925 			dd->dd_name, bsize);
2926 		goto fail3;
2927 	}
2928 	dd->dd_bufptr = bf;
2929 
2930 	TAILQ_INIT(head);
2931 	for (i = 0; i < nbuf; i++, bf++) {
2932 		bf->bf_desc = NULL;
2933 		bf->bf_daddr = 0;
2934 		bf->bf_lastds = NULL;	/* Just an initial value */
2935 
2936 		error = bus_dmamap_create(sc->sc_dmat, BUS_DMA_NOWAIT,
2937 				&bf->bf_dmamap);
2938 		if (error != 0) {
2939 			if_printf(ifp, "unable to create dmamap for %s "
2940 				"buffer %u, error %u\n", dd->dd_name, i, error);
2941 			ath_descdma_cleanup(sc, dd, head);
2942 			return error;
2943 		}
2944 		TAILQ_INSERT_TAIL(head, bf, bf_list);
2945 	}
2946 	return 0;
2947 fail3:
2948 	memset(dd, 0, sizeof(*dd));
2949 	return error;
2950 }
2951 
2952 void
2953 ath_descdma_cleanup(struct ath_softc *sc,
2954 	struct ath_descdma *dd, ath_bufhead *head)
2955 {
2956 	struct ath_buf *bf;
2957 	struct ieee80211_node *ni;
2958 
2959 	if (dd->dd_dmamap != 0) {
2960 		bus_dmamap_unload(dd->dd_dmat, dd->dd_dmamap);
2961 		bus_dmamem_free(dd->dd_dmat, dd->dd_desc, dd->dd_dmamap);
2962 		bus_dmamap_destroy(dd->dd_dmat, dd->dd_dmamap);
2963 		bus_dma_tag_destroy(dd->dd_dmat);
2964 	}
2965 
2966 	TAILQ_FOREACH(bf, head, bf_list) {
2967 		if (bf->bf_m) {
2968 			m_freem(bf->bf_m);
2969 			bf->bf_m = NULL;
2970 		}
2971 		if (bf->bf_dmamap != NULL) {
2972 			bus_dmamap_destroy(sc->sc_dmat, bf->bf_dmamap);
2973 			bf->bf_dmamap = NULL;
2974 		}
2975 		ni = bf->bf_node;
2976 		bf->bf_node = NULL;
2977 		if (ni != NULL) {
2978 			/*
2979 			 * Reclaim node reference.
2980 			 */
2981 			ieee80211_free_node(ni);
2982 		}
2983 	}
2984 
2985 	TAILQ_INIT(head);
2986 	free(dd->dd_bufptr, M_ATHDEV);
2987 	memset(dd, 0, sizeof(*dd));
2988 }
2989 
2990 static int
2991 ath_desc_alloc(struct ath_softc *sc)
2992 {
2993 	int error;
2994 
2995 	error = ath_descdma_setup(sc, &sc->sc_txdma, &sc->sc_txbuf,
2996 			"tx", ath_txbuf, ATH_TXDESC);
2997 	if (error != 0) {
2998 		return error;
2999 	}
3000 	sc->sc_txbuf_cnt = ath_txbuf;
3001 
3002 	error = ath_descdma_setup(sc, &sc->sc_txdma_mgmt, &sc->sc_txbuf_mgmt,
3003 			"tx_mgmt", ath_txbuf_mgmt, ATH_TXDESC);
3004 	if (error != 0) {
3005 		ath_descdma_cleanup(sc, &sc->sc_txdma, &sc->sc_txbuf);
3006 		return error;
3007 	}
3008 
3009 	/*
3010 	 * XXX mark txbuf_mgmt frames with ATH_BUF_MGMT, so the
3011 	 * flag doesn't have to be set in ath_getbuf_locked().
3012 	 */
3013 
3014 	error = ath_descdma_setup(sc, &sc->sc_bdma, &sc->sc_bbuf,
3015 			"beacon", ATH_BCBUF, 1);
3016 	if (error != 0) {
3017 		ath_descdma_cleanup(sc, &sc->sc_txdma, &sc->sc_txbuf);
3018 		ath_descdma_cleanup(sc, &sc->sc_txdma_mgmt,
3019 		    &sc->sc_txbuf_mgmt);
3020 		return error;
3021 	}
3022 	return 0;
3023 }
3024 
3025 static void
3026 ath_desc_free(struct ath_softc *sc)
3027 {
3028 
3029 	if (sc->sc_bdma.dd_desc_len != 0)
3030 		ath_descdma_cleanup(sc, &sc->sc_bdma, &sc->sc_bbuf);
3031 	if (sc->sc_txdma.dd_desc_len != 0)
3032 		ath_descdma_cleanup(sc, &sc->sc_txdma, &sc->sc_txbuf);
3033 	if (sc->sc_txdma_mgmt.dd_desc_len != 0)
3034 		ath_descdma_cleanup(sc, &sc->sc_txdma_mgmt,
3035 		    &sc->sc_txbuf_mgmt);
3036 }
3037 
3038 static struct ieee80211_node *
3039 ath_node_alloc(struct ieee80211vap *vap, const uint8_t mac[IEEE80211_ADDR_LEN])
3040 {
3041 	struct ieee80211com *ic = vap->iv_ic;
3042 	struct ath_softc *sc = ic->ic_ifp->if_softc;
3043 	const size_t space = sizeof(struct ath_node) + sc->sc_rc->arc_space;
3044 	struct ath_node *an;
3045 
3046 	an = malloc(space, M_80211_NODE, M_NOWAIT|M_ZERO);
3047 	if (an == NULL) {
3048 		/* XXX stat+msg */
3049 		return NULL;
3050 	}
3051 	ath_rate_node_init(sc, an);
3052 
3053 	/* Setup the mutex - there's no associd yet so set the name to NULL */
3054 	snprintf(an->an_name, sizeof(an->an_name), "%s: node %p",
3055 	    device_get_nameunit(sc->sc_dev), an);
3056 	mtx_init(&an->an_mtx, an->an_name, NULL, MTX_DEF);
3057 
3058 	/* XXX setup ath_tid */
3059 	ath_tx_tid_init(sc, an);
3060 
3061 	DPRINTF(sc, ATH_DEBUG_NODE, "%s: an %p\n", __func__, an);
3062 	return &an->an_node;
3063 }
3064 
3065 static void
3066 ath_node_cleanup(struct ieee80211_node *ni)
3067 {
3068 	struct ieee80211com *ic = ni->ni_ic;
3069 	struct ath_softc *sc = ic->ic_ifp->if_softc;
3070 
3071 	/* Cleanup ath_tid, free unused bufs, unlink bufs in TXQ */
3072 	ath_tx_node_flush(sc, ATH_NODE(ni));
3073 	ath_rate_node_cleanup(sc, ATH_NODE(ni));
3074 	sc->sc_node_cleanup(ni);
3075 }
3076 
3077 static void
3078 ath_node_free(struct ieee80211_node *ni)
3079 {
3080 	struct ieee80211com *ic = ni->ni_ic;
3081 	struct ath_softc *sc = ic->ic_ifp->if_softc;
3082 
3083 	DPRINTF(sc, ATH_DEBUG_NODE, "%s: ni %p\n", __func__, ni);
3084 	mtx_destroy(&ATH_NODE(ni)->an_mtx);
3085 	sc->sc_node_free(ni);
3086 }
3087 
3088 static void
3089 ath_node_getsignal(const struct ieee80211_node *ni, int8_t *rssi, int8_t *noise)
3090 {
3091 	struct ieee80211com *ic = ni->ni_ic;
3092 	struct ath_softc *sc = ic->ic_ifp->if_softc;
3093 	struct ath_hal *ah = sc->sc_ah;
3094 
3095 	*rssi = ic->ic_node_getrssi(ni);
3096 	if (ni->ni_chan != IEEE80211_CHAN_ANYC)
3097 		*noise = ath_hal_getchannoise(ah, ni->ni_chan);
3098 	else
3099 		*noise = -95;		/* nominally correct */
3100 }
3101 
3102 /*
3103  * Set the default antenna.
3104  */
3105 void
3106 ath_setdefantenna(struct ath_softc *sc, u_int antenna)
3107 {
3108 	struct ath_hal *ah = sc->sc_ah;
3109 
3110 	/* XXX block beacon interrupts */
3111 	ath_hal_setdefantenna(ah, antenna);
3112 	if (sc->sc_defant != antenna)
3113 		sc->sc_stats.ast_ant_defswitch++;
3114 	sc->sc_defant = antenna;
3115 	sc->sc_rxotherant = 0;
3116 }
3117 
3118 static void
3119 ath_txq_init(struct ath_softc *sc, struct ath_txq *txq, int qnum)
3120 {
3121 	txq->axq_qnum = qnum;
3122 	txq->axq_ac = 0;
3123 	txq->axq_depth = 0;
3124 	txq->axq_aggr_depth = 0;
3125 	txq->axq_intrcnt = 0;
3126 	txq->axq_link = NULL;
3127 	txq->axq_softc = sc;
3128 	TAILQ_INIT(&txq->axq_q);
3129 	TAILQ_INIT(&txq->axq_tidq);
3130 	ATH_TXQ_LOCK_INIT(sc, txq);
3131 }
3132 
3133 /*
3134  * Setup a h/w transmit queue.
3135  */
3136 static struct ath_txq *
3137 ath_txq_setup(struct ath_softc *sc, int qtype, int subtype)
3138 {
3139 #define	N(a)	(sizeof(a)/sizeof(a[0]))
3140 	struct ath_hal *ah = sc->sc_ah;
3141 	HAL_TXQ_INFO qi;
3142 	int qnum;
3143 
3144 	memset(&qi, 0, sizeof(qi));
3145 	qi.tqi_subtype = subtype;
3146 	qi.tqi_aifs = HAL_TXQ_USEDEFAULT;
3147 	qi.tqi_cwmin = HAL_TXQ_USEDEFAULT;
3148 	qi.tqi_cwmax = HAL_TXQ_USEDEFAULT;
3149 	/*
3150 	 * Enable interrupts only for EOL and DESC conditions.
3151 	 * We mark tx descriptors to receive a DESC interrupt
3152 	 * when a tx queue gets deep; otherwise waiting for the
3153 	 * EOL to reap descriptors.  Note that this is done to
3154 	 * reduce interrupt load and this only defers reaping
3155 	 * descriptors, never transmitting frames.  Aside from
3156 	 * reducing interrupts this also permits more concurrency.
3157 	 * The only potential downside is if the tx queue backs
3158 	 * up in which case the top half of the kernel may backup
3159 	 * due to a lack of tx descriptors.
3160 	 */
3161 	qi.tqi_qflags = HAL_TXQ_TXEOLINT_ENABLE | HAL_TXQ_TXDESCINT_ENABLE;
3162 	qnum = ath_hal_setuptxqueue(ah, qtype, &qi);
3163 	if (qnum == -1) {
3164 		/*
3165 		 * NB: don't print a message, this happens
3166 		 * normally on parts with too few tx queues
3167 		 */
3168 		return NULL;
3169 	}
3170 	if (qnum >= N(sc->sc_txq)) {
3171 		device_printf(sc->sc_dev,
3172 			"hal qnum %u out of range, max %zu!\n",
3173 			qnum, N(sc->sc_txq));
3174 		ath_hal_releasetxqueue(ah, qnum);
3175 		return NULL;
3176 	}
3177 	if (!ATH_TXQ_SETUP(sc, qnum)) {
3178 		ath_txq_init(sc, &sc->sc_txq[qnum], qnum);
3179 		sc->sc_txqsetup |= 1<<qnum;
3180 	}
3181 	return &sc->sc_txq[qnum];
3182 #undef N
3183 }
3184 
3185 /*
3186  * Setup a hardware data transmit queue for the specified
3187  * access control.  The hal may not support all requested
3188  * queues in which case it will return a reference to a
3189  * previously setup queue.  We record the mapping from ac's
3190  * to h/w queues for use by ath_tx_start and also track
3191  * the set of h/w queues being used to optimize work in the
3192  * transmit interrupt handler and related routines.
3193  */
3194 static int
3195 ath_tx_setup(struct ath_softc *sc, int ac, int haltype)
3196 {
3197 #define	N(a)	(sizeof(a)/sizeof(a[0]))
3198 	struct ath_txq *txq;
3199 
3200 	if (ac >= N(sc->sc_ac2q)) {
3201 		device_printf(sc->sc_dev, "AC %u out of range, max %zu!\n",
3202 			ac, N(sc->sc_ac2q));
3203 		return 0;
3204 	}
3205 	txq = ath_txq_setup(sc, HAL_TX_QUEUE_DATA, haltype);
3206 	if (txq != NULL) {
3207 		txq->axq_ac = ac;
3208 		sc->sc_ac2q[ac] = txq;
3209 		return 1;
3210 	} else
3211 		return 0;
3212 #undef N
3213 }
3214 
3215 /*
3216  * Update WME parameters for a transmit queue.
3217  */
3218 static int
3219 ath_txq_update(struct ath_softc *sc, int ac)
3220 {
3221 #define	ATH_EXPONENT_TO_VALUE(v)	((1<<v)-1)
3222 #define	ATH_TXOP_TO_US(v)		(v<<5)
3223 	struct ifnet *ifp = sc->sc_ifp;
3224 	struct ieee80211com *ic = ifp->if_l2com;
3225 	struct ath_txq *txq = sc->sc_ac2q[ac];
3226 	struct wmeParams *wmep = &ic->ic_wme.wme_chanParams.cap_wmeParams[ac];
3227 	struct ath_hal *ah = sc->sc_ah;
3228 	HAL_TXQ_INFO qi;
3229 
3230 	ath_hal_gettxqueueprops(ah, txq->axq_qnum, &qi);
3231 #ifdef IEEE80211_SUPPORT_TDMA
3232 	if (sc->sc_tdma) {
3233 		/*
3234 		 * AIFS is zero so there's no pre-transmit wait.  The
3235 		 * burst time defines the slot duration and is configured
3236 		 * through net80211.  The QCU is setup to not do post-xmit
3237 		 * back off, lockout all lower-priority QCU's, and fire
3238 		 * off the DMA beacon alert timer which is setup based
3239 		 * on the slot configuration.
3240 		 */
3241 		qi.tqi_qflags = HAL_TXQ_TXOKINT_ENABLE
3242 			      | HAL_TXQ_TXERRINT_ENABLE
3243 			      | HAL_TXQ_TXURNINT_ENABLE
3244 			      | HAL_TXQ_TXEOLINT_ENABLE
3245 			      | HAL_TXQ_DBA_GATED
3246 			      | HAL_TXQ_BACKOFF_DISABLE
3247 			      | HAL_TXQ_ARB_LOCKOUT_GLOBAL
3248 			      ;
3249 		qi.tqi_aifs = 0;
3250 		/* XXX +dbaprep? */
3251 		qi.tqi_readyTime = sc->sc_tdmaslotlen;
3252 		qi.tqi_burstTime = qi.tqi_readyTime;
3253 	} else {
3254 #endif
3255 		/*
3256 		 * XXX shouldn't this just use the default flags
3257 		 * used in the previous queue setup?
3258 		 */
3259 		qi.tqi_qflags = HAL_TXQ_TXOKINT_ENABLE
3260 			      | HAL_TXQ_TXERRINT_ENABLE
3261 			      | HAL_TXQ_TXDESCINT_ENABLE
3262 			      | HAL_TXQ_TXURNINT_ENABLE
3263 			      | HAL_TXQ_TXEOLINT_ENABLE
3264 			      ;
3265 		qi.tqi_aifs = wmep->wmep_aifsn;
3266 		qi.tqi_cwmin = ATH_EXPONENT_TO_VALUE(wmep->wmep_logcwmin);
3267 		qi.tqi_cwmax = ATH_EXPONENT_TO_VALUE(wmep->wmep_logcwmax);
3268 		qi.tqi_readyTime = 0;
3269 		qi.tqi_burstTime = ATH_TXOP_TO_US(wmep->wmep_txopLimit);
3270 #ifdef IEEE80211_SUPPORT_TDMA
3271 	}
3272 #endif
3273 
3274 	DPRINTF(sc, ATH_DEBUG_RESET,
3275 	    "%s: Q%u qflags 0x%x aifs %u cwmin %u cwmax %u burstTime %u\n",
3276 	    __func__, txq->axq_qnum, qi.tqi_qflags,
3277 	    qi.tqi_aifs, qi.tqi_cwmin, qi.tqi_cwmax, qi.tqi_burstTime);
3278 
3279 	if (!ath_hal_settxqueueprops(ah, txq->axq_qnum, &qi)) {
3280 		if_printf(ifp, "unable to update hardware queue "
3281 			"parameters for %s traffic!\n",
3282 			ieee80211_wme_acnames[ac]);
3283 		return 0;
3284 	} else {
3285 		ath_hal_resettxqueue(ah, txq->axq_qnum); /* push to h/w */
3286 		return 1;
3287 	}
3288 #undef ATH_TXOP_TO_US
3289 #undef ATH_EXPONENT_TO_VALUE
3290 }
3291 
3292 /*
3293  * Callback from the 802.11 layer to update WME parameters.
3294  */
3295 int
3296 ath_wme_update(struct ieee80211com *ic)
3297 {
3298 	struct ath_softc *sc = ic->ic_ifp->if_softc;
3299 
3300 	return !ath_txq_update(sc, WME_AC_BE) ||
3301 	    !ath_txq_update(sc, WME_AC_BK) ||
3302 	    !ath_txq_update(sc, WME_AC_VI) ||
3303 	    !ath_txq_update(sc, WME_AC_VO) ? EIO : 0;
3304 }
3305 
3306 /*
3307  * Reclaim resources for a setup queue.
3308  */
3309 static void
3310 ath_tx_cleanupq(struct ath_softc *sc, struct ath_txq *txq)
3311 {
3312 
3313 	ath_hal_releasetxqueue(sc->sc_ah, txq->axq_qnum);
3314 	ATH_TXQ_LOCK_DESTROY(txq);
3315 	sc->sc_txqsetup &= ~(1<<txq->axq_qnum);
3316 }
3317 
3318 /*
3319  * Reclaim all tx queue resources.
3320  */
3321 static void
3322 ath_tx_cleanup(struct ath_softc *sc)
3323 {
3324 	int i;
3325 
3326 	ATH_TXBUF_LOCK_DESTROY(sc);
3327 	for (i = 0; i < HAL_NUM_TX_QUEUES; i++)
3328 		if (ATH_TXQ_SETUP(sc, i))
3329 			ath_tx_cleanupq(sc, &sc->sc_txq[i]);
3330 }
3331 
3332 /*
3333  * Return h/w rate index for an IEEE rate (w/o basic rate bit)
3334  * using the current rates in sc_rixmap.
3335  */
3336 int
3337 ath_tx_findrix(const struct ath_softc *sc, uint8_t rate)
3338 {
3339 	int rix = sc->sc_rixmap[rate];
3340 	/* NB: return lowest rix for invalid rate */
3341 	return (rix == 0xff ? 0 : rix);
3342 }
3343 
3344 static void
3345 ath_tx_update_stats(struct ath_softc *sc, struct ath_tx_status *ts,
3346     struct ath_buf *bf)
3347 {
3348 	struct ieee80211_node *ni = bf->bf_node;
3349 	struct ifnet *ifp = sc->sc_ifp;
3350 	struct ieee80211com *ic = ifp->if_l2com;
3351 	int sr, lr, pri;
3352 
3353 	if (ts->ts_status == 0) {
3354 		u_int8_t txant = ts->ts_antenna;
3355 		sc->sc_stats.ast_ant_tx[txant]++;
3356 		sc->sc_ant_tx[txant]++;
3357 		if (ts->ts_finaltsi != 0)
3358 			sc->sc_stats.ast_tx_altrate++;
3359 		pri = M_WME_GETAC(bf->bf_m);
3360 		if (pri >= WME_AC_VO)
3361 			ic->ic_wme.wme_hipri_traffic++;
3362 		if ((bf->bf_state.bfs_txflags & HAL_TXDESC_NOACK) == 0)
3363 			ni->ni_inact = ni->ni_inact_reload;
3364 	} else {
3365 		if (ts->ts_status & HAL_TXERR_XRETRY)
3366 			sc->sc_stats.ast_tx_xretries++;
3367 		if (ts->ts_status & HAL_TXERR_FIFO)
3368 			sc->sc_stats.ast_tx_fifoerr++;
3369 		if (ts->ts_status & HAL_TXERR_FILT)
3370 			sc->sc_stats.ast_tx_filtered++;
3371 		if (ts->ts_status & HAL_TXERR_XTXOP)
3372 			sc->sc_stats.ast_tx_xtxop++;
3373 		if (ts->ts_status & HAL_TXERR_TIMER_EXPIRED)
3374 			sc->sc_stats.ast_tx_timerexpired++;
3375 
3376 		if (ts->ts_status & HAL_TX_DATA_UNDERRUN)
3377 			sc->sc_stats.ast_tx_data_underrun++;
3378 		if (ts->ts_status & HAL_TX_DELIM_UNDERRUN)
3379 			sc->sc_stats.ast_tx_delim_underrun++;
3380 
3381 		if (bf->bf_m->m_flags & M_FF)
3382 			sc->sc_stats.ast_ff_txerr++;
3383 	}
3384 	/* XXX when is this valid? */
3385 	if (ts->ts_status & HAL_TX_DESC_CFG_ERR)
3386 		sc->sc_stats.ast_tx_desccfgerr++;
3387 
3388 	sr = ts->ts_shortretry;
3389 	lr = ts->ts_longretry;
3390 	sc->sc_stats.ast_tx_shortretry += sr;
3391 	sc->sc_stats.ast_tx_longretry += lr;
3392 
3393 }
3394 
3395 /*
3396  * The default completion. If fail is 1, this means
3397  * "please don't retry the frame, and just return -1 status
3398  * to the net80211 stack.
3399  */
3400 void
3401 ath_tx_default_comp(struct ath_softc *sc, struct ath_buf *bf, int fail)
3402 {
3403 	struct ath_tx_status *ts = &bf->bf_status.ds_txstat;
3404 	int st;
3405 
3406 	if (fail == 1)
3407 		st = -1;
3408 	else
3409 		st = ((bf->bf_state.bfs_txflags & HAL_TXDESC_NOACK) == 0) ?
3410 		    ts->ts_status : HAL_TXERR_XRETRY;
3411 
3412 	if (bf->bf_state.bfs_dobaw)
3413 		device_printf(sc->sc_dev,
3414 		    "%s: bf %p: seqno %d: dobaw should've been cleared!\n",
3415 		    __func__,
3416 		    bf,
3417 		    SEQNO(bf->bf_state.bfs_seqno));
3418 	if (bf->bf_next != NULL)
3419 		device_printf(sc->sc_dev,
3420 		    "%s: bf %p: seqno %d: bf_next not NULL!\n",
3421 		    __func__,
3422 		    bf,
3423 		    SEQNO(bf->bf_state.bfs_seqno));
3424 
3425 	/*
3426 	 * Do any tx complete callback.  Note this must
3427 	 * be done before releasing the node reference.
3428 	 * This will free the mbuf, release the net80211
3429 	 * node and recycle the ath_buf.
3430 	 */
3431 	ath_tx_freebuf(sc, bf, st);
3432 }
3433 
3434 /*
3435  * Update rate control with the given completion status.
3436  */
3437 void
3438 ath_tx_update_ratectrl(struct ath_softc *sc, struct ieee80211_node *ni,
3439     struct ath_rc_series *rc, struct ath_tx_status *ts, int frmlen,
3440     int nframes, int nbad)
3441 {
3442 	struct ath_node *an;
3443 
3444 	/* Only for unicast frames */
3445 	if (ni == NULL)
3446 		return;
3447 
3448 	an = ATH_NODE(ni);
3449 
3450 	if ((ts->ts_status & HAL_TXERR_FILT) == 0) {
3451 		ATH_NODE_LOCK(an);
3452 		ath_rate_tx_complete(sc, an, rc, ts, frmlen, nframes, nbad);
3453 		ATH_NODE_UNLOCK(an);
3454 	}
3455 }
3456 
3457 /*
3458  * Update the busy status of the last frame on the free list.
3459  * When doing TDMA, the busy flag tracks whether the hardware
3460  * currently points to this buffer or not, and thus gated DMA
3461  * may restart by re-reading the last descriptor in this
3462  * buffer.
3463  *
3464  * This should be called in the completion function once one
3465  * of the buffers has been used.
3466  */
3467 static void
3468 ath_tx_update_busy(struct ath_softc *sc)
3469 {
3470 	struct ath_buf *last;
3471 
3472 	/*
3473 	 * Since the last frame may still be marked
3474 	 * as ATH_BUF_BUSY, unmark it here before
3475 	 * finishing the frame processing.
3476 	 * Since we've completed a frame (aggregate
3477 	 * or otherwise), the hardware has moved on
3478 	 * and is no longer referencing the previous
3479 	 * descriptor.
3480 	 */
3481 	ATH_TXBUF_LOCK_ASSERT(sc);
3482 	last = TAILQ_LAST(&sc->sc_txbuf_mgmt, ath_bufhead_s);
3483 	if (last != NULL)
3484 		last->bf_flags &= ~ATH_BUF_BUSY;
3485 	last = TAILQ_LAST(&sc->sc_txbuf, ath_bufhead_s);
3486 	if (last != NULL)
3487 		last->bf_flags &= ~ATH_BUF_BUSY;
3488 }
3489 
3490 /*
3491  * Process completed xmit descriptors from the specified queue.
3492  * Kick the packet scheduler if needed. This can occur from this
3493  * particular task.
3494  */
3495 static int
3496 ath_tx_processq(struct ath_softc *sc, struct ath_txq *txq, int dosched)
3497 {
3498 	struct ath_hal *ah = sc->sc_ah;
3499 	struct ath_buf *bf;
3500 	struct ath_desc *ds;
3501 	struct ath_tx_status *ts;
3502 	struct ieee80211_node *ni;
3503 	struct ath_node *an;
3504 #ifdef	IEEE80211_SUPPORT_SUPERG
3505 	struct ieee80211com *ic = sc->sc_ifp->if_l2com;
3506 #endif	/* IEEE80211_SUPPORT_SUPERG */
3507 	int nacked;
3508 	HAL_STATUS status;
3509 
3510 	DPRINTF(sc, ATH_DEBUG_TX_PROC, "%s: tx queue %u head %p link %p\n",
3511 		__func__, txq->axq_qnum,
3512 		(caddr_t)(uintptr_t) ath_hal_gettxbuf(sc->sc_ah, txq->axq_qnum),
3513 		txq->axq_link);
3514 	nacked = 0;
3515 	for (;;) {
3516 		ATH_TXQ_LOCK(txq);
3517 		txq->axq_intrcnt = 0;	/* reset periodic desc intr count */
3518 		bf = TAILQ_FIRST(&txq->axq_q);
3519 		if (bf == NULL) {
3520 			ATH_TXQ_UNLOCK(txq);
3521 			break;
3522 		}
3523 		ds = bf->bf_lastds;	/* XXX must be setup correctly! */
3524 		ts = &bf->bf_status.ds_txstat;
3525 		status = ath_hal_txprocdesc(ah, ds, ts);
3526 #ifdef ATH_DEBUG
3527 		if (sc->sc_debug & ATH_DEBUG_XMIT_DESC)
3528 			ath_printtxbuf(sc, bf, txq->axq_qnum, 0,
3529 			    status == HAL_OK);
3530 		else if ((sc->sc_debug & ATH_DEBUG_RESET) && (dosched == 0)) {
3531 			ath_printtxbuf(sc, bf, txq->axq_qnum, 0,
3532 			    status == HAL_OK);
3533 		}
3534 #endif
3535 		if (status == HAL_EINPROGRESS) {
3536 			ATH_TXQ_UNLOCK(txq);
3537 			break;
3538 		}
3539 		ATH_TXQ_REMOVE(txq, bf, bf_list);
3540 #ifdef IEEE80211_SUPPORT_TDMA
3541 		if (txq->axq_depth > 0) {
3542 			/*
3543 			 * More frames follow.  Mark the buffer busy
3544 			 * so it's not re-used while the hardware may
3545 			 * still re-read the link field in the descriptor.
3546 			 *
3547 			 * Use the last buffer in an aggregate as that
3548 			 * is where the hardware may be - intermediate
3549 			 * descriptors won't be "busy".
3550 			 */
3551 			bf->bf_last->bf_flags |= ATH_BUF_BUSY;
3552 		} else
3553 #else
3554 		if (txq->axq_depth == 0)
3555 #endif
3556 			txq->axq_link = NULL;
3557 		if (bf->bf_state.bfs_aggr)
3558 			txq->axq_aggr_depth--;
3559 
3560 		ni = bf->bf_node;
3561 		/*
3562 		 * If unicast frame was ack'd update RSSI,
3563 		 * including the last rx time used to
3564 		 * workaround phantom bmiss interrupts.
3565 		 */
3566 		if (ni != NULL && ts->ts_status == 0 &&
3567 		    ((bf->bf_state.bfs_txflags & HAL_TXDESC_NOACK) == 0)) {
3568 			nacked++;
3569 			sc->sc_stats.ast_tx_rssi = ts->ts_rssi;
3570 			ATH_RSSI_LPF(sc->sc_halstats.ns_avgtxrssi,
3571 				ts->ts_rssi);
3572 		}
3573 		ATH_TXQ_UNLOCK(txq);
3574 
3575 		/* If unicast frame, update general statistics */
3576 		if (ni != NULL) {
3577 			an = ATH_NODE(ni);
3578 			/* update statistics */
3579 			ath_tx_update_stats(sc, ts, bf);
3580 		}
3581 
3582 		/*
3583 		 * Call the completion handler.
3584 		 * The completion handler is responsible for
3585 		 * calling the rate control code.
3586 		 *
3587 		 * Frames with no completion handler get the
3588 		 * rate control code called here.
3589 		 */
3590 		if (bf->bf_comp == NULL) {
3591 			if ((ts->ts_status & HAL_TXERR_FILT) == 0 &&
3592 			    (bf->bf_state.bfs_txflags & HAL_TXDESC_NOACK) == 0) {
3593 				/*
3594 				 * XXX assume this isn't an aggregate
3595 				 * frame.
3596 				 */
3597 				ath_tx_update_ratectrl(sc, ni,
3598 				     bf->bf_state.bfs_rc, ts,
3599 				    bf->bf_state.bfs_pktlen, 1,
3600 				    (ts->ts_status == 0 ? 0 : 1));
3601 			}
3602 			ath_tx_default_comp(sc, bf, 0);
3603 		} else
3604 			bf->bf_comp(sc, bf, 0);
3605 	}
3606 #ifdef IEEE80211_SUPPORT_SUPERG
3607 	/*
3608 	 * Flush fast-frame staging queue when traffic slows.
3609 	 */
3610 	if (txq->axq_depth <= 1)
3611 		ieee80211_ff_flush(ic, txq->axq_ac);
3612 #endif
3613 
3614 	/* Kick the TXQ scheduler */
3615 	if (dosched) {
3616 		ATH_TXQ_LOCK(txq);
3617 		ath_txq_sched(sc, txq);
3618 		ATH_TXQ_UNLOCK(txq);
3619 	}
3620 
3621 	return nacked;
3622 }
3623 
3624 #define	TXQACTIVE(t, q)		( (t) & (1 << (q)))
3625 
3626 /*
3627  * Deferred processing of transmit interrupt; special-cased
3628  * for a single hardware transmit queue (e.g. 5210 and 5211).
3629  */
3630 static void
3631 ath_tx_proc_q0(void *arg, int npending)
3632 {
3633 	struct ath_softc *sc = arg;
3634 	struct ifnet *ifp = sc->sc_ifp;
3635 	uint32_t txqs;
3636 
3637 	ATH_PCU_LOCK(sc);
3638 	sc->sc_txproc_cnt++;
3639 	txqs = sc->sc_txq_active;
3640 	sc->sc_txq_active &= ~txqs;
3641 	ATH_PCU_UNLOCK(sc);
3642 
3643 	if (TXQACTIVE(txqs, 0) && ath_tx_processq(sc, &sc->sc_txq[0], 1))
3644 		/* XXX why is lastrx updated in tx code? */
3645 		sc->sc_lastrx = ath_hal_gettsf64(sc->sc_ah);
3646 	if (TXQACTIVE(txqs, sc->sc_cabq->axq_qnum))
3647 		ath_tx_processq(sc, sc->sc_cabq, 1);
3648 	IF_LOCK(&ifp->if_snd);
3649 	ifp->if_drv_flags &= ~IFF_DRV_OACTIVE;
3650 	IF_UNLOCK(&ifp->if_snd);
3651 	sc->sc_wd_timer = 0;
3652 
3653 	if (sc->sc_softled)
3654 		ath_led_event(sc, sc->sc_txrix);
3655 
3656 	ATH_PCU_LOCK(sc);
3657 	sc->sc_txproc_cnt--;
3658 	ATH_PCU_UNLOCK(sc);
3659 
3660 	ath_tx_kick(sc);
3661 }
3662 
3663 /*
3664  * Deferred processing of transmit interrupt; special-cased
3665  * for four hardware queues, 0-3 (e.g. 5212 w/ WME support).
3666  */
3667 static void
3668 ath_tx_proc_q0123(void *arg, int npending)
3669 {
3670 	struct ath_softc *sc = arg;
3671 	struct ifnet *ifp = sc->sc_ifp;
3672 	int nacked;
3673 	uint32_t txqs;
3674 
3675 	ATH_PCU_LOCK(sc);
3676 	sc->sc_txproc_cnt++;
3677 	txqs = sc->sc_txq_active;
3678 	sc->sc_txq_active &= ~txqs;
3679 	ATH_PCU_UNLOCK(sc);
3680 
3681 	/*
3682 	 * Process each active queue.
3683 	 */
3684 	nacked = 0;
3685 	if (TXQACTIVE(txqs, 0))
3686 		nacked += ath_tx_processq(sc, &sc->sc_txq[0], 1);
3687 	if (TXQACTIVE(txqs, 1))
3688 		nacked += ath_tx_processq(sc, &sc->sc_txq[1], 1);
3689 	if (TXQACTIVE(txqs, 2))
3690 		nacked += ath_tx_processq(sc, &sc->sc_txq[2], 1);
3691 	if (TXQACTIVE(txqs, 3))
3692 		nacked += ath_tx_processq(sc, &sc->sc_txq[3], 1);
3693 	if (TXQACTIVE(txqs, sc->sc_cabq->axq_qnum))
3694 		ath_tx_processq(sc, sc->sc_cabq, 1);
3695 	if (nacked)
3696 		sc->sc_lastrx = ath_hal_gettsf64(sc->sc_ah);
3697 
3698 	IF_LOCK(&ifp->if_snd);
3699 	ifp->if_drv_flags &= ~IFF_DRV_OACTIVE;
3700 	IF_UNLOCK(&ifp->if_snd);
3701 	sc->sc_wd_timer = 0;
3702 
3703 	if (sc->sc_softled)
3704 		ath_led_event(sc, sc->sc_txrix);
3705 
3706 	ATH_PCU_LOCK(sc);
3707 	sc->sc_txproc_cnt--;
3708 	ATH_PCU_UNLOCK(sc);
3709 
3710 	ath_tx_kick(sc);
3711 }
3712 
3713 /*
3714  * Deferred processing of transmit interrupt.
3715  */
3716 static void
3717 ath_tx_proc(void *arg, int npending)
3718 {
3719 	struct ath_softc *sc = arg;
3720 	struct ifnet *ifp = sc->sc_ifp;
3721 	int i, nacked;
3722 	uint32_t txqs;
3723 
3724 	ATH_PCU_LOCK(sc);
3725 	sc->sc_txproc_cnt++;
3726 	txqs = sc->sc_txq_active;
3727 	sc->sc_txq_active &= ~txqs;
3728 	ATH_PCU_UNLOCK(sc);
3729 
3730 	/*
3731 	 * Process each active queue.
3732 	 */
3733 	nacked = 0;
3734 	for (i = 0; i < HAL_NUM_TX_QUEUES; i++)
3735 		if (ATH_TXQ_SETUP(sc, i) && TXQACTIVE(txqs, i))
3736 			nacked += ath_tx_processq(sc, &sc->sc_txq[i], 1);
3737 	if (nacked)
3738 		sc->sc_lastrx = ath_hal_gettsf64(sc->sc_ah);
3739 
3740 	/* XXX check this inside of IF_LOCK? */
3741 	IF_LOCK(&ifp->if_snd);
3742 	ifp->if_drv_flags &= ~IFF_DRV_OACTIVE;
3743 	IF_UNLOCK(&ifp->if_snd);
3744 	sc->sc_wd_timer = 0;
3745 
3746 	if (sc->sc_softled)
3747 		ath_led_event(sc, sc->sc_txrix);
3748 
3749 	ATH_PCU_LOCK(sc);
3750 	sc->sc_txproc_cnt--;
3751 	ATH_PCU_UNLOCK(sc);
3752 
3753 	ath_tx_kick(sc);
3754 }
3755 #undef	TXQACTIVE
3756 
3757 /*
3758  * Deferred processing of TXQ rescheduling.
3759  */
3760 static void
3761 ath_txq_sched_tasklet(void *arg, int npending)
3762 {
3763 	struct ath_softc *sc = arg;
3764 	int i;
3765 
3766 	/* XXX is skipping ok? */
3767 	ATH_PCU_LOCK(sc);
3768 #if 0
3769 	if (sc->sc_inreset_cnt > 0) {
3770 		device_printf(sc->sc_dev,
3771 		    "%s: sc_inreset_cnt > 0; skipping\n", __func__);
3772 		ATH_PCU_UNLOCK(sc);
3773 		return;
3774 	}
3775 #endif
3776 	sc->sc_txproc_cnt++;
3777 	ATH_PCU_UNLOCK(sc);
3778 
3779 	for (i = 0; i < HAL_NUM_TX_QUEUES; i++) {
3780 		if (ATH_TXQ_SETUP(sc, i)) {
3781 			ATH_TXQ_LOCK(&sc->sc_txq[i]);
3782 			ath_txq_sched(sc, &sc->sc_txq[i]);
3783 			ATH_TXQ_UNLOCK(&sc->sc_txq[i]);
3784 		}
3785 	}
3786 
3787 	ATH_PCU_LOCK(sc);
3788 	sc->sc_txproc_cnt--;
3789 	ATH_PCU_UNLOCK(sc);
3790 }
3791 
3792 void
3793 ath_returnbuf_tail(struct ath_softc *sc, struct ath_buf *bf)
3794 {
3795 
3796 	ATH_TXBUF_LOCK_ASSERT(sc);
3797 
3798 	if (bf->bf_flags & ATH_BUF_MGMT)
3799 		TAILQ_INSERT_TAIL(&sc->sc_txbuf_mgmt, bf, bf_list);
3800 	else {
3801 		TAILQ_INSERT_TAIL(&sc->sc_txbuf, bf, bf_list);
3802 		sc->sc_txbuf_cnt++;
3803 		if (sc->sc_txbuf_cnt > ath_txbuf) {
3804 			device_printf(sc->sc_dev,
3805 			    "%s: sc_txbuf_cnt > %d?\n",
3806 			    __func__,
3807 			    ath_txbuf);
3808 			sc->sc_txbuf_cnt = ath_txbuf;
3809 		}
3810 	}
3811 }
3812 
3813 void
3814 ath_returnbuf_head(struct ath_softc *sc, struct ath_buf *bf)
3815 {
3816 
3817 	ATH_TXBUF_LOCK_ASSERT(sc);
3818 
3819 	if (bf->bf_flags & ATH_BUF_MGMT)
3820 		TAILQ_INSERT_HEAD(&sc->sc_txbuf_mgmt, bf, bf_list);
3821 	else {
3822 		TAILQ_INSERT_HEAD(&sc->sc_txbuf, bf, bf_list);
3823 		sc->sc_txbuf_cnt++;
3824 		if (sc->sc_txbuf_cnt > ATH_TXBUF) {
3825 			device_printf(sc->sc_dev,
3826 			    "%s: sc_txbuf_cnt > %d?\n",
3827 			    __func__,
3828 			    ATH_TXBUF);
3829 			sc->sc_txbuf_cnt = ATH_TXBUF;
3830 		}
3831 	}
3832 }
3833 
3834 /*
3835  * Return a buffer to the pool and update the 'busy' flag on the
3836  * previous 'tail' entry.
3837  *
3838  * This _must_ only be called when the buffer is involved in a completed
3839  * TX. The logic is that if it was part of an active TX, the previous
3840  * buffer on the list is now not involved in a halted TX DMA queue, waiting
3841  * for restart (eg for TDMA.)
3842  *
3843  * The caller must free the mbuf and recycle the node reference.
3844  */
3845 void
3846 ath_freebuf(struct ath_softc *sc, struct ath_buf *bf)
3847 {
3848 	bus_dmamap_unload(sc->sc_dmat, bf->bf_dmamap);
3849 	bus_dmamap_sync(sc->sc_dmat, bf->bf_dmamap, BUS_DMASYNC_POSTWRITE);
3850 
3851 	KASSERT((bf->bf_node == NULL), ("%s: bf->bf_node != NULL\n", __func__));
3852 	KASSERT((bf->bf_m == NULL), ("%s: bf->bf_m != NULL\n", __func__));
3853 
3854 	ATH_TXBUF_LOCK(sc);
3855 	ath_tx_update_busy(sc);
3856 	ath_returnbuf_tail(sc, bf);
3857 	ATH_TXBUF_UNLOCK(sc);
3858 }
3859 
3860 /*
3861  * This is currently used by ath_tx_draintxq() and
3862  * ath_tx_tid_free_pkts().
3863  *
3864  * It recycles a single ath_buf.
3865  */
3866 void
3867 ath_tx_freebuf(struct ath_softc *sc, struct ath_buf *bf, int status)
3868 {
3869 	struct ieee80211_node *ni = bf->bf_node;
3870 	struct mbuf *m0 = bf->bf_m;
3871 
3872 	bf->bf_node = NULL;
3873 	bf->bf_m = NULL;
3874 
3875 	/* Free the buffer, it's not needed any longer */
3876 	ath_freebuf(sc, bf);
3877 
3878 	if (ni != NULL) {
3879 		/*
3880 		 * Do any callback and reclaim the node reference.
3881 		 */
3882 		if (m0->m_flags & M_TXCB)
3883 			ieee80211_process_callback(ni, m0, status);
3884 		ieee80211_free_node(ni);
3885 	}
3886 	m_freem(m0);
3887 
3888 	/*
3889 	 * XXX the buffer used to be freed -after-, but the DMA map was
3890 	 * freed where ath_freebuf() now is. I've no idea what this
3891 	 * will do.
3892 	 */
3893 }
3894 
3895 void
3896 ath_tx_draintxq(struct ath_softc *sc, struct ath_txq *txq)
3897 {
3898 #ifdef ATH_DEBUG
3899 	struct ath_hal *ah = sc->sc_ah;
3900 #endif
3901 	struct ath_buf *bf;
3902 	u_int ix;
3903 
3904 	/*
3905 	 * NB: this assumes output has been stopped and
3906 	 *     we do not need to block ath_tx_proc
3907 	 */
3908 	ATH_TXBUF_LOCK(sc);
3909 	bf = TAILQ_LAST(&sc->sc_txbuf, ath_bufhead_s);
3910 	if (bf != NULL)
3911 		bf->bf_flags &= ~ATH_BUF_BUSY;
3912 	bf = TAILQ_LAST(&sc->sc_txbuf_mgmt, ath_bufhead_s);
3913 	if (bf != NULL)
3914 		bf->bf_flags &= ~ATH_BUF_BUSY;
3915 	ATH_TXBUF_UNLOCK(sc);
3916 
3917 	for (ix = 0;; ix++) {
3918 		ATH_TXQ_LOCK(txq);
3919 		bf = TAILQ_FIRST(&txq->axq_q);
3920 		if (bf == NULL) {
3921 			txq->axq_link = NULL;
3922 			ATH_TXQ_UNLOCK(txq);
3923 			break;
3924 		}
3925 		ATH_TXQ_REMOVE(txq, bf, bf_list);
3926 		if (bf->bf_state.bfs_aggr)
3927 			txq->axq_aggr_depth--;
3928 #ifdef ATH_DEBUG
3929 		if (sc->sc_debug & ATH_DEBUG_RESET) {
3930 			struct ieee80211com *ic = sc->sc_ifp->if_l2com;
3931 
3932 			ath_printtxbuf(sc, bf, txq->axq_qnum, ix,
3933 				ath_hal_txprocdesc(ah, bf->bf_lastds,
3934 				    &bf->bf_status.ds_txstat) == HAL_OK);
3935 			ieee80211_dump_pkt(ic, mtod(bf->bf_m, const uint8_t *),
3936 			    bf->bf_m->m_len, 0, -1);
3937 		}
3938 #endif /* ATH_DEBUG */
3939 		/*
3940 		 * Since we're now doing magic in the completion
3941 		 * functions, we -must- call it for aggregation
3942 		 * destinations or BAW tracking will get upset.
3943 		 */
3944 		/*
3945 		 * Clear ATH_BUF_BUSY; the completion handler
3946 		 * will free the buffer.
3947 		 */
3948 		ATH_TXQ_UNLOCK(txq);
3949 		bf->bf_flags &= ~ATH_BUF_BUSY;
3950 		if (bf->bf_comp)
3951 			bf->bf_comp(sc, bf, 1);
3952 		else
3953 			ath_tx_default_comp(sc, bf, 1);
3954 	}
3955 
3956 	/*
3957 	 * Drain software queued frames which are on
3958 	 * active TIDs.
3959 	 */
3960 	ath_tx_txq_drain(sc, txq);
3961 }
3962 
3963 static void
3964 ath_tx_stopdma(struct ath_softc *sc, struct ath_txq *txq)
3965 {
3966 	struct ath_hal *ah = sc->sc_ah;
3967 
3968 	DPRINTF(sc, ATH_DEBUG_RESET, "%s: tx queue [%u] %p, link %p\n",
3969 	    __func__, txq->axq_qnum,
3970 	    (caddr_t)(uintptr_t) ath_hal_gettxbuf(ah, txq->axq_qnum),
3971 	    txq->axq_link);
3972 	(void) ath_hal_stoptxdma(ah, txq->axq_qnum);
3973 }
3974 
3975 static int
3976 ath_stoptxdma(struct ath_softc *sc)
3977 {
3978 	struct ath_hal *ah = sc->sc_ah;
3979 	int i;
3980 
3981 	/* XXX return value */
3982 	if (sc->sc_invalid)
3983 		return 0;
3984 
3985 	if (!sc->sc_invalid) {
3986 		/* don't touch the hardware if marked invalid */
3987 		DPRINTF(sc, ATH_DEBUG_RESET, "%s: tx queue [%u] %p, link %p\n",
3988 		    __func__, sc->sc_bhalq,
3989 		    (caddr_t)(uintptr_t) ath_hal_gettxbuf(ah, sc->sc_bhalq),
3990 		    NULL);
3991 		(void) ath_hal_stoptxdma(ah, sc->sc_bhalq);
3992 		for (i = 0; i < HAL_NUM_TX_QUEUES; i++)
3993 			if (ATH_TXQ_SETUP(sc, i))
3994 				ath_tx_stopdma(sc, &sc->sc_txq[i]);
3995 	}
3996 
3997 	return 1;
3998 }
3999 
4000 /*
4001  * Drain the transmit queues and reclaim resources.
4002  */
4003 static void
4004 ath_draintxq(struct ath_softc *sc, ATH_RESET_TYPE reset_type)
4005 {
4006 #ifdef	ATH_DEBUG
4007 	struct ath_hal *ah = sc->sc_ah;
4008 #endif
4009 	struct ifnet *ifp = sc->sc_ifp;
4010 	int i;
4011 
4012 	(void) ath_stoptxdma(sc);
4013 
4014 	for (i = 0; i < HAL_NUM_TX_QUEUES; i++) {
4015 		/*
4016 		 * XXX TODO: should we just handle the completed TX frames
4017 		 * here, whether or not the reset is a full one or not?
4018 		 */
4019 		if (ATH_TXQ_SETUP(sc, i)) {
4020 			if (reset_type == ATH_RESET_NOLOSS)
4021 				ath_tx_processq(sc, &sc->sc_txq[i], 0);
4022 			else
4023 				ath_tx_draintxq(sc, &sc->sc_txq[i]);
4024 		}
4025 	}
4026 #ifdef ATH_DEBUG
4027 	if (sc->sc_debug & ATH_DEBUG_RESET) {
4028 		struct ath_buf *bf = TAILQ_FIRST(&sc->sc_bbuf);
4029 		if (bf != NULL && bf->bf_m != NULL) {
4030 			ath_printtxbuf(sc, bf, sc->sc_bhalq, 0,
4031 				ath_hal_txprocdesc(ah, bf->bf_lastds,
4032 				    &bf->bf_status.ds_txstat) == HAL_OK);
4033 			ieee80211_dump_pkt(ifp->if_l2com,
4034 			    mtod(bf->bf_m, const uint8_t *), bf->bf_m->m_len,
4035 			    0, -1);
4036 		}
4037 	}
4038 #endif /* ATH_DEBUG */
4039 	IF_LOCK(&ifp->if_snd);
4040 	ifp->if_drv_flags &= ~IFF_DRV_OACTIVE;
4041 	IF_UNLOCK(&ifp->if_snd);
4042 	sc->sc_wd_timer = 0;
4043 }
4044 
4045 /*
4046  * Update internal state after a channel change.
4047  */
4048 static void
4049 ath_chan_change(struct ath_softc *sc, struct ieee80211_channel *chan)
4050 {
4051 	enum ieee80211_phymode mode;
4052 
4053 	/*
4054 	 * Change channels and update the h/w rate map
4055 	 * if we're switching; e.g. 11a to 11b/g.
4056 	 */
4057 	mode = ieee80211_chan2mode(chan);
4058 	if (mode != sc->sc_curmode)
4059 		ath_setcurmode(sc, mode);
4060 	sc->sc_curchan = chan;
4061 }
4062 
4063 /*
4064  * Set/change channels.  If the channel is really being changed,
4065  * it's done by resetting the chip.  To accomplish this we must
4066  * first cleanup any pending DMA, then restart stuff after a la
4067  * ath_init.
4068  */
4069 static int
4070 ath_chan_set(struct ath_softc *sc, struct ieee80211_channel *chan)
4071 {
4072 	struct ifnet *ifp = sc->sc_ifp;
4073 	struct ieee80211com *ic = ifp->if_l2com;
4074 	struct ath_hal *ah = sc->sc_ah;
4075 	int ret = 0;
4076 
4077 	/* Treat this as an interface reset */
4078 	ATH_PCU_UNLOCK_ASSERT(sc);
4079 	ATH_UNLOCK_ASSERT(sc);
4080 
4081 	/* (Try to) stop TX/RX from occuring */
4082 	taskqueue_block(sc->sc_tq);
4083 
4084 	ATH_PCU_LOCK(sc);
4085 	ath_hal_intrset(ah, 0);		/* Stop new RX/TX completion */
4086 	ath_txrx_stop_locked(sc);	/* Stop pending RX/TX completion */
4087 	if (ath_reset_grablock(sc, 1) == 0) {
4088 		device_printf(sc->sc_dev, "%s: concurrent reset! Danger!\n",
4089 		    __func__);
4090 	}
4091 	ATH_PCU_UNLOCK(sc);
4092 
4093 	DPRINTF(sc, ATH_DEBUG_RESET, "%s: %u (%u MHz, flags 0x%x)\n",
4094 	    __func__, ieee80211_chan2ieee(ic, chan),
4095 	    chan->ic_freq, chan->ic_flags);
4096 	if (chan != sc->sc_curchan) {
4097 		HAL_STATUS status;
4098 		/*
4099 		 * To switch channels clear any pending DMA operations;
4100 		 * wait long enough for the RX fifo to drain, reset the
4101 		 * hardware at the new frequency, and then re-enable
4102 		 * the relevant bits of the h/w.
4103 		 */
4104 #if 0
4105 		ath_hal_intrset(ah, 0);		/* disable interrupts */
4106 #endif
4107 		ath_stoprecv(sc, 1);		/* turn off frame recv */
4108 		/*
4109 		 * First, handle completed TX/RX frames.
4110 		 */
4111 		ath_rx_flush(sc);
4112 		ath_draintxq(sc, ATH_RESET_NOLOSS);
4113 		/*
4114 		 * Next, flush the non-scheduled frames.
4115 		 */
4116 		ath_draintxq(sc, ATH_RESET_FULL);	/* clear pending tx frames */
4117 
4118 		if (!ath_hal_reset(ah, sc->sc_opmode, chan, AH_TRUE, &status)) {
4119 			if_printf(ifp, "%s: unable to reset "
4120 			    "channel %u (%u MHz, flags 0x%x), hal status %u\n",
4121 			    __func__, ieee80211_chan2ieee(ic, chan),
4122 			    chan->ic_freq, chan->ic_flags, status);
4123 			ret = EIO;
4124 			goto finish;
4125 		}
4126 		sc->sc_diversity = ath_hal_getdiversity(ah);
4127 
4128 		/* Let DFS at it in case it's a DFS channel */
4129 		ath_dfs_radar_enable(sc, chan);
4130 
4131 		/*
4132 		 * Re-enable rx framework.
4133 		 */
4134 		if (ath_startrecv(sc) != 0) {
4135 			if_printf(ifp, "%s: unable to restart recv logic\n",
4136 			    __func__);
4137 			ret = EIO;
4138 			goto finish;
4139 		}
4140 
4141 		/*
4142 		 * Change channels and update the h/w rate map
4143 		 * if we're switching; e.g. 11a to 11b/g.
4144 		 */
4145 		ath_chan_change(sc, chan);
4146 
4147 		/*
4148 		 * Reset clears the beacon timers; reset them
4149 		 * here if needed.
4150 		 */
4151 		if (sc->sc_beacons) {		/* restart beacons */
4152 #ifdef IEEE80211_SUPPORT_TDMA
4153 			if (sc->sc_tdma)
4154 				ath_tdma_config(sc, NULL);
4155 			else
4156 #endif
4157 			ath_beacon_config(sc, NULL);
4158 		}
4159 
4160 		/*
4161 		 * Re-enable interrupts.
4162 		 */
4163 #if 0
4164 		ath_hal_intrset(ah, sc->sc_imask);
4165 #endif
4166 	}
4167 
4168 finish:
4169 	ATH_PCU_LOCK(sc);
4170 	sc->sc_inreset_cnt--;
4171 	/* XXX only do this if sc_inreset_cnt == 0? */
4172 	ath_hal_intrset(ah, sc->sc_imask);
4173 	ATH_PCU_UNLOCK(sc);
4174 
4175 	IF_LOCK(&ifp->if_snd);
4176 	ifp->if_drv_flags &= ~IFF_DRV_OACTIVE;
4177 	IF_UNLOCK(&ifp->if_snd);
4178 	ath_txrx_start(sc);
4179 	/* XXX ath_start? */
4180 
4181 	return ret;
4182 }
4183 
4184 /*
4185  * Periodically recalibrate the PHY to account
4186  * for temperature/environment changes.
4187  */
4188 static void
4189 ath_calibrate(void *arg)
4190 {
4191 	struct ath_softc *sc = arg;
4192 	struct ath_hal *ah = sc->sc_ah;
4193 	struct ifnet *ifp = sc->sc_ifp;
4194 	struct ieee80211com *ic = ifp->if_l2com;
4195 	HAL_BOOL longCal, isCalDone;
4196 	HAL_BOOL aniCal, shortCal = AH_FALSE;
4197 	int nextcal;
4198 
4199 	if (ic->ic_flags & IEEE80211_F_SCAN)	/* defer, off channel */
4200 		goto restart;
4201 	longCal = (ticks - sc->sc_lastlongcal >= ath_longcalinterval*hz);
4202 	aniCal = (ticks - sc->sc_lastani >= ath_anicalinterval*hz/1000);
4203 	if (sc->sc_doresetcal)
4204 		shortCal = (ticks - sc->sc_lastshortcal >= ath_shortcalinterval*hz/1000);
4205 
4206 	DPRINTF(sc, ATH_DEBUG_CALIBRATE, "%s: shortCal=%d; longCal=%d; aniCal=%d\n", __func__, shortCal, longCal, aniCal);
4207 	if (aniCal) {
4208 		sc->sc_stats.ast_ani_cal++;
4209 		sc->sc_lastani = ticks;
4210 		ath_hal_ani_poll(ah, sc->sc_curchan);
4211 	}
4212 
4213 	if (longCal) {
4214 		sc->sc_stats.ast_per_cal++;
4215 		sc->sc_lastlongcal = ticks;
4216 		if (ath_hal_getrfgain(ah) == HAL_RFGAIN_NEED_CHANGE) {
4217 			/*
4218 			 * Rfgain is out of bounds, reset the chip
4219 			 * to load new gain values.
4220 			 */
4221 			DPRINTF(sc, ATH_DEBUG_CALIBRATE,
4222 				"%s: rfgain change\n", __func__);
4223 			sc->sc_stats.ast_per_rfgain++;
4224 			sc->sc_resetcal = 0;
4225 			sc->sc_doresetcal = AH_TRUE;
4226 			taskqueue_enqueue(sc->sc_tq, &sc->sc_resettask);
4227 			callout_reset(&sc->sc_cal_ch, 1, ath_calibrate, sc);
4228 			return;
4229 		}
4230 		/*
4231 		 * If this long cal is after an idle period, then
4232 		 * reset the data collection state so we start fresh.
4233 		 */
4234 		if (sc->sc_resetcal) {
4235 			(void) ath_hal_calreset(ah, sc->sc_curchan);
4236 			sc->sc_lastcalreset = ticks;
4237 			sc->sc_lastshortcal = ticks;
4238 			sc->sc_resetcal = 0;
4239 			sc->sc_doresetcal = AH_TRUE;
4240 		}
4241 	}
4242 
4243 	/* Only call if we're doing a short/long cal, not for ANI calibration */
4244 	if (shortCal || longCal) {
4245 		if (ath_hal_calibrateN(ah, sc->sc_curchan, longCal, &isCalDone)) {
4246 			if (longCal) {
4247 				/*
4248 				 * Calibrate noise floor data again in case of change.
4249 				 */
4250 				ath_hal_process_noisefloor(ah);
4251 			}
4252 		} else {
4253 			DPRINTF(sc, ATH_DEBUG_ANY,
4254 				"%s: calibration of channel %u failed\n",
4255 				__func__, sc->sc_curchan->ic_freq);
4256 			sc->sc_stats.ast_per_calfail++;
4257 		}
4258 		if (shortCal)
4259 			sc->sc_lastshortcal = ticks;
4260 	}
4261 	if (!isCalDone) {
4262 restart:
4263 		/*
4264 		 * Use a shorter interval to potentially collect multiple
4265 		 * data samples required to complete calibration.  Once
4266 		 * we're told the work is done we drop back to a longer
4267 		 * interval between requests.  We're more aggressive doing
4268 		 * work when operating as an AP to improve operation right
4269 		 * after startup.
4270 		 */
4271 		sc->sc_lastshortcal = ticks;
4272 		nextcal = ath_shortcalinterval*hz/1000;
4273 		if (sc->sc_opmode != HAL_M_HOSTAP)
4274 			nextcal *= 10;
4275 		sc->sc_doresetcal = AH_TRUE;
4276 	} else {
4277 		/* nextcal should be the shortest time for next event */
4278 		nextcal = ath_longcalinterval*hz;
4279 		if (sc->sc_lastcalreset == 0)
4280 			sc->sc_lastcalreset = sc->sc_lastlongcal;
4281 		else if (ticks - sc->sc_lastcalreset >= ath_resetcalinterval*hz)
4282 			sc->sc_resetcal = 1;	/* setup reset next trip */
4283 		sc->sc_doresetcal = AH_FALSE;
4284 	}
4285 	/* ANI calibration may occur more often than short/long/resetcal */
4286 	if (ath_anicalinterval > 0)
4287 		nextcal = MIN(nextcal, ath_anicalinterval*hz/1000);
4288 
4289 	if (nextcal != 0) {
4290 		DPRINTF(sc, ATH_DEBUG_CALIBRATE, "%s: next +%u (%sisCalDone)\n",
4291 		    __func__, nextcal, isCalDone ? "" : "!");
4292 		callout_reset(&sc->sc_cal_ch, nextcal, ath_calibrate, sc);
4293 	} else {
4294 		DPRINTF(sc, ATH_DEBUG_CALIBRATE, "%s: calibration disabled\n",
4295 		    __func__);
4296 		/* NB: don't rearm timer */
4297 	}
4298 }
4299 
4300 static void
4301 ath_scan_start(struct ieee80211com *ic)
4302 {
4303 	struct ifnet *ifp = ic->ic_ifp;
4304 	struct ath_softc *sc = ifp->if_softc;
4305 	struct ath_hal *ah = sc->sc_ah;
4306 	u_int32_t rfilt;
4307 
4308 	/* XXX calibration timer? */
4309 
4310 	ATH_LOCK(sc);
4311 	sc->sc_scanning = 1;
4312 	sc->sc_syncbeacon = 0;
4313 	rfilt = ath_calcrxfilter(sc);
4314 	ATH_UNLOCK(sc);
4315 
4316 	ATH_PCU_LOCK(sc);
4317 	ath_hal_setrxfilter(ah, rfilt);
4318 	ath_hal_setassocid(ah, ifp->if_broadcastaddr, 0);
4319 	ATH_PCU_UNLOCK(sc);
4320 
4321 	DPRINTF(sc, ATH_DEBUG_STATE, "%s: RX filter 0x%x bssid %s aid 0\n",
4322 		 __func__, rfilt, ether_sprintf(ifp->if_broadcastaddr));
4323 }
4324 
4325 static void
4326 ath_scan_end(struct ieee80211com *ic)
4327 {
4328 	struct ifnet *ifp = ic->ic_ifp;
4329 	struct ath_softc *sc = ifp->if_softc;
4330 	struct ath_hal *ah = sc->sc_ah;
4331 	u_int32_t rfilt;
4332 
4333 	ATH_LOCK(sc);
4334 	sc->sc_scanning = 0;
4335 	rfilt = ath_calcrxfilter(sc);
4336 	ATH_UNLOCK(sc);
4337 
4338 	ATH_PCU_LOCK(sc);
4339 	ath_hal_setrxfilter(ah, rfilt);
4340 	ath_hal_setassocid(ah, sc->sc_curbssid, sc->sc_curaid);
4341 
4342 	ath_hal_process_noisefloor(ah);
4343 	ATH_PCU_UNLOCK(sc);
4344 
4345 	DPRINTF(sc, ATH_DEBUG_STATE, "%s: RX filter 0x%x bssid %s aid 0x%x\n",
4346 		 __func__, rfilt, ether_sprintf(sc->sc_curbssid),
4347 		 sc->sc_curaid);
4348 }
4349 
4350 #ifdef	ATH_ENABLE_11N
4351 /*
4352  * For now, just do a channel change.
4353  *
4354  * Later, we'll go through the hard slog of suspending tx/rx, changing rate
4355  * control state and resetting the hardware without dropping frames out
4356  * of the queue.
4357  *
4358  * The unfortunate trouble here is making absolutely sure that the
4359  * channel width change has propagated enough so the hardware
4360  * absolutely isn't handed bogus frames for it's current operating
4361  * mode. (Eg, 40MHz frames in 20MHz mode.) Since TX and RX can and
4362  * does occur in parallel, we need to make certain we've blocked
4363  * any further ongoing TX (and RX, that can cause raw TX)
4364  * before we do this.
4365  */
4366 static void
4367 ath_update_chw(struct ieee80211com *ic)
4368 {
4369 	struct ifnet *ifp = ic->ic_ifp;
4370 	struct ath_softc *sc = ifp->if_softc;
4371 
4372 	DPRINTF(sc, ATH_DEBUG_STATE, "%s: called\n", __func__);
4373 	ath_set_channel(ic);
4374 }
4375 #endif	/* ATH_ENABLE_11N */
4376 
4377 static void
4378 ath_set_channel(struct ieee80211com *ic)
4379 {
4380 	struct ifnet *ifp = ic->ic_ifp;
4381 	struct ath_softc *sc = ifp->if_softc;
4382 
4383 	(void) ath_chan_set(sc, ic->ic_curchan);
4384 	/*
4385 	 * If we are returning to our bss channel then mark state
4386 	 * so the next recv'd beacon's tsf will be used to sync the
4387 	 * beacon timers.  Note that since we only hear beacons in
4388 	 * sta/ibss mode this has no effect in other operating modes.
4389 	 */
4390 	ATH_LOCK(sc);
4391 	if (!sc->sc_scanning && ic->ic_curchan == ic->ic_bsschan)
4392 		sc->sc_syncbeacon = 1;
4393 	ATH_UNLOCK(sc);
4394 }
4395 
4396 /*
4397  * Walk the vap list and check if there any vap's in RUN state.
4398  */
4399 static int
4400 ath_isanyrunningvaps(struct ieee80211vap *this)
4401 {
4402 	struct ieee80211com *ic = this->iv_ic;
4403 	struct ieee80211vap *vap;
4404 
4405 	IEEE80211_LOCK_ASSERT(ic);
4406 
4407 	TAILQ_FOREACH(vap, &ic->ic_vaps, iv_next) {
4408 		if (vap != this && vap->iv_state >= IEEE80211_S_RUN)
4409 			return 1;
4410 	}
4411 	return 0;
4412 }
4413 
4414 static int
4415 ath_newstate(struct ieee80211vap *vap, enum ieee80211_state nstate, int arg)
4416 {
4417 	struct ieee80211com *ic = vap->iv_ic;
4418 	struct ath_softc *sc = ic->ic_ifp->if_softc;
4419 	struct ath_vap *avp = ATH_VAP(vap);
4420 	struct ath_hal *ah = sc->sc_ah;
4421 	struct ieee80211_node *ni = NULL;
4422 	int i, error, stamode;
4423 	u_int32_t rfilt;
4424 	int csa_run_transition = 0;
4425 	static const HAL_LED_STATE leds[] = {
4426 	    HAL_LED_INIT,	/* IEEE80211_S_INIT */
4427 	    HAL_LED_SCAN,	/* IEEE80211_S_SCAN */
4428 	    HAL_LED_AUTH,	/* IEEE80211_S_AUTH */
4429 	    HAL_LED_ASSOC, 	/* IEEE80211_S_ASSOC */
4430 	    HAL_LED_RUN, 	/* IEEE80211_S_CAC */
4431 	    HAL_LED_RUN, 	/* IEEE80211_S_RUN */
4432 	    HAL_LED_RUN, 	/* IEEE80211_S_CSA */
4433 	    HAL_LED_RUN, 	/* IEEE80211_S_SLEEP */
4434 	};
4435 
4436 	DPRINTF(sc, ATH_DEBUG_STATE, "%s: %s -> %s\n", __func__,
4437 		ieee80211_state_name[vap->iv_state],
4438 		ieee80211_state_name[nstate]);
4439 
4440 	/*
4441 	 * net80211 _should_ have the comlock asserted at this point.
4442 	 * There are some comments around the calls to vap->iv_newstate
4443 	 * which indicate that it (newstate) may end up dropping the
4444 	 * lock.  This and the subsequent lock assert check after newstate
4445 	 * are an attempt to catch these and figure out how/why.
4446 	 */
4447 	IEEE80211_LOCK_ASSERT(ic);
4448 
4449 	if (vap->iv_state == IEEE80211_S_CSA && nstate == IEEE80211_S_RUN)
4450 		csa_run_transition = 1;
4451 
4452 	callout_drain(&sc->sc_cal_ch);
4453 	ath_hal_setledstate(ah, leds[nstate]);	/* set LED */
4454 
4455 	if (nstate == IEEE80211_S_SCAN) {
4456 		/*
4457 		 * Scanning: turn off beacon miss and don't beacon.
4458 		 * Mark beacon state so when we reach RUN state we'll
4459 		 * [re]setup beacons.  Unblock the task q thread so
4460 		 * deferred interrupt processing is done.
4461 		 */
4462 		ath_hal_intrset(ah,
4463 		    sc->sc_imask &~ (HAL_INT_SWBA | HAL_INT_BMISS));
4464 		sc->sc_imask &= ~(HAL_INT_SWBA | HAL_INT_BMISS);
4465 		sc->sc_beacons = 0;
4466 		taskqueue_unblock(sc->sc_tq);
4467 	}
4468 
4469 	ni = ieee80211_ref_node(vap->iv_bss);
4470 	rfilt = ath_calcrxfilter(sc);
4471 	stamode = (vap->iv_opmode == IEEE80211_M_STA ||
4472 		   vap->iv_opmode == IEEE80211_M_AHDEMO ||
4473 		   vap->iv_opmode == IEEE80211_M_IBSS);
4474 	if (stamode && nstate == IEEE80211_S_RUN) {
4475 		sc->sc_curaid = ni->ni_associd;
4476 		IEEE80211_ADDR_COPY(sc->sc_curbssid, ni->ni_bssid);
4477 		ath_hal_setassocid(ah, sc->sc_curbssid, sc->sc_curaid);
4478 	}
4479 	DPRINTF(sc, ATH_DEBUG_STATE, "%s: RX filter 0x%x bssid %s aid 0x%x\n",
4480 	   __func__, rfilt, ether_sprintf(sc->sc_curbssid), sc->sc_curaid);
4481 	ath_hal_setrxfilter(ah, rfilt);
4482 
4483 	/* XXX is this to restore keycache on resume? */
4484 	if (vap->iv_opmode != IEEE80211_M_STA &&
4485 	    (vap->iv_flags & IEEE80211_F_PRIVACY)) {
4486 		for (i = 0; i < IEEE80211_WEP_NKID; i++)
4487 			if (ath_hal_keyisvalid(ah, i))
4488 				ath_hal_keysetmac(ah, i, ni->ni_bssid);
4489 	}
4490 
4491 	/*
4492 	 * Invoke the parent method to do net80211 work.
4493 	 */
4494 	error = avp->av_newstate(vap, nstate, arg);
4495 	if (error != 0)
4496 		goto bad;
4497 
4498 	/*
4499 	 * See above: ensure av_newstate() doesn't drop the lock
4500 	 * on us.
4501 	 */
4502 	IEEE80211_LOCK_ASSERT(ic);
4503 
4504 	if (nstate == IEEE80211_S_RUN) {
4505 		/* NB: collect bss node again, it may have changed */
4506 		ieee80211_free_node(ni);
4507 		ni = ieee80211_ref_node(vap->iv_bss);
4508 
4509 		DPRINTF(sc, ATH_DEBUG_STATE,
4510 		    "%s(RUN): iv_flags 0x%08x bintvl %d bssid %s "
4511 		    "capinfo 0x%04x chan %d\n", __func__,
4512 		    vap->iv_flags, ni->ni_intval, ether_sprintf(ni->ni_bssid),
4513 		    ni->ni_capinfo, ieee80211_chan2ieee(ic, ic->ic_curchan));
4514 
4515 		switch (vap->iv_opmode) {
4516 #ifdef IEEE80211_SUPPORT_TDMA
4517 		case IEEE80211_M_AHDEMO:
4518 			if ((vap->iv_caps & IEEE80211_C_TDMA) == 0)
4519 				break;
4520 			/* fall thru... */
4521 #endif
4522 		case IEEE80211_M_HOSTAP:
4523 		case IEEE80211_M_IBSS:
4524 		case IEEE80211_M_MBSS:
4525 			/*
4526 			 * Allocate and setup the beacon frame.
4527 			 *
4528 			 * Stop any previous beacon DMA.  This may be
4529 			 * necessary, for example, when an ibss merge
4530 			 * causes reconfiguration; there will be a state
4531 			 * transition from RUN->RUN that means we may
4532 			 * be called with beacon transmission active.
4533 			 */
4534 			ath_hal_stoptxdma(ah, sc->sc_bhalq);
4535 
4536 			error = ath_beacon_alloc(sc, ni);
4537 			if (error != 0)
4538 				goto bad;
4539 			/*
4540 			 * If joining an adhoc network defer beacon timer
4541 			 * configuration to the next beacon frame so we
4542 			 * have a current TSF to use.  Otherwise we're
4543 			 * starting an ibss/bss so there's no need to delay;
4544 			 * if this is the first vap moving to RUN state, then
4545 			 * beacon state needs to be [re]configured.
4546 			 */
4547 			if (vap->iv_opmode == IEEE80211_M_IBSS &&
4548 			    ni->ni_tstamp.tsf != 0) {
4549 				sc->sc_syncbeacon = 1;
4550 			} else if (!sc->sc_beacons) {
4551 #ifdef IEEE80211_SUPPORT_TDMA
4552 				if (vap->iv_caps & IEEE80211_C_TDMA)
4553 					ath_tdma_config(sc, vap);
4554 				else
4555 #endif
4556 					ath_beacon_config(sc, vap);
4557 				sc->sc_beacons = 1;
4558 			}
4559 			break;
4560 		case IEEE80211_M_STA:
4561 			/*
4562 			 * Defer beacon timer configuration to the next
4563 			 * beacon frame so we have a current TSF to use
4564 			 * (any TSF collected when scanning is likely old).
4565 			 * However if it's due to a CSA -> RUN transition,
4566 			 * force a beacon update so we pick up a lack of
4567 			 * beacons from an AP in CAC and thus force a
4568 			 * scan.
4569 			 */
4570 			sc->sc_syncbeacon = 1;
4571 			if (csa_run_transition)
4572 				ath_beacon_config(sc, vap);
4573 			break;
4574 		case IEEE80211_M_MONITOR:
4575 			/*
4576 			 * Monitor mode vaps have only INIT->RUN and RUN->RUN
4577 			 * transitions so we must re-enable interrupts here to
4578 			 * handle the case of a single monitor mode vap.
4579 			 */
4580 			ath_hal_intrset(ah, sc->sc_imask);
4581 			break;
4582 		case IEEE80211_M_WDS:
4583 			break;
4584 		default:
4585 			break;
4586 		}
4587 		/*
4588 		 * Let the hal process statistics collected during a
4589 		 * scan so it can provide calibrated noise floor data.
4590 		 */
4591 		ath_hal_process_noisefloor(ah);
4592 		/*
4593 		 * Reset rssi stats; maybe not the best place...
4594 		 */
4595 		sc->sc_halstats.ns_avgbrssi = ATH_RSSI_DUMMY_MARKER;
4596 		sc->sc_halstats.ns_avgrssi = ATH_RSSI_DUMMY_MARKER;
4597 		sc->sc_halstats.ns_avgtxrssi = ATH_RSSI_DUMMY_MARKER;
4598 		/*
4599 		 * Finally, start any timers and the task q thread
4600 		 * (in case we didn't go through SCAN state).
4601 		 */
4602 		if (ath_longcalinterval != 0) {
4603 			/* start periodic recalibration timer */
4604 			callout_reset(&sc->sc_cal_ch, 1, ath_calibrate, sc);
4605 		} else {
4606 			DPRINTF(sc, ATH_DEBUG_CALIBRATE,
4607 			    "%s: calibration disabled\n", __func__);
4608 		}
4609 		taskqueue_unblock(sc->sc_tq);
4610 	} else if (nstate == IEEE80211_S_INIT) {
4611 		/*
4612 		 * If there are no vaps left in RUN state then
4613 		 * shutdown host/driver operation:
4614 		 * o disable interrupts
4615 		 * o disable the task queue thread
4616 		 * o mark beacon processing as stopped
4617 		 */
4618 		if (!ath_isanyrunningvaps(vap)) {
4619 			sc->sc_imask &= ~(HAL_INT_SWBA | HAL_INT_BMISS);
4620 			/* disable interrupts  */
4621 			ath_hal_intrset(ah, sc->sc_imask &~ HAL_INT_GLOBAL);
4622 			taskqueue_block(sc->sc_tq);
4623 			sc->sc_beacons = 0;
4624 		}
4625 #ifdef IEEE80211_SUPPORT_TDMA
4626 		ath_hal_setcca(ah, AH_TRUE);
4627 #endif
4628 	}
4629 bad:
4630 	ieee80211_free_node(ni);
4631 	return error;
4632 }
4633 
4634 /*
4635  * Allocate a key cache slot to the station so we can
4636  * setup a mapping from key index to node. The key cache
4637  * slot is needed for managing antenna state and for
4638  * compression when stations do not use crypto.  We do
4639  * it uniliaterally here; if crypto is employed this slot
4640  * will be reassigned.
4641  */
4642 static void
4643 ath_setup_stationkey(struct ieee80211_node *ni)
4644 {
4645 	struct ieee80211vap *vap = ni->ni_vap;
4646 	struct ath_softc *sc = vap->iv_ic->ic_ifp->if_softc;
4647 	ieee80211_keyix keyix, rxkeyix;
4648 
4649 	/* XXX should take a locked ref to vap->iv_bss */
4650 	if (!ath_key_alloc(vap, &ni->ni_ucastkey, &keyix, &rxkeyix)) {
4651 		/*
4652 		 * Key cache is full; we'll fall back to doing
4653 		 * the more expensive lookup in software.  Note
4654 		 * this also means no h/w compression.
4655 		 */
4656 		/* XXX msg+statistic */
4657 	} else {
4658 		/* XXX locking? */
4659 		ni->ni_ucastkey.wk_keyix = keyix;
4660 		ni->ni_ucastkey.wk_rxkeyix = rxkeyix;
4661 		/* NB: must mark device key to get called back on delete */
4662 		ni->ni_ucastkey.wk_flags |= IEEE80211_KEY_DEVKEY;
4663 		IEEE80211_ADDR_COPY(ni->ni_ucastkey.wk_macaddr, ni->ni_macaddr);
4664 		/* NB: this will create a pass-thru key entry */
4665 		ath_keyset(sc, vap, &ni->ni_ucastkey, vap->iv_bss);
4666 	}
4667 }
4668 
4669 /*
4670  * Setup driver-specific state for a newly associated node.
4671  * Note that we're called also on a re-associate, the isnew
4672  * param tells us if this is the first time or not.
4673  */
4674 static void
4675 ath_newassoc(struct ieee80211_node *ni, int isnew)
4676 {
4677 	struct ath_node *an = ATH_NODE(ni);
4678 	struct ieee80211vap *vap = ni->ni_vap;
4679 	struct ath_softc *sc = vap->iv_ic->ic_ifp->if_softc;
4680 	const struct ieee80211_txparam *tp = ni->ni_txparms;
4681 
4682 	an->an_mcastrix = ath_tx_findrix(sc, tp->mcastrate);
4683 	an->an_mgmtrix = ath_tx_findrix(sc, tp->mgmtrate);
4684 
4685 	ath_rate_newassoc(sc, an, isnew);
4686 	if (isnew &&
4687 	    (vap->iv_flags & IEEE80211_F_PRIVACY) == 0 && sc->sc_hasclrkey &&
4688 	    ni->ni_ucastkey.wk_keyix == IEEE80211_KEYIX_NONE)
4689 		ath_setup_stationkey(ni);
4690 }
4691 
4692 static int
4693 ath_setregdomain(struct ieee80211com *ic, struct ieee80211_regdomain *reg,
4694 	int nchans, struct ieee80211_channel chans[])
4695 {
4696 	struct ath_softc *sc = ic->ic_ifp->if_softc;
4697 	struct ath_hal *ah = sc->sc_ah;
4698 	HAL_STATUS status;
4699 
4700 	DPRINTF(sc, ATH_DEBUG_REGDOMAIN,
4701 	    "%s: rd %u cc %u location %c%s\n",
4702 	    __func__, reg->regdomain, reg->country, reg->location,
4703 	    reg->ecm ? " ecm" : "");
4704 
4705 	status = ath_hal_set_channels(ah, chans, nchans,
4706 	    reg->country, reg->regdomain);
4707 	if (status != HAL_OK) {
4708 		DPRINTF(sc, ATH_DEBUG_REGDOMAIN, "%s: failed, status %u\n",
4709 		    __func__, status);
4710 		return EINVAL;		/* XXX */
4711 	}
4712 
4713 	return 0;
4714 }
4715 
4716 static void
4717 ath_getradiocaps(struct ieee80211com *ic,
4718 	int maxchans, int *nchans, struct ieee80211_channel chans[])
4719 {
4720 	struct ath_softc *sc = ic->ic_ifp->if_softc;
4721 	struct ath_hal *ah = sc->sc_ah;
4722 
4723 	DPRINTF(sc, ATH_DEBUG_REGDOMAIN, "%s: use rd %u cc %d\n",
4724 	    __func__, SKU_DEBUG, CTRY_DEFAULT);
4725 
4726 	/* XXX check return */
4727 	(void) ath_hal_getchannels(ah, chans, maxchans, nchans,
4728 	    HAL_MODE_ALL, CTRY_DEFAULT, SKU_DEBUG, AH_TRUE);
4729 
4730 }
4731 
4732 static int
4733 ath_getchannels(struct ath_softc *sc)
4734 {
4735 	struct ifnet *ifp = sc->sc_ifp;
4736 	struct ieee80211com *ic = ifp->if_l2com;
4737 	struct ath_hal *ah = sc->sc_ah;
4738 	HAL_STATUS status;
4739 
4740 	/*
4741 	 * Collect channel set based on EEPROM contents.
4742 	 */
4743 	status = ath_hal_init_channels(ah, ic->ic_channels, IEEE80211_CHAN_MAX,
4744 	    &ic->ic_nchans, HAL_MODE_ALL, CTRY_DEFAULT, SKU_NONE, AH_TRUE);
4745 	if (status != HAL_OK) {
4746 		if_printf(ifp, "%s: unable to collect channel list from hal, "
4747 		    "status %d\n", __func__, status);
4748 		return EINVAL;
4749 	}
4750 	(void) ath_hal_getregdomain(ah, &sc->sc_eerd);
4751 	ath_hal_getcountrycode(ah, &sc->sc_eecc);	/* NB: cannot fail */
4752 	/* XXX map Atheros sku's to net80211 SKU's */
4753 	/* XXX net80211 types too small */
4754 	ic->ic_regdomain.regdomain = (uint16_t) sc->sc_eerd;
4755 	ic->ic_regdomain.country = (uint16_t) sc->sc_eecc;
4756 	ic->ic_regdomain.isocc[0] = ' ';	/* XXX don't know */
4757 	ic->ic_regdomain.isocc[1] = ' ';
4758 
4759 	ic->ic_regdomain.ecm = 1;
4760 	ic->ic_regdomain.location = 'I';
4761 
4762 	DPRINTF(sc, ATH_DEBUG_REGDOMAIN,
4763 	    "%s: eeprom rd %u cc %u (mapped rd %u cc %u) location %c%s\n",
4764 	    __func__, sc->sc_eerd, sc->sc_eecc,
4765 	    ic->ic_regdomain.regdomain, ic->ic_regdomain.country,
4766 	    ic->ic_regdomain.location, ic->ic_regdomain.ecm ? " ecm" : "");
4767 	return 0;
4768 }
4769 
4770 static int
4771 ath_rate_setup(struct ath_softc *sc, u_int mode)
4772 {
4773 	struct ath_hal *ah = sc->sc_ah;
4774 	const HAL_RATE_TABLE *rt;
4775 
4776 	switch (mode) {
4777 	case IEEE80211_MODE_11A:
4778 		rt = ath_hal_getratetable(ah, HAL_MODE_11A);
4779 		break;
4780 	case IEEE80211_MODE_HALF:
4781 		rt = ath_hal_getratetable(ah, HAL_MODE_11A_HALF_RATE);
4782 		break;
4783 	case IEEE80211_MODE_QUARTER:
4784 		rt = ath_hal_getratetable(ah, HAL_MODE_11A_QUARTER_RATE);
4785 		break;
4786 	case IEEE80211_MODE_11B:
4787 		rt = ath_hal_getratetable(ah, HAL_MODE_11B);
4788 		break;
4789 	case IEEE80211_MODE_11G:
4790 		rt = ath_hal_getratetable(ah, HAL_MODE_11G);
4791 		break;
4792 	case IEEE80211_MODE_TURBO_A:
4793 		rt = ath_hal_getratetable(ah, HAL_MODE_108A);
4794 		break;
4795 	case IEEE80211_MODE_TURBO_G:
4796 		rt = ath_hal_getratetable(ah, HAL_MODE_108G);
4797 		break;
4798 	case IEEE80211_MODE_STURBO_A:
4799 		rt = ath_hal_getratetable(ah, HAL_MODE_TURBO);
4800 		break;
4801 	case IEEE80211_MODE_11NA:
4802 		rt = ath_hal_getratetable(ah, HAL_MODE_11NA_HT20);
4803 		break;
4804 	case IEEE80211_MODE_11NG:
4805 		rt = ath_hal_getratetable(ah, HAL_MODE_11NG_HT20);
4806 		break;
4807 	default:
4808 		DPRINTF(sc, ATH_DEBUG_ANY, "%s: invalid mode %u\n",
4809 			__func__, mode);
4810 		return 0;
4811 	}
4812 	sc->sc_rates[mode] = rt;
4813 	return (rt != NULL);
4814 }
4815 
4816 static void
4817 ath_setcurmode(struct ath_softc *sc, enum ieee80211_phymode mode)
4818 {
4819 #define	N(a)	(sizeof(a)/sizeof(a[0]))
4820 	/* NB: on/off times from the Atheros NDIS driver, w/ permission */
4821 	static const struct {
4822 		u_int		rate;		/* tx/rx 802.11 rate */
4823 		u_int16_t	timeOn;		/* LED on time (ms) */
4824 		u_int16_t	timeOff;	/* LED off time (ms) */
4825 	} blinkrates[] = {
4826 		{ 108,  40,  10 },
4827 		{  96,  44,  11 },
4828 		{  72,  50,  13 },
4829 		{  48,  57,  14 },
4830 		{  36,  67,  16 },
4831 		{  24,  80,  20 },
4832 		{  22, 100,  25 },
4833 		{  18, 133,  34 },
4834 		{  12, 160,  40 },
4835 		{  10, 200,  50 },
4836 		{   6, 240,  58 },
4837 		{   4, 267,  66 },
4838 		{   2, 400, 100 },
4839 		{   0, 500, 130 },
4840 		/* XXX half/quarter rates */
4841 	};
4842 	const HAL_RATE_TABLE *rt;
4843 	int i, j;
4844 
4845 	memset(sc->sc_rixmap, 0xff, sizeof(sc->sc_rixmap));
4846 	rt = sc->sc_rates[mode];
4847 	KASSERT(rt != NULL, ("no h/w rate set for phy mode %u", mode));
4848 	for (i = 0; i < rt->rateCount; i++) {
4849 		uint8_t ieeerate = rt->info[i].dot11Rate & IEEE80211_RATE_VAL;
4850 		if (rt->info[i].phy != IEEE80211_T_HT)
4851 			sc->sc_rixmap[ieeerate] = i;
4852 		else
4853 			sc->sc_rixmap[ieeerate | IEEE80211_RATE_MCS] = i;
4854 	}
4855 	memset(sc->sc_hwmap, 0, sizeof(sc->sc_hwmap));
4856 	for (i = 0; i < N(sc->sc_hwmap); i++) {
4857 		if (i >= rt->rateCount) {
4858 			sc->sc_hwmap[i].ledon = (500 * hz) / 1000;
4859 			sc->sc_hwmap[i].ledoff = (130 * hz) / 1000;
4860 			continue;
4861 		}
4862 		sc->sc_hwmap[i].ieeerate =
4863 			rt->info[i].dot11Rate & IEEE80211_RATE_VAL;
4864 		if (rt->info[i].phy == IEEE80211_T_HT)
4865 			sc->sc_hwmap[i].ieeerate |= IEEE80211_RATE_MCS;
4866 		sc->sc_hwmap[i].txflags = IEEE80211_RADIOTAP_F_DATAPAD;
4867 		if (rt->info[i].shortPreamble ||
4868 		    rt->info[i].phy == IEEE80211_T_OFDM)
4869 			sc->sc_hwmap[i].txflags |= IEEE80211_RADIOTAP_F_SHORTPRE;
4870 		sc->sc_hwmap[i].rxflags = sc->sc_hwmap[i].txflags;
4871 		for (j = 0; j < N(blinkrates)-1; j++)
4872 			if (blinkrates[j].rate == sc->sc_hwmap[i].ieeerate)
4873 				break;
4874 		/* NB: this uses the last entry if the rate isn't found */
4875 		/* XXX beware of overlow */
4876 		sc->sc_hwmap[i].ledon = (blinkrates[j].timeOn * hz) / 1000;
4877 		sc->sc_hwmap[i].ledoff = (blinkrates[j].timeOff * hz) / 1000;
4878 	}
4879 	sc->sc_currates = rt;
4880 	sc->sc_curmode = mode;
4881 	/*
4882 	 * All protection frames are transmited at 2Mb/s for
4883 	 * 11g, otherwise at 1Mb/s.
4884 	 */
4885 	if (mode == IEEE80211_MODE_11G)
4886 		sc->sc_protrix = ath_tx_findrix(sc, 2*2);
4887 	else
4888 		sc->sc_protrix = ath_tx_findrix(sc, 2*1);
4889 	/* NB: caller is responsible for resetting rate control state */
4890 #undef N
4891 }
4892 
4893 static void
4894 ath_watchdog(void *arg)
4895 {
4896 	struct ath_softc *sc = arg;
4897 	int do_reset = 0;
4898 
4899 	if (sc->sc_wd_timer != 0 && --sc->sc_wd_timer == 0) {
4900 		struct ifnet *ifp = sc->sc_ifp;
4901 		uint32_t hangs;
4902 
4903 		if (ath_hal_gethangstate(sc->sc_ah, 0xffff, &hangs) &&
4904 		    hangs != 0) {
4905 			if_printf(ifp, "%s hang detected (0x%x)\n",
4906 			    hangs & 0xff ? "bb" : "mac", hangs);
4907 		} else
4908 			if_printf(ifp, "device timeout\n");
4909 		do_reset = 1;
4910 		ifp->if_oerrors++;
4911 		sc->sc_stats.ast_watchdog++;
4912 	}
4913 
4914 	/*
4915 	 * We can't hold the lock across the ath_reset() call.
4916 	 *
4917 	 * And since this routine can't hold a lock and sleep,
4918 	 * do the reset deferred.
4919 	 */
4920 	if (do_reset) {
4921 		taskqueue_enqueue(sc->sc_tq, &sc->sc_resettask);
4922 	}
4923 
4924 	callout_schedule(&sc->sc_wd_ch, hz);
4925 }
4926 
4927 #ifdef ATH_DIAGAPI
4928 /*
4929  * Diagnostic interface to the HAL.  This is used by various
4930  * tools to do things like retrieve register contents for
4931  * debugging.  The mechanism is intentionally opaque so that
4932  * it can change frequently w/o concern for compatiblity.
4933  */
4934 static int
4935 ath_ioctl_diag(struct ath_softc *sc, struct ath_diag *ad)
4936 {
4937 	struct ath_hal *ah = sc->sc_ah;
4938 	u_int id = ad->ad_id & ATH_DIAG_ID;
4939 	void *indata = NULL;
4940 	void *outdata = NULL;
4941 	u_int32_t insize = ad->ad_in_size;
4942 	u_int32_t outsize = ad->ad_out_size;
4943 	int error = 0;
4944 
4945 	if (ad->ad_id & ATH_DIAG_IN) {
4946 		/*
4947 		 * Copy in data.
4948 		 */
4949 		indata = malloc(insize, M_TEMP, M_NOWAIT);
4950 		if (indata == NULL) {
4951 			error = ENOMEM;
4952 			goto bad;
4953 		}
4954 		error = copyin(ad->ad_in_data, indata, insize);
4955 		if (error)
4956 			goto bad;
4957 	}
4958 	if (ad->ad_id & ATH_DIAG_DYN) {
4959 		/*
4960 		 * Allocate a buffer for the results (otherwise the HAL
4961 		 * returns a pointer to a buffer where we can read the
4962 		 * results).  Note that we depend on the HAL leaving this
4963 		 * pointer for us to use below in reclaiming the buffer;
4964 		 * may want to be more defensive.
4965 		 */
4966 		outdata = malloc(outsize, M_TEMP, M_NOWAIT);
4967 		if (outdata == NULL) {
4968 			error = ENOMEM;
4969 			goto bad;
4970 		}
4971 	}
4972 	if (ath_hal_getdiagstate(ah, id, indata, insize, &outdata, &outsize)) {
4973 		if (outsize < ad->ad_out_size)
4974 			ad->ad_out_size = outsize;
4975 		if (outdata != NULL)
4976 			error = copyout(outdata, ad->ad_out_data,
4977 					ad->ad_out_size);
4978 	} else {
4979 		error = EINVAL;
4980 	}
4981 bad:
4982 	if ((ad->ad_id & ATH_DIAG_IN) && indata != NULL)
4983 		free(indata, M_TEMP);
4984 	if ((ad->ad_id & ATH_DIAG_DYN) && outdata != NULL)
4985 		free(outdata, M_TEMP);
4986 	return error;
4987 }
4988 #endif /* ATH_DIAGAPI */
4989 
4990 static int
4991 ath_ioctl(struct ifnet *ifp, u_long cmd, caddr_t data)
4992 {
4993 #define	IS_RUNNING(ifp) \
4994 	((ifp->if_flags & IFF_UP) && (ifp->if_drv_flags & IFF_DRV_RUNNING))
4995 	struct ath_softc *sc = ifp->if_softc;
4996 	struct ieee80211com *ic = ifp->if_l2com;
4997 	struct ifreq *ifr = (struct ifreq *)data;
4998 	const HAL_RATE_TABLE *rt;
4999 	int error = 0;
5000 
5001 	switch (cmd) {
5002 	case SIOCSIFFLAGS:
5003 		ATH_LOCK(sc);
5004 		if (IS_RUNNING(ifp)) {
5005 			/*
5006 			 * To avoid rescanning another access point,
5007 			 * do not call ath_init() here.  Instead,
5008 			 * only reflect promisc mode settings.
5009 			 */
5010 			ath_mode_init(sc);
5011 		} else if (ifp->if_flags & IFF_UP) {
5012 			/*
5013 			 * Beware of being called during attach/detach
5014 			 * to reset promiscuous mode.  In that case we
5015 			 * will still be marked UP but not RUNNING.
5016 			 * However trying to re-init the interface
5017 			 * is the wrong thing to do as we've already
5018 			 * torn down much of our state.  There's
5019 			 * probably a better way to deal with this.
5020 			 */
5021 			if (!sc->sc_invalid)
5022 				ath_init(sc);	/* XXX lose error */
5023 		} else {
5024 			ath_stop_locked(ifp);
5025 #ifdef notyet
5026 			/* XXX must wakeup in places like ath_vap_delete */
5027 			if (!sc->sc_invalid)
5028 				ath_hal_setpower(sc->sc_ah, HAL_PM_FULL_SLEEP);
5029 #endif
5030 		}
5031 		ATH_UNLOCK(sc);
5032 		break;
5033 	case SIOCGIFMEDIA:
5034 	case SIOCSIFMEDIA:
5035 		error = ifmedia_ioctl(ifp, ifr, &ic->ic_media, cmd);
5036 		break;
5037 	case SIOCGATHSTATS:
5038 		/* NB: embed these numbers to get a consistent view */
5039 		sc->sc_stats.ast_tx_packets = ifp->if_opackets;
5040 		sc->sc_stats.ast_rx_packets = ifp->if_ipackets;
5041 		sc->sc_stats.ast_tx_rssi = ATH_RSSI(sc->sc_halstats.ns_avgtxrssi);
5042 		sc->sc_stats.ast_rx_rssi = ATH_RSSI(sc->sc_halstats.ns_avgrssi);
5043 #ifdef IEEE80211_SUPPORT_TDMA
5044 		sc->sc_stats.ast_tdma_tsfadjp = TDMA_AVG(sc->sc_avgtsfdeltap);
5045 		sc->sc_stats.ast_tdma_tsfadjm = TDMA_AVG(sc->sc_avgtsfdeltam);
5046 #endif
5047 		rt = sc->sc_currates;
5048 		sc->sc_stats.ast_tx_rate =
5049 		    rt->info[sc->sc_txrix].dot11Rate &~ IEEE80211_RATE_BASIC;
5050 		if (rt->info[sc->sc_txrix].phy & IEEE80211_T_HT)
5051 			sc->sc_stats.ast_tx_rate |= IEEE80211_RATE_MCS;
5052 		return copyout(&sc->sc_stats,
5053 		    ifr->ifr_data, sizeof (sc->sc_stats));
5054 	case SIOCGATHAGSTATS:
5055 		return copyout(&sc->sc_aggr_stats,
5056 		    ifr->ifr_data, sizeof (sc->sc_aggr_stats));
5057 	case SIOCZATHSTATS:
5058 		error = priv_check(curthread, PRIV_DRIVER);
5059 		if (error == 0) {
5060 			memset(&sc->sc_stats, 0, sizeof(sc->sc_stats));
5061 			memset(&sc->sc_aggr_stats, 0,
5062 			    sizeof(sc->sc_aggr_stats));
5063 			memset(&sc->sc_intr_stats, 0,
5064 			    sizeof(sc->sc_intr_stats));
5065 		}
5066 		break;
5067 #ifdef ATH_DIAGAPI
5068 	case SIOCGATHDIAG:
5069 		error = ath_ioctl_diag(sc, (struct ath_diag *) ifr);
5070 		break;
5071 	case SIOCGATHPHYERR:
5072 		error = ath_ioctl_phyerr(sc,(struct ath_diag*) ifr);
5073 		break;
5074 #endif
5075 	case SIOCGIFADDR:
5076 		error = ether_ioctl(ifp, cmd, data);
5077 		break;
5078 	default:
5079 		error = EINVAL;
5080 		break;
5081 	}
5082 	return error;
5083 #undef IS_RUNNING
5084 }
5085 
5086 /*
5087  * Announce various information on device/driver attach.
5088  */
5089 static void
5090 ath_announce(struct ath_softc *sc)
5091 {
5092 	struct ifnet *ifp = sc->sc_ifp;
5093 	struct ath_hal *ah = sc->sc_ah;
5094 
5095 	if_printf(ifp, "AR%s mac %d.%d RF%s phy %d.%d\n",
5096 		ath_hal_mac_name(ah), ah->ah_macVersion, ah->ah_macRev,
5097 		ath_hal_rf_name(ah), ah->ah_phyRev >> 4, ah->ah_phyRev & 0xf);
5098 	if_printf(ifp, "2GHz radio: 0x%.4x; 5GHz radio: 0x%.4x\n",
5099 		ah->ah_analog2GhzRev, ah->ah_analog5GhzRev);
5100 	if (bootverbose) {
5101 		int i;
5102 		for (i = 0; i <= WME_AC_VO; i++) {
5103 			struct ath_txq *txq = sc->sc_ac2q[i];
5104 			if_printf(ifp, "Use hw queue %u for %s traffic\n",
5105 				txq->axq_qnum, ieee80211_wme_acnames[i]);
5106 		}
5107 		if_printf(ifp, "Use hw queue %u for CAB traffic\n",
5108 			sc->sc_cabq->axq_qnum);
5109 		if_printf(ifp, "Use hw queue %u for beacons\n", sc->sc_bhalq);
5110 	}
5111 	if (ath_rxbuf != ATH_RXBUF)
5112 		if_printf(ifp, "using %u rx buffers\n", ath_rxbuf);
5113 	if (ath_txbuf != ATH_TXBUF)
5114 		if_printf(ifp, "using %u tx buffers\n", ath_txbuf);
5115 	if (sc->sc_mcastkey && bootverbose)
5116 		if_printf(ifp, "using multicast key search\n");
5117 }
5118 
5119 static void
5120 ath_dfs_tasklet(void *p, int npending)
5121 {
5122 	struct ath_softc *sc = (struct ath_softc *) p;
5123 	struct ifnet *ifp = sc->sc_ifp;
5124 	struct ieee80211com *ic = ifp->if_l2com;
5125 
5126 	/*
5127 	 * If previous processing has found a radar event,
5128 	 * signal this to the net80211 layer to begin DFS
5129 	 * processing.
5130 	 */
5131 	if (ath_dfs_process_radar_event(sc, sc->sc_curchan)) {
5132 		/* DFS event found, initiate channel change */
5133 		/*
5134 		 * XXX doesn't currently tell us whether the event
5135 		 * XXX was found in the primary or extension
5136 		 * XXX channel!
5137 		 */
5138 		IEEE80211_LOCK(ic);
5139 		ieee80211_dfs_notify_radar(ic, sc->sc_curchan);
5140 		IEEE80211_UNLOCK(ic);
5141 	}
5142 }
5143 
5144 MODULE_VERSION(if_ath, 1);
5145 MODULE_DEPEND(if_ath, wlan, 1, 1, 1);          /* 802.11 media layer */
5146 #if	defined(IEEE80211_ALQ) || defined(AH_DEBUG_ALQ)
5147 MODULE_DEPEND(if_ath, alq, 1, 1, 1);
5148 #endif
5149