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