xref: /freebsd/sys/dev/ath/if_ath.c (revision 8a166cafe0965f6bd72cd3d2f5372704f05cb5e8)
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_IC_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_IC_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_IC_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_IC_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_IC_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_IC_LOCK(sc);
2883 	TAILQ_CONCAT(&txlist, &sc->sc_txbuf_list, bf_list);
2884 	ATH_TX_IC_UNLOCK(sc);
2885 
2886 	/*
2887 	 * Attempt to transmit each frame.
2888 	 *
2889 	 * In the old code path - if a TX fragment fails, subsequent
2890 	 * fragments in that group would be aborted.
2891 	 *
2892 	 * It would be nice to chain together TX fragments in this
2893 	 * way so they can be aborted together.
2894 	 */
2895 	ATH_TX_LOCK(sc);
2896 	TAILQ_FOREACH_SAFE(bf, &txlist, bf_list, bf_next) {
2897 		/*
2898 		 * Clear, because we're going to reuse this
2899 		 * as a real ath_buf now
2900 		 */
2901 		ni = bf->bf_node;
2902 		m = bf->bf_m;
2903 
2904 		bf->bf_node = NULL;
2905 		bf->bf_m = NULL;
2906 
2907 		/*
2908 		 * Remove it from the list.
2909 		 */
2910 		TAILQ_REMOVE(&txlist, bf, bf_list);
2911 
2912 		/*
2913 		 * If we fail, free this buffer and go to the next one;
2914 		 * ath_tx_start() frees the mbuf but not the node
2915 		 * reference.
2916 		 */
2917 		if (ath_tx_start(sc, ni, bf, m)) {
2918 			/*
2919 			 * XXX m is freed by ath_tx_start(); node reference
2920 			 * is not!
2921 			 */
2922 			DPRINTF(sc, ATH_DEBUG_XMIT,
2923 			    "%s: failed; bf=%p, ni=%p, m=%p\n",
2924 			    __func__,
2925 			    bf,
2926 			    ni,
2927 			    m);
2928 			ifp->if_oerrors++;
2929 			bf->bf_m = NULL;
2930 			bf->bf_node = NULL;
2931 			ATH_TXBUF_LOCK(sc);
2932 			ath_returnbuf_head(sc, bf);
2933 			ATH_TXBUF_UNLOCK(sc);
2934 			/*
2935 			 * XXX todo, free the node outside of
2936 			 * the TX lock context!
2937 			 */
2938 			if (ni != NULL)
2939 				ieee80211_free_node(ni);
2940 		} else {
2941 			/*
2942 			 * Check here if the node is in power save state.
2943 			 * XXX we should hold a node ref here, and release
2944 			 * it after the TX has completed.
2945 			 */
2946 			ath_tx_update_tim(sc, ni, 1);
2947 			ifp->if_opackets++;
2948 		}
2949 
2950 		/*
2951 		 * XXX should check for state change and flip out
2952 		 * if needed.
2953 		 */
2954 	}
2955 	ATH_TX_UNLOCK(sc);
2956 
2957 	/*
2958 	 * If we break out early (eg a state change) we should prepend these
2959 	 * frames onto the TX queue.
2960 	 */
2961 }
2962 
2963 /*
2964  * This is now primarily used by the net80211 layer to kick-start
2965  * queue processing.
2966  */
2967 void
2968 ath_start(struct ifnet *ifp)
2969 {
2970 	struct mbuf *m;
2971 	struct ath_softc *sc = ifp->if_softc;
2972 	struct ieee80211_node *ni;
2973 	int npkts = 0;
2974 
2975 	ATH_TX_UNLOCK_ASSERT(sc);
2976 
2977 	if ((ifp->if_drv_flags & IFF_DRV_RUNNING) == 0 || sc->sc_invalid)
2978 		return;
2979 
2980 	/*
2981 	 * If we're below the free buffer limit, don't dequeue anything.
2982 	 * The original code would not dequeue anything from the queue
2983 	 * if allocating an ath_buf failed.
2984 	 *
2985 	 * For if_transmit, we have to either queue or drop the frame.
2986 	 * So we have to try and queue it _somewhere_.
2987 	 */
2988 	for (;;) {
2989 		IFQ_DEQUEUE(&ifp->if_snd, m);
2990 		if (m == NULL) {
2991 			break;
2992 		}
2993 
2994 		/*
2995 		 * If we do fail here, just break out for now
2996 		 * and wait until we've transmitted something
2997 		 * before we attempt again?
2998 		 */
2999 		if (ath_txq_qadd(ifp, m) < 0) {
3000 			DPRINTF(sc, ATH_DEBUG_XMIT,
3001 			    "%s: ath_txq_qadd failed\n",
3002 			    __func__);
3003 			ni = (struct ieee80211_node *) m->m_pkthdr.rcvif;
3004 			if (ni != NULL)
3005 				ieee80211_free_node(ni);
3006 			ath_freetx(m);
3007 			break;
3008 		}
3009 		npkts++;
3010 	}
3011 
3012 	/*
3013 	 * Kick the taskqueue into activity, but only if we
3014 	 * queued something.
3015 	 */
3016 	if (npkts > 0)
3017 		ath_tx_kick(sc);
3018 }
3019 
3020 static int
3021 ath_media_change(struct ifnet *ifp)
3022 {
3023 	int error = ieee80211_media_change(ifp);
3024 	/* NB: only the fixed rate can change and that doesn't need a reset */
3025 	return (error == ENETRESET ? 0 : error);
3026 }
3027 
3028 /*
3029  * Block/unblock tx+rx processing while a key change is done.
3030  * We assume the caller serializes key management operations
3031  * so we only need to worry about synchronization with other
3032  * uses that originate in the driver.
3033  */
3034 static void
3035 ath_key_update_begin(struct ieee80211vap *vap)
3036 {
3037 	struct ifnet *ifp = vap->iv_ic->ic_ifp;
3038 	struct ath_softc *sc = ifp->if_softc;
3039 
3040 	DPRINTF(sc, ATH_DEBUG_KEYCACHE, "%s:\n", __func__);
3041 	taskqueue_block(sc->sc_tq);
3042 	taskqueue_block(sc->sc_tx_tq);
3043 	IF_LOCK(&ifp->if_snd);		/* NB: doesn't block mgmt frames */
3044 }
3045 
3046 static void
3047 ath_key_update_end(struct ieee80211vap *vap)
3048 {
3049 	struct ifnet *ifp = vap->iv_ic->ic_ifp;
3050 	struct ath_softc *sc = ifp->if_softc;
3051 
3052 	DPRINTF(sc, ATH_DEBUG_KEYCACHE, "%s:\n", __func__);
3053 	IF_UNLOCK(&ifp->if_snd);
3054 	taskqueue_unblock(sc->sc_tq);
3055 	taskqueue_unblock(sc->sc_tx_tq);
3056 }
3057 
3058 static void
3059 ath_update_promisc(struct ifnet *ifp)
3060 {
3061 	struct ath_softc *sc = ifp->if_softc;
3062 	u_int32_t rfilt;
3063 
3064 	/* configure rx filter */
3065 	rfilt = ath_calcrxfilter(sc);
3066 	ath_hal_setrxfilter(sc->sc_ah, rfilt);
3067 
3068 	DPRINTF(sc, ATH_DEBUG_MODE, "%s: RX filter 0x%x\n", __func__, rfilt);
3069 }
3070 
3071 static void
3072 ath_update_mcast(struct ifnet *ifp)
3073 {
3074 	struct ath_softc *sc = ifp->if_softc;
3075 	u_int32_t mfilt[2];
3076 
3077 	/* calculate and install multicast filter */
3078 	if ((ifp->if_flags & IFF_ALLMULTI) == 0) {
3079 		struct ifmultiaddr *ifma;
3080 		/*
3081 		 * Merge multicast addresses to form the hardware filter.
3082 		 */
3083 		mfilt[0] = mfilt[1] = 0;
3084 		if_maddr_rlock(ifp);	/* XXX need some fiddling to remove? */
3085 		TAILQ_FOREACH(ifma, &ifp->if_multiaddrs, ifma_link) {
3086 			caddr_t dl;
3087 			u_int32_t val;
3088 			u_int8_t pos;
3089 
3090 			/* calculate XOR of eight 6bit values */
3091 			dl = LLADDR((struct sockaddr_dl *) ifma->ifma_addr);
3092 			val = LE_READ_4(dl + 0);
3093 			pos = (val >> 18) ^ (val >> 12) ^ (val >> 6) ^ val;
3094 			val = LE_READ_4(dl + 3);
3095 			pos ^= (val >> 18) ^ (val >> 12) ^ (val >> 6) ^ val;
3096 			pos &= 0x3f;
3097 			mfilt[pos / 32] |= (1 << (pos % 32));
3098 		}
3099 		if_maddr_runlock(ifp);
3100 	} else
3101 		mfilt[0] = mfilt[1] = ~0;
3102 	ath_hal_setmcastfilter(sc->sc_ah, mfilt[0], mfilt[1]);
3103 	DPRINTF(sc, ATH_DEBUG_MODE, "%s: MC filter %08x:%08x\n",
3104 		__func__, mfilt[0], mfilt[1]);
3105 }
3106 
3107 void
3108 ath_mode_init(struct ath_softc *sc)
3109 {
3110 	struct ifnet *ifp = sc->sc_ifp;
3111 	struct ath_hal *ah = sc->sc_ah;
3112 	u_int32_t rfilt;
3113 
3114 	/* configure rx filter */
3115 	rfilt = ath_calcrxfilter(sc);
3116 	ath_hal_setrxfilter(ah, rfilt);
3117 
3118 	/* configure operational mode */
3119 	ath_hal_setopmode(ah);
3120 
3121 	DPRINTF(sc, ATH_DEBUG_STATE | ATH_DEBUG_MODE,
3122 	    "%s: ah=%p, ifp=%p, if_addr=%p\n",
3123 	    __func__,
3124 	    ah,
3125 	    ifp,
3126 	    (ifp == NULL) ? NULL : ifp->if_addr);
3127 
3128 	/* handle any link-level address change */
3129 	ath_hal_setmac(ah, IF_LLADDR(ifp));
3130 
3131 	/* calculate and install multicast filter */
3132 	ath_update_mcast(ifp);
3133 }
3134 
3135 /*
3136  * Set the slot time based on the current setting.
3137  */
3138 void
3139 ath_setslottime(struct ath_softc *sc)
3140 {
3141 	struct ieee80211com *ic = sc->sc_ifp->if_l2com;
3142 	struct ath_hal *ah = sc->sc_ah;
3143 	u_int usec;
3144 
3145 	if (IEEE80211_IS_CHAN_HALF(ic->ic_curchan))
3146 		usec = 13;
3147 	else if (IEEE80211_IS_CHAN_QUARTER(ic->ic_curchan))
3148 		usec = 21;
3149 	else if (IEEE80211_IS_CHAN_ANYG(ic->ic_curchan)) {
3150 		/* honor short/long slot time only in 11g */
3151 		/* XXX shouldn't honor on pure g or turbo g channel */
3152 		if (ic->ic_flags & IEEE80211_F_SHSLOT)
3153 			usec = HAL_SLOT_TIME_9;
3154 		else
3155 			usec = HAL_SLOT_TIME_20;
3156 	} else
3157 		usec = HAL_SLOT_TIME_9;
3158 
3159 	DPRINTF(sc, ATH_DEBUG_RESET,
3160 	    "%s: chan %u MHz flags 0x%x %s slot, %u usec\n",
3161 	    __func__, ic->ic_curchan->ic_freq, ic->ic_curchan->ic_flags,
3162 	    ic->ic_flags & IEEE80211_F_SHSLOT ? "short" : "long", usec);
3163 
3164 	ath_hal_setslottime(ah, usec);
3165 	sc->sc_updateslot = OK;
3166 }
3167 
3168 /*
3169  * Callback from the 802.11 layer to update the
3170  * slot time based on the current setting.
3171  */
3172 static void
3173 ath_updateslot(struct ifnet *ifp)
3174 {
3175 	struct ath_softc *sc = ifp->if_softc;
3176 	struct ieee80211com *ic = ifp->if_l2com;
3177 
3178 	/*
3179 	 * When not coordinating the BSS, change the hardware
3180 	 * immediately.  For other operation we defer the change
3181 	 * until beacon updates have propagated to the stations.
3182 	 */
3183 	if (ic->ic_opmode == IEEE80211_M_HOSTAP ||
3184 	    ic->ic_opmode == IEEE80211_M_MBSS)
3185 		sc->sc_updateslot = UPDATE;
3186 	else
3187 		ath_setslottime(sc);
3188 }
3189 
3190 /*
3191  * Append the contents of src to dst; both queues
3192  * are assumed to be locked.
3193  */
3194 void
3195 ath_txqmove(struct ath_txq *dst, struct ath_txq *src)
3196 {
3197 
3198 	TAILQ_CONCAT(&dst->axq_q, &src->axq_q, bf_list);
3199 	dst->axq_link = src->axq_link;
3200 	src->axq_link = NULL;
3201 	dst->axq_depth += src->axq_depth;
3202 	dst->axq_aggr_depth += src->axq_aggr_depth;
3203 	src->axq_depth = 0;
3204 	src->axq_aggr_depth = 0;
3205 }
3206 
3207 /*
3208  * Reset the hardware, with no loss.
3209  *
3210  * This can't be used for a general case reset.
3211  */
3212 static void
3213 ath_reset_proc(void *arg, int pending)
3214 {
3215 	struct ath_softc *sc = arg;
3216 	struct ifnet *ifp = sc->sc_ifp;
3217 
3218 #if 0
3219 	if_printf(ifp, "%s: resetting\n", __func__);
3220 #endif
3221 	ath_reset(ifp, ATH_RESET_NOLOSS);
3222 }
3223 
3224 /*
3225  * Reset the hardware after detecting beacons have stopped.
3226  */
3227 static void
3228 ath_bstuck_proc(void *arg, int pending)
3229 {
3230 	struct ath_softc *sc = arg;
3231 	struct ifnet *ifp = sc->sc_ifp;
3232 	uint32_t hangs = 0;
3233 
3234 	if (ath_hal_gethangstate(sc->sc_ah, 0xff, &hangs) && hangs != 0)
3235 		if_printf(ifp, "bb hang detected (0x%x)\n", hangs);
3236 
3237 	if_printf(ifp, "stuck beacon; resetting (bmiss count %u)\n",
3238 		sc->sc_bmisscount);
3239 	sc->sc_stats.ast_bstuck++;
3240 	/*
3241 	 * This assumes that there's no simultaneous channel mode change
3242 	 * occuring.
3243 	 */
3244 	ath_reset(ifp, ATH_RESET_NOLOSS);
3245 }
3246 
3247 static void
3248 ath_load_cb(void *arg, bus_dma_segment_t *segs, int nsegs, int error)
3249 {
3250 	bus_addr_t *paddr = (bus_addr_t*) arg;
3251 	KASSERT(error == 0, ("error %u on bus_dma callback", error));
3252 	*paddr = segs->ds_addr;
3253 }
3254 
3255 /*
3256  * Allocate the descriptors and appropriate DMA tag/setup.
3257  *
3258  * For some situations (eg EDMA TX completion), there isn't a requirement
3259  * for the ath_buf entries to be allocated.
3260  */
3261 int
3262 ath_descdma_alloc_desc(struct ath_softc *sc,
3263 	struct ath_descdma *dd, ath_bufhead *head,
3264 	const char *name, int ds_size, int ndesc)
3265 {
3266 #define	DS2PHYS(_dd, _ds) \
3267 	((_dd)->dd_desc_paddr + ((caddr_t)(_ds) - (caddr_t)(_dd)->dd_desc))
3268 #define	ATH_DESC_4KB_BOUND_CHECK(_daddr, _len) \
3269 	((((u_int32_t)(_daddr) & 0xFFF) > (0x1000 - (_len))) ? 1 : 0)
3270 	struct ifnet *ifp = sc->sc_ifp;
3271 	int error;
3272 
3273 	dd->dd_descsize = ds_size;
3274 
3275 	DPRINTF(sc, ATH_DEBUG_RESET,
3276 	    "%s: %s DMA: %u desc, %d bytes per descriptor\n",
3277 	    __func__, name, ndesc, dd->dd_descsize);
3278 
3279 	dd->dd_name = name;
3280 	dd->dd_desc_len = dd->dd_descsize * ndesc;
3281 
3282 	/*
3283 	 * Merlin work-around:
3284 	 * Descriptors that cross the 4KB boundary can't be used.
3285 	 * Assume one skipped descriptor per 4KB page.
3286 	 */
3287 	if (! ath_hal_split4ktrans(sc->sc_ah)) {
3288 		int numpages = dd->dd_desc_len / 4096;
3289 		dd->dd_desc_len += ds_size * numpages;
3290 	}
3291 
3292 	/*
3293 	 * Setup DMA descriptor area.
3294 	 */
3295 	error = bus_dma_tag_create(bus_get_dma_tag(sc->sc_dev),	/* parent */
3296 		       PAGE_SIZE, 0,		/* alignment, bounds */
3297 		       BUS_SPACE_MAXADDR_32BIT,	/* lowaddr */
3298 		       BUS_SPACE_MAXADDR,	/* highaddr */
3299 		       NULL, NULL,		/* filter, filterarg */
3300 		       dd->dd_desc_len,		/* maxsize */
3301 		       1,			/* nsegments */
3302 		       dd->dd_desc_len,		/* maxsegsize */
3303 		       BUS_DMA_ALLOCNOW,	/* flags */
3304 		       NULL,			/* lockfunc */
3305 		       NULL,			/* lockarg */
3306 		       &dd->dd_dmat);
3307 	if (error != 0) {
3308 		if_printf(ifp, "cannot allocate %s DMA tag\n", dd->dd_name);
3309 		return error;
3310 	}
3311 
3312 	/* allocate descriptors */
3313 	error = bus_dmamem_alloc(dd->dd_dmat, (void**) &dd->dd_desc,
3314 				 BUS_DMA_NOWAIT | BUS_DMA_COHERENT,
3315 				 &dd->dd_dmamap);
3316 	if (error != 0) {
3317 		if_printf(ifp, "unable to alloc memory for %u %s descriptors, "
3318 			"error %u\n", ndesc, dd->dd_name, error);
3319 		goto fail1;
3320 	}
3321 
3322 	error = bus_dmamap_load(dd->dd_dmat, dd->dd_dmamap,
3323 				dd->dd_desc, dd->dd_desc_len,
3324 				ath_load_cb, &dd->dd_desc_paddr,
3325 				BUS_DMA_NOWAIT);
3326 	if (error != 0) {
3327 		if_printf(ifp, "unable to map %s descriptors, error %u\n",
3328 			dd->dd_name, error);
3329 		goto fail2;
3330 	}
3331 
3332 	DPRINTF(sc, ATH_DEBUG_RESET, "%s: %s DMA map: %p (%lu) -> %p (%lu)\n",
3333 	    __func__, dd->dd_name, (uint8_t *) dd->dd_desc,
3334 	    (u_long) dd->dd_desc_len, (caddr_t) dd->dd_desc_paddr,
3335 	    /*XXX*/ (u_long) dd->dd_desc_len);
3336 
3337 	return (0);
3338 
3339 fail2:
3340 	bus_dmamem_free(dd->dd_dmat, dd->dd_desc, dd->dd_dmamap);
3341 fail1:
3342 	bus_dma_tag_destroy(dd->dd_dmat);
3343 	memset(dd, 0, sizeof(*dd));
3344 	return error;
3345 #undef DS2PHYS
3346 #undef ATH_DESC_4KB_BOUND_CHECK
3347 }
3348 
3349 int
3350 ath_descdma_setup(struct ath_softc *sc,
3351 	struct ath_descdma *dd, ath_bufhead *head,
3352 	const char *name, int ds_size, int nbuf, int ndesc)
3353 {
3354 #define	DS2PHYS(_dd, _ds) \
3355 	((_dd)->dd_desc_paddr + ((caddr_t)(_ds) - (caddr_t)(_dd)->dd_desc))
3356 #define	ATH_DESC_4KB_BOUND_CHECK(_daddr, _len) \
3357 	((((u_int32_t)(_daddr) & 0xFFF) > (0x1000 - (_len))) ? 1 : 0)
3358 	struct ifnet *ifp = sc->sc_ifp;
3359 	uint8_t *ds;
3360 	struct ath_buf *bf;
3361 	int i, bsize, error;
3362 
3363 	/* Allocate descriptors */
3364 	error = ath_descdma_alloc_desc(sc, dd, head, name, ds_size,
3365 	    nbuf * ndesc);
3366 
3367 	/* Assume any errors during allocation were dealt with */
3368 	if (error != 0) {
3369 		return (error);
3370 	}
3371 
3372 	ds = (uint8_t *) dd->dd_desc;
3373 
3374 	/* allocate rx buffers */
3375 	bsize = sizeof(struct ath_buf) * nbuf;
3376 	bf = malloc(bsize, M_ATHDEV, M_NOWAIT | M_ZERO);
3377 	if (bf == NULL) {
3378 		if_printf(ifp, "malloc of %s buffers failed, size %u\n",
3379 			dd->dd_name, bsize);
3380 		goto fail3;
3381 	}
3382 	dd->dd_bufptr = bf;
3383 
3384 	TAILQ_INIT(head);
3385 	for (i = 0; i < nbuf; i++, bf++, ds += (ndesc * dd->dd_descsize)) {
3386 		bf->bf_desc = (struct ath_desc *) ds;
3387 		bf->bf_daddr = DS2PHYS(dd, ds);
3388 		if (! ath_hal_split4ktrans(sc->sc_ah)) {
3389 			/*
3390 			 * Merlin WAR: Skip descriptor addresses which
3391 			 * cause 4KB boundary crossing along any point
3392 			 * in the descriptor.
3393 			 */
3394 			 if (ATH_DESC_4KB_BOUND_CHECK(bf->bf_daddr,
3395 			     dd->dd_descsize)) {
3396 				/* Start at the next page */
3397 				ds += 0x1000 - (bf->bf_daddr & 0xFFF);
3398 				bf->bf_desc = (struct ath_desc *) ds;
3399 				bf->bf_daddr = DS2PHYS(dd, ds);
3400 			}
3401 		}
3402 		error = bus_dmamap_create(sc->sc_dmat, BUS_DMA_NOWAIT,
3403 				&bf->bf_dmamap);
3404 		if (error != 0) {
3405 			if_printf(ifp, "unable to create dmamap for %s "
3406 				"buffer %u, error %u\n", dd->dd_name, i, error);
3407 			ath_descdma_cleanup(sc, dd, head);
3408 			return error;
3409 		}
3410 		bf->bf_lastds = bf->bf_desc;	/* Just an initial value */
3411 		TAILQ_INSERT_TAIL(head, bf, bf_list);
3412 	}
3413 
3414 	/*
3415 	 * XXX TODO: ensure that ds doesn't overflow the descriptor
3416 	 * allocation otherwise weird stuff will occur and crash your
3417 	 * machine.
3418 	 */
3419 	return 0;
3420 	/* XXX this should likely just call ath_descdma_cleanup() */
3421 fail3:
3422 	bus_dmamap_unload(dd->dd_dmat, dd->dd_dmamap);
3423 	bus_dmamem_free(dd->dd_dmat, dd->dd_desc, dd->dd_dmamap);
3424 	bus_dma_tag_destroy(dd->dd_dmat);
3425 	memset(dd, 0, sizeof(*dd));
3426 	return error;
3427 #undef DS2PHYS
3428 #undef ATH_DESC_4KB_BOUND_CHECK
3429 }
3430 
3431 /*
3432  * Allocate ath_buf entries but no descriptor contents.
3433  *
3434  * This is for RX EDMA where the descriptors are the header part of
3435  * the RX buffer.
3436  */
3437 int
3438 ath_descdma_setup_rx_edma(struct ath_softc *sc,
3439 	struct ath_descdma *dd, ath_bufhead *head,
3440 	const char *name, int nbuf, int rx_status_len)
3441 {
3442 	struct ifnet *ifp = sc->sc_ifp;
3443 	struct ath_buf *bf;
3444 	int i, bsize, error;
3445 
3446 	DPRINTF(sc, ATH_DEBUG_RESET, "%s: %s DMA: %u buffers\n",
3447 	    __func__, name, nbuf);
3448 
3449 	dd->dd_name = name;
3450 	/*
3451 	 * This is (mostly) purely for show.  We're not allocating any actual
3452 	 * descriptors here as EDMA RX has the descriptor be part
3453 	 * of the RX buffer.
3454 	 *
3455 	 * However, dd_desc_len is used by ath_descdma_free() to determine
3456 	 * whether we have already freed this DMA mapping.
3457 	 */
3458 	dd->dd_desc_len = rx_status_len * nbuf;
3459 	dd->dd_descsize = rx_status_len;
3460 
3461 	/* allocate rx buffers */
3462 	bsize = sizeof(struct ath_buf) * nbuf;
3463 	bf = malloc(bsize, M_ATHDEV, M_NOWAIT | M_ZERO);
3464 	if (bf == NULL) {
3465 		if_printf(ifp, "malloc of %s buffers failed, size %u\n",
3466 			dd->dd_name, bsize);
3467 		error = ENOMEM;
3468 		goto fail3;
3469 	}
3470 	dd->dd_bufptr = bf;
3471 
3472 	TAILQ_INIT(head);
3473 	for (i = 0; i < nbuf; i++, bf++) {
3474 		bf->bf_desc = NULL;
3475 		bf->bf_daddr = 0;
3476 		bf->bf_lastds = NULL;	/* Just an initial value */
3477 
3478 		error = bus_dmamap_create(sc->sc_dmat, BUS_DMA_NOWAIT,
3479 				&bf->bf_dmamap);
3480 		if (error != 0) {
3481 			if_printf(ifp, "unable to create dmamap for %s "
3482 				"buffer %u, error %u\n", dd->dd_name, i, error);
3483 			ath_descdma_cleanup(sc, dd, head);
3484 			return error;
3485 		}
3486 		TAILQ_INSERT_TAIL(head, bf, bf_list);
3487 	}
3488 	return 0;
3489 fail3:
3490 	memset(dd, 0, sizeof(*dd));
3491 	return error;
3492 }
3493 
3494 void
3495 ath_descdma_cleanup(struct ath_softc *sc,
3496 	struct ath_descdma *dd, ath_bufhead *head)
3497 {
3498 	struct ath_buf *bf;
3499 	struct ieee80211_node *ni;
3500 
3501 	if (dd->dd_dmamap != 0) {
3502 		bus_dmamap_unload(dd->dd_dmat, dd->dd_dmamap);
3503 		bus_dmamem_free(dd->dd_dmat, dd->dd_desc, dd->dd_dmamap);
3504 		bus_dma_tag_destroy(dd->dd_dmat);
3505 	}
3506 
3507 	if (head != NULL) {
3508 		TAILQ_FOREACH(bf, head, bf_list) {
3509 			if (bf->bf_m) {
3510 				m_freem(bf->bf_m);
3511 				bf->bf_m = NULL;
3512 			}
3513 			if (bf->bf_dmamap != NULL) {
3514 				bus_dmamap_destroy(sc->sc_dmat, bf->bf_dmamap);
3515 				bf->bf_dmamap = NULL;
3516 			}
3517 			ni = bf->bf_node;
3518 			bf->bf_node = NULL;
3519 			if (ni != NULL) {
3520 				/*
3521 				 * Reclaim node reference.
3522 				 */
3523 				ieee80211_free_node(ni);
3524 			}
3525 		}
3526 	}
3527 
3528 	if (head != NULL)
3529 		TAILQ_INIT(head);
3530 
3531 	if (dd->dd_bufptr != NULL)
3532 		free(dd->dd_bufptr, M_ATHDEV);
3533 	memset(dd, 0, sizeof(*dd));
3534 }
3535 
3536 static int
3537 ath_desc_alloc(struct ath_softc *sc)
3538 {
3539 	int error;
3540 
3541 	error = ath_descdma_setup(sc, &sc->sc_txdma, &sc->sc_txbuf,
3542 		    "tx", sc->sc_tx_desclen, ath_txbuf, ATH_TXDESC);
3543 	if (error != 0) {
3544 		return error;
3545 	}
3546 	sc->sc_txbuf_cnt = ath_txbuf;
3547 
3548 	error = ath_descdma_setup(sc, &sc->sc_txdma_mgmt, &sc->sc_txbuf_mgmt,
3549 		    "tx_mgmt", sc->sc_tx_desclen, ath_txbuf_mgmt,
3550 		    ATH_TXDESC);
3551 	if (error != 0) {
3552 		ath_descdma_cleanup(sc, &sc->sc_txdma, &sc->sc_txbuf);
3553 		return error;
3554 	}
3555 
3556 	/*
3557 	 * XXX mark txbuf_mgmt frames with ATH_BUF_MGMT, so the
3558 	 * flag doesn't have to be set in ath_getbuf_locked().
3559 	 */
3560 
3561 	error = ath_descdma_setup(sc, &sc->sc_bdma, &sc->sc_bbuf,
3562 			"beacon", sc->sc_tx_desclen, ATH_BCBUF, 1);
3563 	if (error != 0) {
3564 		ath_descdma_cleanup(sc, &sc->sc_txdma, &sc->sc_txbuf);
3565 		ath_descdma_cleanup(sc, &sc->sc_txdma_mgmt,
3566 		    &sc->sc_txbuf_mgmt);
3567 		return error;
3568 	}
3569 	return 0;
3570 }
3571 
3572 static void
3573 ath_desc_free(struct ath_softc *sc)
3574 {
3575 
3576 	if (sc->sc_bdma.dd_desc_len != 0)
3577 		ath_descdma_cleanup(sc, &sc->sc_bdma, &sc->sc_bbuf);
3578 	if (sc->sc_txdma.dd_desc_len != 0)
3579 		ath_descdma_cleanup(sc, &sc->sc_txdma, &sc->sc_txbuf);
3580 	if (sc->sc_txdma_mgmt.dd_desc_len != 0)
3581 		ath_descdma_cleanup(sc, &sc->sc_txdma_mgmt,
3582 		    &sc->sc_txbuf_mgmt);
3583 }
3584 
3585 static struct ieee80211_node *
3586 ath_node_alloc(struct ieee80211vap *vap, const uint8_t mac[IEEE80211_ADDR_LEN])
3587 {
3588 	struct ieee80211com *ic = vap->iv_ic;
3589 	struct ath_softc *sc = ic->ic_ifp->if_softc;
3590 	const size_t space = sizeof(struct ath_node) + sc->sc_rc->arc_space;
3591 	struct ath_node *an;
3592 
3593 	an = malloc(space, M_80211_NODE, M_NOWAIT|M_ZERO);
3594 	if (an == NULL) {
3595 		/* XXX stat+msg */
3596 		return NULL;
3597 	}
3598 	ath_rate_node_init(sc, an);
3599 
3600 	/* Setup the mutex - there's no associd yet so set the name to NULL */
3601 	snprintf(an->an_name, sizeof(an->an_name), "%s: node %p",
3602 	    device_get_nameunit(sc->sc_dev), an);
3603 	mtx_init(&an->an_mtx, an->an_name, NULL, MTX_DEF);
3604 
3605 	/* XXX setup ath_tid */
3606 	ath_tx_tid_init(sc, an);
3607 
3608 	DPRINTF(sc, ATH_DEBUG_NODE, "%s: an %p\n", __func__, an);
3609 	return &an->an_node;
3610 }
3611 
3612 static void
3613 ath_node_cleanup(struct ieee80211_node *ni)
3614 {
3615 	struct ieee80211com *ic = ni->ni_ic;
3616 	struct ath_softc *sc = ic->ic_ifp->if_softc;
3617 
3618 	/* Cleanup ath_tid, free unused bufs, unlink bufs in TXQ */
3619 	ath_tx_node_flush(sc, ATH_NODE(ni));
3620 	ath_rate_node_cleanup(sc, ATH_NODE(ni));
3621 	sc->sc_node_cleanup(ni);
3622 }
3623 
3624 static void
3625 ath_node_free(struct ieee80211_node *ni)
3626 {
3627 	struct ieee80211com *ic = ni->ni_ic;
3628 	struct ath_softc *sc = ic->ic_ifp->if_softc;
3629 
3630 	DPRINTF(sc, ATH_DEBUG_NODE, "%s: ni %p\n", __func__, ni);
3631 	mtx_destroy(&ATH_NODE(ni)->an_mtx);
3632 	sc->sc_node_free(ni);
3633 }
3634 
3635 static void
3636 ath_node_getsignal(const struct ieee80211_node *ni, int8_t *rssi, int8_t *noise)
3637 {
3638 	struct ieee80211com *ic = ni->ni_ic;
3639 	struct ath_softc *sc = ic->ic_ifp->if_softc;
3640 	struct ath_hal *ah = sc->sc_ah;
3641 
3642 	*rssi = ic->ic_node_getrssi(ni);
3643 	if (ni->ni_chan != IEEE80211_CHAN_ANYC)
3644 		*noise = ath_hal_getchannoise(ah, ni->ni_chan);
3645 	else
3646 		*noise = -95;		/* nominally correct */
3647 }
3648 
3649 /*
3650  * Set the default antenna.
3651  */
3652 void
3653 ath_setdefantenna(struct ath_softc *sc, u_int antenna)
3654 {
3655 	struct ath_hal *ah = sc->sc_ah;
3656 
3657 	/* XXX block beacon interrupts */
3658 	ath_hal_setdefantenna(ah, antenna);
3659 	if (sc->sc_defant != antenna)
3660 		sc->sc_stats.ast_ant_defswitch++;
3661 	sc->sc_defant = antenna;
3662 	sc->sc_rxotherant = 0;
3663 }
3664 
3665 static void
3666 ath_txq_init(struct ath_softc *sc, struct ath_txq *txq, int qnum)
3667 {
3668 	txq->axq_qnum = qnum;
3669 	txq->axq_ac = 0;
3670 	txq->axq_depth = 0;
3671 	txq->axq_aggr_depth = 0;
3672 	txq->axq_intrcnt = 0;
3673 	txq->axq_link = NULL;
3674 	txq->axq_softc = sc;
3675 	TAILQ_INIT(&txq->axq_q);
3676 	TAILQ_INIT(&txq->axq_tidq);
3677 }
3678 
3679 /*
3680  * Setup a h/w transmit queue.
3681  */
3682 static struct ath_txq *
3683 ath_txq_setup(struct ath_softc *sc, int qtype, int subtype)
3684 {
3685 #define	N(a)	(sizeof(a)/sizeof(a[0]))
3686 	struct ath_hal *ah = sc->sc_ah;
3687 	HAL_TXQ_INFO qi;
3688 	int qnum;
3689 
3690 	memset(&qi, 0, sizeof(qi));
3691 	qi.tqi_subtype = subtype;
3692 	qi.tqi_aifs = HAL_TXQ_USEDEFAULT;
3693 	qi.tqi_cwmin = HAL_TXQ_USEDEFAULT;
3694 	qi.tqi_cwmax = HAL_TXQ_USEDEFAULT;
3695 	/*
3696 	 * Enable interrupts only for EOL and DESC conditions.
3697 	 * We mark tx descriptors to receive a DESC interrupt
3698 	 * when a tx queue gets deep; otherwise waiting for the
3699 	 * EOL to reap descriptors.  Note that this is done to
3700 	 * reduce interrupt load and this only defers reaping
3701 	 * descriptors, never transmitting frames.  Aside from
3702 	 * reducing interrupts this also permits more concurrency.
3703 	 * The only potential downside is if the tx queue backs
3704 	 * up in which case the top half of the kernel may backup
3705 	 * due to a lack of tx descriptors.
3706 	 */
3707 	qi.tqi_qflags = HAL_TXQ_TXEOLINT_ENABLE | HAL_TXQ_TXDESCINT_ENABLE;
3708 	qnum = ath_hal_setuptxqueue(ah, qtype, &qi);
3709 	if (qnum == -1) {
3710 		/*
3711 		 * NB: don't print a message, this happens
3712 		 * normally on parts with too few tx queues
3713 		 */
3714 		return NULL;
3715 	}
3716 	if (qnum >= N(sc->sc_txq)) {
3717 		device_printf(sc->sc_dev,
3718 			"hal qnum %u out of range, max %zu!\n",
3719 			qnum, N(sc->sc_txq));
3720 		ath_hal_releasetxqueue(ah, qnum);
3721 		return NULL;
3722 	}
3723 	if (!ATH_TXQ_SETUP(sc, qnum)) {
3724 		ath_txq_init(sc, &sc->sc_txq[qnum], qnum);
3725 		sc->sc_txqsetup |= 1<<qnum;
3726 	}
3727 	return &sc->sc_txq[qnum];
3728 #undef N
3729 }
3730 
3731 /*
3732  * Setup a hardware data transmit queue for the specified
3733  * access control.  The hal may not support all requested
3734  * queues in which case it will return a reference to a
3735  * previously setup queue.  We record the mapping from ac's
3736  * to h/w queues for use by ath_tx_start and also track
3737  * the set of h/w queues being used to optimize work in the
3738  * transmit interrupt handler and related routines.
3739  */
3740 static int
3741 ath_tx_setup(struct ath_softc *sc, int ac, int haltype)
3742 {
3743 #define	N(a)	(sizeof(a)/sizeof(a[0]))
3744 	struct ath_txq *txq;
3745 
3746 	if (ac >= N(sc->sc_ac2q)) {
3747 		device_printf(sc->sc_dev, "AC %u out of range, max %zu!\n",
3748 			ac, N(sc->sc_ac2q));
3749 		return 0;
3750 	}
3751 	txq = ath_txq_setup(sc, HAL_TX_QUEUE_DATA, haltype);
3752 	if (txq != NULL) {
3753 		txq->axq_ac = ac;
3754 		sc->sc_ac2q[ac] = txq;
3755 		return 1;
3756 	} else
3757 		return 0;
3758 #undef N
3759 }
3760 
3761 /*
3762  * Update WME parameters for a transmit queue.
3763  */
3764 static int
3765 ath_txq_update(struct ath_softc *sc, int ac)
3766 {
3767 #define	ATH_EXPONENT_TO_VALUE(v)	((1<<v)-1)
3768 #define	ATH_TXOP_TO_US(v)		(v<<5)
3769 	struct ifnet *ifp = sc->sc_ifp;
3770 	struct ieee80211com *ic = ifp->if_l2com;
3771 	struct ath_txq *txq = sc->sc_ac2q[ac];
3772 	struct wmeParams *wmep = &ic->ic_wme.wme_chanParams.cap_wmeParams[ac];
3773 	struct ath_hal *ah = sc->sc_ah;
3774 	HAL_TXQ_INFO qi;
3775 
3776 	ath_hal_gettxqueueprops(ah, txq->axq_qnum, &qi);
3777 #ifdef IEEE80211_SUPPORT_TDMA
3778 	if (sc->sc_tdma) {
3779 		/*
3780 		 * AIFS is zero so there's no pre-transmit wait.  The
3781 		 * burst time defines the slot duration and is configured
3782 		 * through net80211.  The QCU is setup to not do post-xmit
3783 		 * back off, lockout all lower-priority QCU's, and fire
3784 		 * off the DMA beacon alert timer which is setup based
3785 		 * on the slot configuration.
3786 		 */
3787 		qi.tqi_qflags = HAL_TXQ_TXOKINT_ENABLE
3788 			      | HAL_TXQ_TXERRINT_ENABLE
3789 			      | HAL_TXQ_TXURNINT_ENABLE
3790 			      | HAL_TXQ_TXEOLINT_ENABLE
3791 			      | HAL_TXQ_DBA_GATED
3792 			      | HAL_TXQ_BACKOFF_DISABLE
3793 			      | HAL_TXQ_ARB_LOCKOUT_GLOBAL
3794 			      ;
3795 		qi.tqi_aifs = 0;
3796 		/* XXX +dbaprep? */
3797 		qi.tqi_readyTime = sc->sc_tdmaslotlen;
3798 		qi.tqi_burstTime = qi.tqi_readyTime;
3799 	} else {
3800 #endif
3801 		/*
3802 		 * XXX shouldn't this just use the default flags
3803 		 * used in the previous queue setup?
3804 		 */
3805 		qi.tqi_qflags = HAL_TXQ_TXOKINT_ENABLE
3806 			      | HAL_TXQ_TXERRINT_ENABLE
3807 			      | HAL_TXQ_TXDESCINT_ENABLE
3808 			      | HAL_TXQ_TXURNINT_ENABLE
3809 			      | HAL_TXQ_TXEOLINT_ENABLE
3810 			      ;
3811 		qi.tqi_aifs = wmep->wmep_aifsn;
3812 		qi.tqi_cwmin = ATH_EXPONENT_TO_VALUE(wmep->wmep_logcwmin);
3813 		qi.tqi_cwmax = ATH_EXPONENT_TO_VALUE(wmep->wmep_logcwmax);
3814 		qi.tqi_readyTime = 0;
3815 		qi.tqi_burstTime = ATH_TXOP_TO_US(wmep->wmep_txopLimit);
3816 #ifdef IEEE80211_SUPPORT_TDMA
3817 	}
3818 #endif
3819 
3820 	DPRINTF(sc, ATH_DEBUG_RESET,
3821 	    "%s: Q%u qflags 0x%x aifs %u cwmin %u cwmax %u burstTime %u\n",
3822 	    __func__, txq->axq_qnum, qi.tqi_qflags,
3823 	    qi.tqi_aifs, qi.tqi_cwmin, qi.tqi_cwmax, qi.tqi_burstTime);
3824 
3825 	if (!ath_hal_settxqueueprops(ah, txq->axq_qnum, &qi)) {
3826 		if_printf(ifp, "unable to update hardware queue "
3827 			"parameters for %s traffic!\n",
3828 			ieee80211_wme_acnames[ac]);
3829 		return 0;
3830 	} else {
3831 		ath_hal_resettxqueue(ah, txq->axq_qnum); /* push to h/w */
3832 		return 1;
3833 	}
3834 #undef ATH_TXOP_TO_US
3835 #undef ATH_EXPONENT_TO_VALUE
3836 }
3837 
3838 /*
3839  * Callback from the 802.11 layer to update WME parameters.
3840  */
3841 int
3842 ath_wme_update(struct ieee80211com *ic)
3843 {
3844 	struct ath_softc *sc = ic->ic_ifp->if_softc;
3845 
3846 	return !ath_txq_update(sc, WME_AC_BE) ||
3847 	    !ath_txq_update(sc, WME_AC_BK) ||
3848 	    !ath_txq_update(sc, WME_AC_VI) ||
3849 	    !ath_txq_update(sc, WME_AC_VO) ? EIO : 0;
3850 }
3851 
3852 /*
3853  * Reclaim resources for a setup queue.
3854  */
3855 static void
3856 ath_tx_cleanupq(struct ath_softc *sc, struct ath_txq *txq)
3857 {
3858 
3859 	ath_hal_releasetxqueue(sc->sc_ah, txq->axq_qnum);
3860 	sc->sc_txqsetup &= ~(1<<txq->axq_qnum);
3861 }
3862 
3863 /*
3864  * Reclaim all tx queue resources.
3865  */
3866 static void
3867 ath_tx_cleanup(struct ath_softc *sc)
3868 {
3869 	int i;
3870 
3871 	ATH_TXBUF_LOCK_DESTROY(sc);
3872 	for (i = 0; i < HAL_NUM_TX_QUEUES; i++)
3873 		if (ATH_TXQ_SETUP(sc, i))
3874 			ath_tx_cleanupq(sc, &sc->sc_txq[i]);
3875 }
3876 
3877 /*
3878  * Return h/w rate index for an IEEE rate (w/o basic rate bit)
3879  * using the current rates in sc_rixmap.
3880  */
3881 int
3882 ath_tx_findrix(const struct ath_softc *sc, uint8_t rate)
3883 {
3884 	int rix = sc->sc_rixmap[rate];
3885 	/* NB: return lowest rix for invalid rate */
3886 	return (rix == 0xff ? 0 : rix);
3887 }
3888 
3889 static void
3890 ath_tx_update_stats(struct ath_softc *sc, struct ath_tx_status *ts,
3891     struct ath_buf *bf)
3892 {
3893 	struct ieee80211_node *ni = bf->bf_node;
3894 	struct ifnet *ifp = sc->sc_ifp;
3895 	struct ieee80211com *ic = ifp->if_l2com;
3896 	int sr, lr, pri;
3897 
3898 	if (ts->ts_status == 0) {
3899 		u_int8_t txant = ts->ts_antenna;
3900 		sc->sc_stats.ast_ant_tx[txant]++;
3901 		sc->sc_ant_tx[txant]++;
3902 		if (ts->ts_finaltsi != 0)
3903 			sc->sc_stats.ast_tx_altrate++;
3904 		pri = M_WME_GETAC(bf->bf_m);
3905 		if (pri >= WME_AC_VO)
3906 			ic->ic_wme.wme_hipri_traffic++;
3907 		if ((bf->bf_state.bfs_txflags & HAL_TXDESC_NOACK) == 0)
3908 			ni->ni_inact = ni->ni_inact_reload;
3909 	} else {
3910 		if (ts->ts_status & HAL_TXERR_XRETRY)
3911 			sc->sc_stats.ast_tx_xretries++;
3912 		if (ts->ts_status & HAL_TXERR_FIFO)
3913 			sc->sc_stats.ast_tx_fifoerr++;
3914 		if (ts->ts_status & HAL_TXERR_FILT)
3915 			sc->sc_stats.ast_tx_filtered++;
3916 		if (ts->ts_status & HAL_TXERR_XTXOP)
3917 			sc->sc_stats.ast_tx_xtxop++;
3918 		if (ts->ts_status & HAL_TXERR_TIMER_EXPIRED)
3919 			sc->sc_stats.ast_tx_timerexpired++;
3920 
3921 		if (ts->ts_status & HAL_TX_DATA_UNDERRUN)
3922 			sc->sc_stats.ast_tx_data_underrun++;
3923 		if (ts->ts_status & HAL_TX_DELIM_UNDERRUN)
3924 			sc->sc_stats.ast_tx_delim_underrun++;
3925 
3926 		if (bf->bf_m->m_flags & M_FF)
3927 			sc->sc_stats.ast_ff_txerr++;
3928 	}
3929 	/* XXX when is this valid? */
3930 	if (ts->ts_status & HAL_TX_DESC_CFG_ERR)
3931 		sc->sc_stats.ast_tx_desccfgerr++;
3932 
3933 	sr = ts->ts_shortretry;
3934 	lr = ts->ts_longretry;
3935 	sc->sc_stats.ast_tx_shortretry += sr;
3936 	sc->sc_stats.ast_tx_longretry += lr;
3937 
3938 }
3939 
3940 /*
3941  * The default completion. If fail is 1, this means
3942  * "please don't retry the frame, and just return -1 status
3943  * to the net80211 stack.
3944  */
3945 void
3946 ath_tx_default_comp(struct ath_softc *sc, struct ath_buf *bf, int fail)
3947 {
3948 	struct ath_tx_status *ts = &bf->bf_status.ds_txstat;
3949 	int st;
3950 
3951 	if (fail == 1)
3952 		st = -1;
3953 	else
3954 		st = ((bf->bf_state.bfs_txflags & HAL_TXDESC_NOACK) == 0) ?
3955 		    ts->ts_status : HAL_TXERR_XRETRY;
3956 
3957 	if (bf->bf_state.bfs_dobaw)
3958 		device_printf(sc->sc_dev,
3959 		    "%s: bf %p: seqno %d: dobaw should've been cleared!\n",
3960 		    __func__,
3961 		    bf,
3962 		    SEQNO(bf->bf_state.bfs_seqno));
3963 	if (bf->bf_next != NULL)
3964 		device_printf(sc->sc_dev,
3965 		    "%s: bf %p: seqno %d: bf_next not NULL!\n",
3966 		    __func__,
3967 		    bf,
3968 		    SEQNO(bf->bf_state.bfs_seqno));
3969 
3970 	/*
3971 	 * Check if the node software queue is empty; if so
3972 	 * then clear the TIM.
3973 	 *
3974 	 * This needs to be done before the buffer is freed as
3975 	 * otherwise the node reference will have been released
3976 	 * and the node may not actually exist any longer.
3977 	 *
3978 	 * XXX I don't like this belonging here, but it's cleaner
3979 	 * to do it here right now then all the other places
3980 	 * where ath_tx_default_comp() is called.
3981 	 *
3982 	 * XXX TODO: during drain, ensure that the callback is
3983 	 * being called so we get a chance to update the TIM.
3984 	 */
3985 	if (bf->bf_node)
3986 		ath_tx_update_tim(sc, bf->bf_node, 0);
3987 
3988 	/*
3989 	 * Do any tx complete callback.  Note this must
3990 	 * be done before releasing the node reference.
3991 	 * This will free the mbuf, release the net80211
3992 	 * node and recycle the ath_buf.
3993 	 */
3994 	ath_tx_freebuf(sc, bf, st);
3995 }
3996 
3997 /*
3998  * Update rate control with the given completion status.
3999  */
4000 void
4001 ath_tx_update_ratectrl(struct ath_softc *sc, struct ieee80211_node *ni,
4002     struct ath_rc_series *rc, struct ath_tx_status *ts, int frmlen,
4003     int nframes, int nbad)
4004 {
4005 	struct ath_node *an;
4006 
4007 	/* Only for unicast frames */
4008 	if (ni == NULL)
4009 		return;
4010 
4011 	an = ATH_NODE(ni);
4012 	ATH_NODE_UNLOCK_ASSERT(an);
4013 
4014 	if ((ts->ts_status & HAL_TXERR_FILT) == 0) {
4015 		ATH_NODE_LOCK(an);
4016 		ath_rate_tx_complete(sc, an, rc, ts, frmlen, nframes, nbad);
4017 		ATH_NODE_UNLOCK(an);
4018 	}
4019 }
4020 
4021 /*
4022  * Update the busy status of the last frame on the free list.
4023  * When doing TDMA, the busy flag tracks whether the hardware
4024  * currently points to this buffer or not, and thus gated DMA
4025  * may restart by re-reading the last descriptor in this
4026  * buffer.
4027  *
4028  * This should be called in the completion function once one
4029  * of the buffers has been used.
4030  */
4031 static void
4032 ath_tx_update_busy(struct ath_softc *sc)
4033 {
4034 	struct ath_buf *last;
4035 
4036 	/*
4037 	 * Since the last frame may still be marked
4038 	 * as ATH_BUF_BUSY, unmark it here before
4039 	 * finishing the frame processing.
4040 	 * Since we've completed a frame (aggregate
4041 	 * or otherwise), the hardware has moved on
4042 	 * and is no longer referencing the previous
4043 	 * descriptor.
4044 	 */
4045 	ATH_TXBUF_LOCK_ASSERT(sc);
4046 	last = TAILQ_LAST(&sc->sc_txbuf_mgmt, ath_bufhead_s);
4047 	if (last != NULL)
4048 		last->bf_flags &= ~ATH_BUF_BUSY;
4049 	last = TAILQ_LAST(&sc->sc_txbuf, ath_bufhead_s);
4050 	if (last != NULL)
4051 		last->bf_flags &= ~ATH_BUF_BUSY;
4052 }
4053 
4054 /*
4055  * Process the completion of the given buffer.
4056  *
4057  * This calls the rate control update and then the buffer completion.
4058  * This will either free the buffer or requeue it.  In any case, the
4059  * bf pointer should be treated as invalid after this function is called.
4060  */
4061 void
4062 ath_tx_process_buf_completion(struct ath_softc *sc, struct ath_txq *txq,
4063     struct ath_tx_status *ts, struct ath_buf *bf)
4064 {
4065 	struct ieee80211_node *ni = bf->bf_node;
4066 	struct ath_node *an = NULL;
4067 
4068 	ATH_TX_UNLOCK_ASSERT(sc);
4069 
4070 	/* If unicast frame, update general statistics */
4071 	if (ni != NULL) {
4072 		an = ATH_NODE(ni);
4073 		/* update statistics */
4074 		ath_tx_update_stats(sc, ts, bf);
4075 	}
4076 
4077 	/*
4078 	 * Call the completion handler.
4079 	 * The completion handler is responsible for
4080 	 * calling the rate control code.
4081 	 *
4082 	 * Frames with no completion handler get the
4083 	 * rate control code called here.
4084 	 */
4085 	if (bf->bf_comp == NULL) {
4086 		if ((ts->ts_status & HAL_TXERR_FILT) == 0 &&
4087 		    (bf->bf_state.bfs_txflags & HAL_TXDESC_NOACK) == 0) {
4088 			/*
4089 			 * XXX assume this isn't an aggregate
4090 			 * frame.
4091 			 */
4092 			ath_tx_update_ratectrl(sc, ni,
4093 			     bf->bf_state.bfs_rc, ts,
4094 			    bf->bf_state.bfs_pktlen, 1,
4095 			    (ts->ts_status == 0 ? 0 : 1));
4096 		}
4097 		ath_tx_default_comp(sc, bf, 0);
4098 	} else
4099 		bf->bf_comp(sc, bf, 0);
4100 }
4101 
4102 
4103 
4104 /*
4105  * Process completed xmit descriptors from the specified queue.
4106  * Kick the packet scheduler if needed. This can occur from this
4107  * particular task.
4108  */
4109 static int
4110 ath_tx_processq(struct ath_softc *sc, struct ath_txq *txq, int dosched)
4111 {
4112 	struct ath_hal *ah = sc->sc_ah;
4113 	struct ath_buf *bf;
4114 	struct ath_desc *ds;
4115 	struct ath_tx_status *ts;
4116 	struct ieee80211_node *ni;
4117 #ifdef	IEEE80211_SUPPORT_SUPERG
4118 	struct ieee80211com *ic = sc->sc_ifp->if_l2com;
4119 #endif	/* IEEE80211_SUPPORT_SUPERG */
4120 	int nacked;
4121 	HAL_STATUS status;
4122 
4123 	DPRINTF(sc, ATH_DEBUG_TX_PROC, "%s: tx queue %u head %p link %p\n",
4124 		__func__, txq->axq_qnum,
4125 		(caddr_t)(uintptr_t) ath_hal_gettxbuf(sc->sc_ah, txq->axq_qnum),
4126 		txq->axq_link);
4127 
4128 	ATH_KTR(sc, ATH_KTR_TXCOMP, 4,
4129 	    "ath_tx_processq: txq=%u head %p link %p depth %p",
4130 	    txq->axq_qnum,
4131 	    (caddr_t)(uintptr_t) ath_hal_gettxbuf(sc->sc_ah, txq->axq_qnum),
4132 	    txq->axq_link,
4133 	    txq->axq_depth);
4134 
4135 	nacked = 0;
4136 	for (;;) {
4137 		ATH_TX_LOCK(sc);
4138 		txq->axq_intrcnt = 0;	/* reset periodic desc intr count */
4139 		bf = TAILQ_FIRST(&txq->axq_q);
4140 		if (bf == NULL) {
4141 			ATH_TX_UNLOCK(sc);
4142 			break;
4143 		}
4144 		ds = bf->bf_lastds;	/* XXX must be setup correctly! */
4145 		ts = &bf->bf_status.ds_txstat;
4146 
4147 		status = ath_hal_txprocdesc(ah, ds, ts);
4148 #ifdef ATH_DEBUG
4149 		if (sc->sc_debug & ATH_DEBUG_XMIT_DESC)
4150 			ath_printtxbuf(sc, bf, txq->axq_qnum, 0,
4151 			    status == HAL_OK);
4152 		else if ((sc->sc_debug & ATH_DEBUG_RESET) && (dosched == 0))
4153 			ath_printtxbuf(sc, bf, txq->axq_qnum, 0,
4154 			    status == HAL_OK);
4155 #endif
4156 #ifdef	ATH_DEBUG_ALQ
4157 		if (if_ath_alq_checkdebug(&sc->sc_alq,
4158 		    ATH_ALQ_EDMA_TXSTATUS)) {
4159 			if_ath_alq_post(&sc->sc_alq, ATH_ALQ_EDMA_TXSTATUS,
4160 			sc->sc_tx_statuslen,
4161 			(char *) ds);
4162 		}
4163 #endif
4164 
4165 		if (status == HAL_EINPROGRESS) {
4166 			ATH_KTR(sc, ATH_KTR_TXCOMP, 3,
4167 			    "ath_tx_processq: txq=%u, bf=%p ds=%p, HAL_EINPROGRESS",
4168 			    txq->axq_qnum, bf, ds);
4169 			ATH_TX_UNLOCK(sc);
4170 			break;
4171 		}
4172 		ATH_TXQ_REMOVE(txq, bf, bf_list);
4173 #ifdef IEEE80211_SUPPORT_TDMA
4174 		if (txq->axq_depth > 0) {
4175 			/*
4176 			 * More frames follow.  Mark the buffer busy
4177 			 * so it's not re-used while the hardware may
4178 			 * still re-read the link field in the descriptor.
4179 			 *
4180 			 * Use the last buffer in an aggregate as that
4181 			 * is where the hardware may be - intermediate
4182 			 * descriptors won't be "busy".
4183 			 */
4184 			bf->bf_last->bf_flags |= ATH_BUF_BUSY;
4185 		} else
4186 #else
4187 		if (txq->axq_depth == 0)
4188 #endif
4189 			txq->axq_link = NULL;
4190 		if (bf->bf_state.bfs_aggr)
4191 			txq->axq_aggr_depth--;
4192 
4193 		ni = bf->bf_node;
4194 
4195 		ATH_KTR(sc, ATH_KTR_TXCOMP, 5,
4196 		    "ath_tx_processq: txq=%u, bf=%p, ds=%p, ni=%p, ts_status=0x%08x",
4197 		    txq->axq_qnum, bf, ds, ni, ts->ts_status);
4198 		/*
4199 		 * If unicast frame was ack'd update RSSI,
4200 		 * including the last rx time used to
4201 		 * workaround phantom bmiss interrupts.
4202 		 */
4203 		if (ni != NULL && ts->ts_status == 0 &&
4204 		    ((bf->bf_state.bfs_txflags & HAL_TXDESC_NOACK) == 0)) {
4205 			nacked++;
4206 			sc->sc_stats.ast_tx_rssi = ts->ts_rssi;
4207 			ATH_RSSI_LPF(sc->sc_halstats.ns_avgtxrssi,
4208 				ts->ts_rssi);
4209 		}
4210 		ATH_TX_UNLOCK(sc);
4211 
4212 		/*
4213 		 * Update statistics and call completion
4214 		 */
4215 		ath_tx_process_buf_completion(sc, txq, ts, bf);
4216 
4217 		/* XXX at this point, bf and ni may be totally invalid */
4218 	}
4219 #ifdef IEEE80211_SUPPORT_SUPERG
4220 	/*
4221 	 * Flush fast-frame staging queue when traffic slows.
4222 	 */
4223 	if (txq->axq_depth <= 1)
4224 		ieee80211_ff_flush(ic, txq->axq_ac);
4225 #endif
4226 
4227 	/* Kick the software TXQ scheduler */
4228 	if (dosched) {
4229 		ATH_TX_LOCK(sc);
4230 		ath_txq_sched(sc, txq);
4231 		ATH_TX_UNLOCK(sc);
4232 	}
4233 
4234 	ATH_KTR(sc, ATH_KTR_TXCOMP, 1,
4235 	    "ath_tx_processq: txq=%u: done",
4236 	    txq->axq_qnum);
4237 
4238 	return nacked;
4239 }
4240 
4241 #define	TXQACTIVE(t, q)		( (t) & (1 << (q)))
4242 
4243 /*
4244  * Deferred processing of transmit interrupt; special-cased
4245  * for a single hardware transmit queue (e.g. 5210 and 5211).
4246  */
4247 static void
4248 ath_tx_proc_q0(void *arg, int npending)
4249 {
4250 	struct ath_softc *sc = arg;
4251 	struct ifnet *ifp = sc->sc_ifp;
4252 	uint32_t txqs;
4253 
4254 	ATH_PCU_LOCK(sc);
4255 	sc->sc_txproc_cnt++;
4256 	txqs = sc->sc_txq_active;
4257 	sc->sc_txq_active &= ~txqs;
4258 	ATH_PCU_UNLOCK(sc);
4259 
4260 	ATH_KTR(sc, ATH_KTR_TXCOMP, 1,
4261 	    "ath_tx_proc_q0: txqs=0x%08x", txqs);
4262 
4263 	if (TXQACTIVE(txqs, 0) && ath_tx_processq(sc, &sc->sc_txq[0], 1))
4264 		/* XXX why is lastrx updated in tx code? */
4265 		sc->sc_lastrx = ath_hal_gettsf64(sc->sc_ah);
4266 	if (TXQACTIVE(txqs, sc->sc_cabq->axq_qnum))
4267 		ath_tx_processq(sc, sc->sc_cabq, 1);
4268 	IF_LOCK(&ifp->if_snd);
4269 	ifp->if_drv_flags &= ~IFF_DRV_OACTIVE;
4270 	IF_UNLOCK(&ifp->if_snd);
4271 	sc->sc_wd_timer = 0;
4272 
4273 	if (sc->sc_softled)
4274 		ath_led_event(sc, sc->sc_txrix);
4275 
4276 	ath_txq_qrun(ifp);
4277 
4278 	ATH_PCU_LOCK(sc);
4279 	sc->sc_txproc_cnt--;
4280 	ATH_PCU_UNLOCK(sc);
4281 }
4282 
4283 /*
4284  * Deferred processing of transmit interrupt; special-cased
4285  * for four hardware queues, 0-3 (e.g. 5212 w/ WME support).
4286  */
4287 static void
4288 ath_tx_proc_q0123(void *arg, int npending)
4289 {
4290 	struct ath_softc *sc = arg;
4291 	struct ifnet *ifp = sc->sc_ifp;
4292 	int nacked;
4293 	uint32_t txqs;
4294 
4295 	ATH_PCU_LOCK(sc);
4296 	sc->sc_txproc_cnt++;
4297 	txqs = sc->sc_txq_active;
4298 	sc->sc_txq_active &= ~txqs;
4299 	ATH_PCU_UNLOCK(sc);
4300 
4301 	ATH_KTR(sc, ATH_KTR_TXCOMP, 1,
4302 	    "ath_tx_proc_q0123: txqs=0x%08x", txqs);
4303 
4304 	/*
4305 	 * Process each active queue.
4306 	 */
4307 	nacked = 0;
4308 	if (TXQACTIVE(txqs, 0))
4309 		nacked += ath_tx_processq(sc, &sc->sc_txq[0], 1);
4310 	if (TXQACTIVE(txqs, 1))
4311 		nacked += ath_tx_processq(sc, &sc->sc_txq[1], 1);
4312 	if (TXQACTIVE(txqs, 2))
4313 		nacked += ath_tx_processq(sc, &sc->sc_txq[2], 1);
4314 	if (TXQACTIVE(txqs, 3))
4315 		nacked += ath_tx_processq(sc, &sc->sc_txq[3], 1);
4316 	if (TXQACTIVE(txqs, sc->sc_cabq->axq_qnum))
4317 		ath_tx_processq(sc, sc->sc_cabq, 1);
4318 	if (nacked)
4319 		sc->sc_lastrx = ath_hal_gettsf64(sc->sc_ah);
4320 
4321 	IF_LOCK(&ifp->if_snd);
4322 	ifp->if_drv_flags &= ~IFF_DRV_OACTIVE;
4323 	IF_UNLOCK(&ifp->if_snd);
4324 	sc->sc_wd_timer = 0;
4325 
4326 	if (sc->sc_softled)
4327 		ath_led_event(sc, sc->sc_txrix);
4328 
4329 	ath_txq_qrun(ifp);
4330 
4331 	ATH_PCU_LOCK(sc);
4332 	sc->sc_txproc_cnt--;
4333 	ATH_PCU_UNLOCK(sc);
4334 }
4335 
4336 /*
4337  * Deferred processing of transmit interrupt.
4338  */
4339 static void
4340 ath_tx_proc(void *arg, int npending)
4341 {
4342 	struct ath_softc *sc = arg;
4343 	struct ifnet *ifp = sc->sc_ifp;
4344 	int i, nacked;
4345 	uint32_t txqs;
4346 
4347 	ATH_PCU_LOCK(sc);
4348 	sc->sc_txproc_cnt++;
4349 	txqs = sc->sc_txq_active;
4350 	sc->sc_txq_active &= ~txqs;
4351 	ATH_PCU_UNLOCK(sc);
4352 
4353 	ATH_KTR(sc, ATH_KTR_TXCOMP, 1, "ath_tx_proc: txqs=0x%08x", txqs);
4354 
4355 	/*
4356 	 * Process each active queue.
4357 	 */
4358 	nacked = 0;
4359 	for (i = 0; i < HAL_NUM_TX_QUEUES; i++)
4360 		if (ATH_TXQ_SETUP(sc, i) && TXQACTIVE(txqs, i))
4361 			nacked += ath_tx_processq(sc, &sc->sc_txq[i], 1);
4362 	if (nacked)
4363 		sc->sc_lastrx = ath_hal_gettsf64(sc->sc_ah);
4364 
4365 	/* XXX check this inside of IF_LOCK? */
4366 	IF_LOCK(&ifp->if_snd);
4367 	ifp->if_drv_flags &= ~IFF_DRV_OACTIVE;
4368 	IF_UNLOCK(&ifp->if_snd);
4369 	sc->sc_wd_timer = 0;
4370 
4371 	if (sc->sc_softled)
4372 		ath_led_event(sc, sc->sc_txrix);
4373 
4374 	ath_txq_qrun(ifp);
4375 
4376 	ATH_PCU_LOCK(sc);
4377 	sc->sc_txproc_cnt--;
4378 	ATH_PCU_UNLOCK(sc);
4379 }
4380 #undef	TXQACTIVE
4381 
4382 /*
4383  * Deferred processing of TXQ rescheduling.
4384  */
4385 static void
4386 ath_txq_sched_tasklet(void *arg, int npending)
4387 {
4388 	struct ath_softc *sc = arg;
4389 	int i;
4390 
4391 	/* XXX is skipping ok? */
4392 	ATH_PCU_LOCK(sc);
4393 #if 0
4394 	if (sc->sc_inreset_cnt > 0) {
4395 		device_printf(sc->sc_dev,
4396 		    "%s: sc_inreset_cnt > 0; skipping\n", __func__);
4397 		ATH_PCU_UNLOCK(sc);
4398 		return;
4399 	}
4400 #endif
4401 	sc->sc_txproc_cnt++;
4402 	ATH_PCU_UNLOCK(sc);
4403 
4404 	ATH_TX_LOCK(sc);
4405 	for (i = 0; i < HAL_NUM_TX_QUEUES; i++) {
4406 		if (ATH_TXQ_SETUP(sc, i)) {
4407 			ath_txq_sched(sc, &sc->sc_txq[i]);
4408 		}
4409 	}
4410 	ATH_TX_UNLOCK(sc);
4411 
4412 	ATH_PCU_LOCK(sc);
4413 	sc->sc_txproc_cnt--;
4414 	ATH_PCU_UNLOCK(sc);
4415 }
4416 
4417 void
4418 ath_returnbuf_tail(struct ath_softc *sc, struct ath_buf *bf)
4419 {
4420 
4421 	ATH_TXBUF_LOCK_ASSERT(sc);
4422 
4423 	if (bf->bf_flags & ATH_BUF_MGMT)
4424 		TAILQ_INSERT_TAIL(&sc->sc_txbuf_mgmt, bf, bf_list);
4425 	else {
4426 		TAILQ_INSERT_TAIL(&sc->sc_txbuf, bf, bf_list);
4427 		sc->sc_txbuf_cnt++;
4428 		if (sc->sc_txbuf_cnt > ath_txbuf) {
4429 			device_printf(sc->sc_dev,
4430 			    "%s: sc_txbuf_cnt > %d?\n",
4431 			    __func__,
4432 			    ath_txbuf);
4433 			sc->sc_txbuf_cnt = ath_txbuf;
4434 		}
4435 	}
4436 }
4437 
4438 void
4439 ath_returnbuf_head(struct ath_softc *sc, struct ath_buf *bf)
4440 {
4441 
4442 	ATH_TXBUF_LOCK_ASSERT(sc);
4443 
4444 	if (bf->bf_flags & ATH_BUF_MGMT)
4445 		TAILQ_INSERT_HEAD(&sc->sc_txbuf_mgmt, bf, bf_list);
4446 	else {
4447 		TAILQ_INSERT_HEAD(&sc->sc_txbuf, bf, bf_list);
4448 		sc->sc_txbuf_cnt++;
4449 		if (sc->sc_txbuf_cnt > ATH_TXBUF) {
4450 			device_printf(sc->sc_dev,
4451 			    "%s: sc_txbuf_cnt > %d?\n",
4452 			    __func__,
4453 			    ATH_TXBUF);
4454 			sc->sc_txbuf_cnt = ATH_TXBUF;
4455 		}
4456 	}
4457 }
4458 
4459 /*
4460  * Return a buffer to the pool and update the 'busy' flag on the
4461  * previous 'tail' entry.
4462  *
4463  * This _must_ only be called when the buffer is involved in a completed
4464  * TX. The logic is that if it was part of an active TX, the previous
4465  * buffer on the list is now not involved in a halted TX DMA queue, waiting
4466  * for restart (eg for TDMA.)
4467  *
4468  * The caller must free the mbuf and recycle the node reference.
4469  */
4470 void
4471 ath_freebuf(struct ath_softc *sc, struct ath_buf *bf)
4472 {
4473 	bus_dmamap_unload(sc->sc_dmat, bf->bf_dmamap);
4474 	bus_dmamap_sync(sc->sc_dmat, bf->bf_dmamap, BUS_DMASYNC_POSTWRITE);
4475 
4476 	KASSERT((bf->bf_node == NULL), ("%s: bf->bf_node != NULL\n", __func__));
4477 	KASSERT((bf->bf_m == NULL), ("%s: bf->bf_m != NULL\n", __func__));
4478 
4479 	ATH_TXBUF_LOCK(sc);
4480 	ath_tx_update_busy(sc);
4481 	ath_returnbuf_tail(sc, bf);
4482 	ATH_TXBUF_UNLOCK(sc);
4483 }
4484 
4485 /*
4486  * This is currently used by ath_tx_draintxq() and
4487  * ath_tx_tid_free_pkts().
4488  *
4489  * It recycles a single ath_buf.
4490  */
4491 void
4492 ath_tx_freebuf(struct ath_softc *sc, struct ath_buf *bf, int status)
4493 {
4494 	struct ieee80211_node *ni = bf->bf_node;
4495 	struct mbuf *m0 = bf->bf_m;
4496 
4497 	bf->bf_node = NULL;
4498 	bf->bf_m = NULL;
4499 
4500 	/* Free the buffer, it's not needed any longer */
4501 	ath_freebuf(sc, bf);
4502 
4503 	if (ni != NULL) {
4504 		/*
4505 		 * Do any callback and reclaim the node reference.
4506 		 */
4507 		if (m0->m_flags & M_TXCB)
4508 			ieee80211_process_callback(ni, m0, status);
4509 		ieee80211_free_node(ni);
4510 	}
4511 	m_freem(m0);
4512 
4513 	/*
4514 	 * XXX the buffer used to be freed -after-, but the DMA map was
4515 	 * freed where ath_freebuf() now is. I've no idea what this
4516 	 * will do.
4517 	 */
4518 }
4519 
4520 void
4521 ath_tx_draintxq(struct ath_softc *sc, struct ath_txq *txq)
4522 {
4523 #ifdef ATH_DEBUG
4524 	struct ath_hal *ah = sc->sc_ah;
4525 #endif
4526 	struct ath_buf *bf;
4527 	u_int ix;
4528 
4529 	/*
4530 	 * NB: this assumes output has been stopped and
4531 	 *     we do not need to block ath_tx_proc
4532 	 */
4533 	ATH_TXBUF_LOCK(sc);
4534 	bf = TAILQ_LAST(&sc->sc_txbuf, ath_bufhead_s);
4535 	if (bf != NULL)
4536 		bf->bf_flags &= ~ATH_BUF_BUSY;
4537 	bf = TAILQ_LAST(&sc->sc_txbuf_mgmt, ath_bufhead_s);
4538 	if (bf != NULL)
4539 		bf->bf_flags &= ~ATH_BUF_BUSY;
4540 	ATH_TXBUF_UNLOCK(sc);
4541 
4542 	for (ix = 0;; ix++) {
4543 		ATH_TX_LOCK(sc);
4544 		bf = TAILQ_FIRST(&txq->axq_q);
4545 		if (bf == NULL) {
4546 			txq->axq_link = NULL;
4547 			/*
4548 			 * There's currently no flag that indicates
4549 			 * a buffer is on the FIFO.  So until that
4550 			 * occurs, just clear the FIFO counter here.
4551 			 *
4552 			 * Yes, this means that if something in parallel
4553 			 * is pushing things onto this TXQ and pushing
4554 			 * _that_ into the hardware, things will get
4555 			 * very fruity very quickly.
4556 			 */
4557 			txq->axq_fifo_depth = 0;
4558 			ATH_TX_UNLOCK(sc);
4559 			break;
4560 		}
4561 		ATH_TXQ_REMOVE(txq, bf, bf_list);
4562 		if (bf->bf_state.bfs_aggr)
4563 			txq->axq_aggr_depth--;
4564 #ifdef ATH_DEBUG
4565 		if (sc->sc_debug & ATH_DEBUG_RESET) {
4566 			struct ieee80211com *ic = sc->sc_ifp->if_l2com;
4567 			int status = 0;
4568 
4569 			/*
4570 			 * EDMA operation has a TX completion FIFO
4571 			 * separate from the TX descriptor, so this
4572 			 * method of checking the "completion" status
4573 			 * is wrong.
4574 			 */
4575 			if (! sc->sc_isedma) {
4576 				status = (ath_hal_txprocdesc(ah,
4577 				    bf->bf_lastds,
4578 				    &bf->bf_status.ds_txstat) == HAL_OK);
4579 			}
4580 			ath_printtxbuf(sc, bf, txq->axq_qnum, ix, status);
4581 			ieee80211_dump_pkt(ic, mtod(bf->bf_m, const uint8_t *),
4582 			    bf->bf_m->m_len, 0, -1);
4583 		}
4584 #endif /* ATH_DEBUG */
4585 		/*
4586 		 * Since we're now doing magic in the completion
4587 		 * functions, we -must- call it for aggregation
4588 		 * destinations or BAW tracking will get upset.
4589 		 */
4590 		/*
4591 		 * Clear ATH_BUF_BUSY; the completion handler
4592 		 * will free the buffer.
4593 		 */
4594 		ATH_TX_UNLOCK(sc);
4595 		bf->bf_flags &= ~ATH_BUF_BUSY;
4596 		if (bf->bf_comp)
4597 			bf->bf_comp(sc, bf, 1);
4598 		else
4599 			ath_tx_default_comp(sc, bf, 1);
4600 	}
4601 
4602 	/*
4603 	 * Drain software queued frames which are on
4604 	 * active TIDs.
4605 	 */
4606 	ath_tx_txq_drain(sc, txq);
4607 }
4608 
4609 static void
4610 ath_tx_stopdma(struct ath_softc *sc, struct ath_txq *txq)
4611 {
4612 	struct ath_hal *ah = sc->sc_ah;
4613 
4614 	DPRINTF(sc, ATH_DEBUG_RESET, "%s: tx queue [%u] %p, link %p\n",
4615 	    __func__, txq->axq_qnum,
4616 	    (caddr_t)(uintptr_t) ath_hal_gettxbuf(ah, txq->axq_qnum),
4617 	    txq->axq_link);
4618 	(void) ath_hal_stoptxdma(ah, txq->axq_qnum);
4619 }
4620 
4621 int
4622 ath_stoptxdma(struct ath_softc *sc)
4623 {
4624 	struct ath_hal *ah = sc->sc_ah;
4625 	int i;
4626 
4627 	/* XXX return value */
4628 	if (sc->sc_invalid)
4629 		return 0;
4630 
4631 	if (!sc->sc_invalid) {
4632 		/* don't touch the hardware if marked invalid */
4633 		DPRINTF(sc, ATH_DEBUG_RESET, "%s: tx queue [%u] %p, link %p\n",
4634 		    __func__, sc->sc_bhalq,
4635 		    (caddr_t)(uintptr_t) ath_hal_gettxbuf(ah, sc->sc_bhalq),
4636 		    NULL);
4637 		(void) ath_hal_stoptxdma(ah, sc->sc_bhalq);
4638 		for (i = 0; i < HAL_NUM_TX_QUEUES; i++)
4639 			if (ATH_TXQ_SETUP(sc, i))
4640 				ath_tx_stopdma(sc, &sc->sc_txq[i]);
4641 	}
4642 
4643 	return 1;
4644 }
4645 
4646 /*
4647  * Drain the transmit queues and reclaim resources.
4648  */
4649 void
4650 ath_legacy_tx_drain(struct ath_softc *sc, ATH_RESET_TYPE reset_type)
4651 {
4652 #ifdef	ATH_DEBUG
4653 	struct ath_hal *ah = sc->sc_ah;
4654 #endif
4655 	struct ifnet *ifp = sc->sc_ifp;
4656 	int i;
4657 
4658 	(void) ath_stoptxdma(sc);
4659 
4660 	for (i = 0; i < HAL_NUM_TX_QUEUES; i++) {
4661 		/*
4662 		 * XXX TODO: should we just handle the completed TX frames
4663 		 * here, whether or not the reset is a full one or not?
4664 		 */
4665 		if (ATH_TXQ_SETUP(sc, i)) {
4666 			if (reset_type == ATH_RESET_NOLOSS)
4667 				ath_tx_processq(sc, &sc->sc_txq[i], 0);
4668 			else
4669 				ath_tx_draintxq(sc, &sc->sc_txq[i]);
4670 		}
4671 	}
4672 #ifdef ATH_DEBUG
4673 	if (sc->sc_debug & ATH_DEBUG_RESET) {
4674 		struct ath_buf *bf = TAILQ_FIRST(&sc->sc_bbuf);
4675 		if (bf != NULL && bf->bf_m != NULL) {
4676 			ath_printtxbuf(sc, bf, sc->sc_bhalq, 0,
4677 				ath_hal_txprocdesc(ah, bf->bf_lastds,
4678 				    &bf->bf_status.ds_txstat) == HAL_OK);
4679 			ieee80211_dump_pkt(ifp->if_l2com,
4680 			    mtod(bf->bf_m, const uint8_t *), bf->bf_m->m_len,
4681 			    0, -1);
4682 		}
4683 	}
4684 #endif /* ATH_DEBUG */
4685 	IF_LOCK(&ifp->if_snd);
4686 	ifp->if_drv_flags &= ~IFF_DRV_OACTIVE;
4687 	IF_UNLOCK(&ifp->if_snd);
4688 	sc->sc_wd_timer = 0;
4689 }
4690 
4691 /*
4692  * Update internal state after a channel change.
4693  */
4694 static void
4695 ath_chan_change(struct ath_softc *sc, struct ieee80211_channel *chan)
4696 {
4697 	enum ieee80211_phymode mode;
4698 
4699 	/*
4700 	 * Change channels and update the h/w rate map
4701 	 * if we're switching; e.g. 11a to 11b/g.
4702 	 */
4703 	mode = ieee80211_chan2mode(chan);
4704 	if (mode != sc->sc_curmode)
4705 		ath_setcurmode(sc, mode);
4706 	sc->sc_curchan = chan;
4707 }
4708 
4709 /*
4710  * Set/change channels.  If the channel is really being changed,
4711  * it's done by resetting the chip.  To accomplish this we must
4712  * first cleanup any pending DMA, then restart stuff after a la
4713  * ath_init.
4714  */
4715 static int
4716 ath_chan_set(struct ath_softc *sc, struct ieee80211_channel *chan)
4717 {
4718 	struct ifnet *ifp = sc->sc_ifp;
4719 	struct ieee80211com *ic = ifp->if_l2com;
4720 	struct ath_hal *ah = sc->sc_ah;
4721 	int ret = 0;
4722 
4723 	/* Treat this as an interface reset */
4724 	ATH_PCU_UNLOCK_ASSERT(sc);
4725 	ATH_UNLOCK_ASSERT(sc);
4726 
4727 	/* (Try to) stop TX/RX from occuring */
4728 	taskqueue_block(sc->sc_tq);
4729 	taskqueue_block(sc->sc_tx_tq);
4730 
4731 	ATH_PCU_LOCK(sc);
4732 	ath_hal_intrset(ah, 0);		/* Stop new RX/TX completion */
4733 	ath_txrx_stop_locked(sc);	/* Stop pending RX/TX completion */
4734 	if (ath_reset_grablock(sc, 1) == 0) {
4735 		device_printf(sc->sc_dev, "%s: concurrent reset! Danger!\n",
4736 		    __func__);
4737 	}
4738 	ATH_PCU_UNLOCK(sc);
4739 
4740 	DPRINTF(sc, ATH_DEBUG_RESET, "%s: %u (%u MHz, flags 0x%x)\n",
4741 	    __func__, ieee80211_chan2ieee(ic, chan),
4742 	    chan->ic_freq, chan->ic_flags);
4743 	if (chan != sc->sc_curchan) {
4744 		HAL_STATUS status;
4745 		/*
4746 		 * To switch channels clear any pending DMA operations;
4747 		 * wait long enough for the RX fifo to drain, reset the
4748 		 * hardware at the new frequency, and then re-enable
4749 		 * the relevant bits of the h/w.
4750 		 */
4751 #if 0
4752 		ath_hal_intrset(ah, 0);		/* disable interrupts */
4753 #endif
4754 		ath_stoprecv(sc, 1);		/* turn off frame recv */
4755 		/*
4756 		 * First, handle completed TX/RX frames.
4757 		 */
4758 		ath_rx_flush(sc);
4759 		ath_draintxq(sc, ATH_RESET_NOLOSS);
4760 		/*
4761 		 * Next, flush the non-scheduled frames.
4762 		 */
4763 		ath_draintxq(sc, ATH_RESET_FULL);	/* clear pending tx frames */
4764 
4765 		if (!ath_hal_reset(ah, sc->sc_opmode, chan, AH_TRUE, &status)) {
4766 			if_printf(ifp, "%s: unable to reset "
4767 			    "channel %u (%u MHz, flags 0x%x), hal status %u\n",
4768 			    __func__, ieee80211_chan2ieee(ic, chan),
4769 			    chan->ic_freq, chan->ic_flags, status);
4770 			ret = EIO;
4771 			goto finish;
4772 		}
4773 		sc->sc_diversity = ath_hal_getdiversity(ah);
4774 
4775 		/* Let DFS at it in case it's a DFS channel */
4776 		ath_dfs_radar_enable(sc, chan);
4777 
4778 		/* Let spectral at in case spectral is enabled */
4779 		ath_spectral_enable(sc, chan);
4780 
4781 		/*
4782 		 * Re-enable rx framework.
4783 		 */
4784 		if (ath_startrecv(sc) != 0) {
4785 			if_printf(ifp, "%s: unable to restart recv logic\n",
4786 			    __func__);
4787 			ret = EIO;
4788 			goto finish;
4789 		}
4790 
4791 		/*
4792 		 * Change channels and update the h/w rate map
4793 		 * if we're switching; e.g. 11a to 11b/g.
4794 		 */
4795 		ath_chan_change(sc, chan);
4796 
4797 		/*
4798 		 * Reset clears the beacon timers; reset them
4799 		 * here if needed.
4800 		 */
4801 		if (sc->sc_beacons) {		/* restart beacons */
4802 #ifdef IEEE80211_SUPPORT_TDMA
4803 			if (sc->sc_tdma)
4804 				ath_tdma_config(sc, NULL);
4805 			else
4806 #endif
4807 			ath_beacon_config(sc, NULL);
4808 		}
4809 
4810 		/*
4811 		 * Re-enable interrupts.
4812 		 */
4813 #if 0
4814 		ath_hal_intrset(ah, sc->sc_imask);
4815 #endif
4816 	}
4817 
4818 finish:
4819 	ATH_PCU_LOCK(sc);
4820 	sc->sc_inreset_cnt--;
4821 	/* XXX only do this if sc_inreset_cnt == 0? */
4822 	ath_hal_intrset(ah, sc->sc_imask);
4823 	ATH_PCU_UNLOCK(sc);
4824 
4825 	IF_LOCK(&ifp->if_snd);
4826 	ifp->if_drv_flags &= ~IFF_DRV_OACTIVE;
4827 	IF_UNLOCK(&ifp->if_snd);
4828 	ath_txrx_start(sc);
4829 	/* XXX ath_start? */
4830 
4831 	return ret;
4832 }
4833 
4834 /*
4835  * Periodically recalibrate the PHY to account
4836  * for temperature/environment changes.
4837  */
4838 static void
4839 ath_calibrate(void *arg)
4840 {
4841 	struct ath_softc *sc = arg;
4842 	struct ath_hal *ah = sc->sc_ah;
4843 	struct ifnet *ifp = sc->sc_ifp;
4844 	struct ieee80211com *ic = ifp->if_l2com;
4845 	HAL_BOOL longCal, isCalDone = AH_TRUE;
4846 	HAL_BOOL aniCal, shortCal = AH_FALSE;
4847 	int nextcal;
4848 
4849 	if (ic->ic_flags & IEEE80211_F_SCAN)	/* defer, off channel */
4850 		goto restart;
4851 	longCal = (ticks - sc->sc_lastlongcal >= ath_longcalinterval*hz);
4852 	aniCal = (ticks - sc->sc_lastani >= ath_anicalinterval*hz/1000);
4853 	if (sc->sc_doresetcal)
4854 		shortCal = (ticks - sc->sc_lastshortcal >= ath_shortcalinterval*hz/1000);
4855 
4856 	DPRINTF(sc, ATH_DEBUG_CALIBRATE, "%s: shortCal=%d; longCal=%d; aniCal=%d\n", __func__, shortCal, longCal, aniCal);
4857 	if (aniCal) {
4858 		sc->sc_stats.ast_ani_cal++;
4859 		sc->sc_lastani = ticks;
4860 		ath_hal_ani_poll(ah, sc->sc_curchan);
4861 	}
4862 
4863 	if (longCal) {
4864 		sc->sc_stats.ast_per_cal++;
4865 		sc->sc_lastlongcal = ticks;
4866 		if (ath_hal_getrfgain(ah) == HAL_RFGAIN_NEED_CHANGE) {
4867 			/*
4868 			 * Rfgain is out of bounds, reset the chip
4869 			 * to load new gain values.
4870 			 */
4871 			DPRINTF(sc, ATH_DEBUG_CALIBRATE,
4872 				"%s: rfgain change\n", __func__);
4873 			sc->sc_stats.ast_per_rfgain++;
4874 			sc->sc_resetcal = 0;
4875 			sc->sc_doresetcal = AH_TRUE;
4876 			taskqueue_enqueue(sc->sc_tq, &sc->sc_resettask);
4877 			callout_reset(&sc->sc_cal_ch, 1, ath_calibrate, sc);
4878 			return;
4879 		}
4880 		/*
4881 		 * If this long cal is after an idle period, then
4882 		 * reset the data collection state so we start fresh.
4883 		 */
4884 		if (sc->sc_resetcal) {
4885 			(void) ath_hal_calreset(ah, sc->sc_curchan);
4886 			sc->sc_lastcalreset = ticks;
4887 			sc->sc_lastshortcal = ticks;
4888 			sc->sc_resetcal = 0;
4889 			sc->sc_doresetcal = AH_TRUE;
4890 		}
4891 	}
4892 
4893 	/* Only call if we're doing a short/long cal, not for ANI calibration */
4894 	if (shortCal || longCal) {
4895 		isCalDone = AH_FALSE;
4896 		if (ath_hal_calibrateN(ah, sc->sc_curchan, longCal, &isCalDone)) {
4897 			if (longCal) {
4898 				/*
4899 				 * Calibrate noise floor data again in case of change.
4900 				 */
4901 				ath_hal_process_noisefloor(ah);
4902 			}
4903 		} else {
4904 			DPRINTF(sc, ATH_DEBUG_ANY,
4905 				"%s: calibration of channel %u failed\n",
4906 				__func__, sc->sc_curchan->ic_freq);
4907 			sc->sc_stats.ast_per_calfail++;
4908 		}
4909 		if (shortCal)
4910 			sc->sc_lastshortcal = ticks;
4911 	}
4912 	if (!isCalDone) {
4913 restart:
4914 		/*
4915 		 * Use a shorter interval to potentially collect multiple
4916 		 * data samples required to complete calibration.  Once
4917 		 * we're told the work is done we drop back to a longer
4918 		 * interval between requests.  We're more aggressive doing
4919 		 * work when operating as an AP to improve operation right
4920 		 * after startup.
4921 		 */
4922 		sc->sc_lastshortcal = ticks;
4923 		nextcal = ath_shortcalinterval*hz/1000;
4924 		if (sc->sc_opmode != HAL_M_HOSTAP)
4925 			nextcal *= 10;
4926 		sc->sc_doresetcal = AH_TRUE;
4927 	} else {
4928 		/* nextcal should be the shortest time for next event */
4929 		nextcal = ath_longcalinterval*hz;
4930 		if (sc->sc_lastcalreset == 0)
4931 			sc->sc_lastcalreset = sc->sc_lastlongcal;
4932 		else if (ticks - sc->sc_lastcalreset >= ath_resetcalinterval*hz)
4933 			sc->sc_resetcal = 1;	/* setup reset next trip */
4934 		sc->sc_doresetcal = AH_FALSE;
4935 	}
4936 	/* ANI calibration may occur more often than short/long/resetcal */
4937 	if (ath_anicalinterval > 0)
4938 		nextcal = MIN(nextcal, ath_anicalinterval*hz/1000);
4939 
4940 	if (nextcal != 0) {
4941 		DPRINTF(sc, ATH_DEBUG_CALIBRATE, "%s: next +%u (%sisCalDone)\n",
4942 		    __func__, nextcal, isCalDone ? "" : "!");
4943 		callout_reset(&sc->sc_cal_ch, nextcal, ath_calibrate, sc);
4944 	} else {
4945 		DPRINTF(sc, ATH_DEBUG_CALIBRATE, "%s: calibration disabled\n",
4946 		    __func__);
4947 		/* NB: don't rearm timer */
4948 	}
4949 }
4950 
4951 static void
4952 ath_scan_start(struct ieee80211com *ic)
4953 {
4954 	struct ifnet *ifp = ic->ic_ifp;
4955 	struct ath_softc *sc = ifp->if_softc;
4956 	struct ath_hal *ah = sc->sc_ah;
4957 	u_int32_t rfilt;
4958 
4959 	/* XXX calibration timer? */
4960 
4961 	ATH_LOCK(sc);
4962 	sc->sc_scanning = 1;
4963 	sc->sc_syncbeacon = 0;
4964 	rfilt = ath_calcrxfilter(sc);
4965 	ATH_UNLOCK(sc);
4966 
4967 	ATH_PCU_LOCK(sc);
4968 	ath_hal_setrxfilter(ah, rfilt);
4969 	ath_hal_setassocid(ah, ifp->if_broadcastaddr, 0);
4970 	ATH_PCU_UNLOCK(sc);
4971 
4972 	DPRINTF(sc, ATH_DEBUG_STATE, "%s: RX filter 0x%x bssid %s aid 0\n",
4973 		 __func__, rfilt, ether_sprintf(ifp->if_broadcastaddr));
4974 }
4975 
4976 static void
4977 ath_scan_end(struct ieee80211com *ic)
4978 {
4979 	struct ifnet *ifp = ic->ic_ifp;
4980 	struct ath_softc *sc = ifp->if_softc;
4981 	struct ath_hal *ah = sc->sc_ah;
4982 	u_int32_t rfilt;
4983 
4984 	ATH_LOCK(sc);
4985 	sc->sc_scanning = 0;
4986 	rfilt = ath_calcrxfilter(sc);
4987 	ATH_UNLOCK(sc);
4988 
4989 	ATH_PCU_LOCK(sc);
4990 	ath_hal_setrxfilter(ah, rfilt);
4991 	ath_hal_setassocid(ah, sc->sc_curbssid, sc->sc_curaid);
4992 
4993 	ath_hal_process_noisefloor(ah);
4994 	ATH_PCU_UNLOCK(sc);
4995 
4996 	DPRINTF(sc, ATH_DEBUG_STATE, "%s: RX filter 0x%x bssid %s aid 0x%x\n",
4997 		 __func__, rfilt, ether_sprintf(sc->sc_curbssid),
4998 		 sc->sc_curaid);
4999 }
5000 
5001 #ifdef	ATH_ENABLE_11N
5002 /*
5003  * For now, just do a channel change.
5004  *
5005  * Later, we'll go through the hard slog of suspending tx/rx, changing rate
5006  * control state and resetting the hardware without dropping frames out
5007  * of the queue.
5008  *
5009  * The unfortunate trouble here is making absolutely sure that the
5010  * channel width change has propagated enough so the hardware
5011  * absolutely isn't handed bogus frames for it's current operating
5012  * mode. (Eg, 40MHz frames in 20MHz mode.) Since TX and RX can and
5013  * does occur in parallel, we need to make certain we've blocked
5014  * any further ongoing TX (and RX, that can cause raw TX)
5015  * before we do this.
5016  */
5017 static void
5018 ath_update_chw(struct ieee80211com *ic)
5019 {
5020 	struct ifnet *ifp = ic->ic_ifp;
5021 	struct ath_softc *sc = ifp->if_softc;
5022 
5023 	DPRINTF(sc, ATH_DEBUG_STATE, "%s: called\n", __func__);
5024 	ath_set_channel(ic);
5025 }
5026 #endif	/* ATH_ENABLE_11N */
5027 
5028 static void
5029 ath_set_channel(struct ieee80211com *ic)
5030 {
5031 	struct ifnet *ifp = ic->ic_ifp;
5032 	struct ath_softc *sc = ifp->if_softc;
5033 
5034 	(void) ath_chan_set(sc, ic->ic_curchan);
5035 	/*
5036 	 * If we are returning to our bss channel then mark state
5037 	 * so the next recv'd beacon's tsf will be used to sync the
5038 	 * beacon timers.  Note that since we only hear beacons in
5039 	 * sta/ibss mode this has no effect in other operating modes.
5040 	 */
5041 	ATH_LOCK(sc);
5042 	if (!sc->sc_scanning && ic->ic_curchan == ic->ic_bsschan)
5043 		sc->sc_syncbeacon = 1;
5044 	ATH_UNLOCK(sc);
5045 }
5046 
5047 /*
5048  * Walk the vap list and check if there any vap's in RUN state.
5049  */
5050 static int
5051 ath_isanyrunningvaps(struct ieee80211vap *this)
5052 {
5053 	struct ieee80211com *ic = this->iv_ic;
5054 	struct ieee80211vap *vap;
5055 
5056 	IEEE80211_LOCK_ASSERT(ic);
5057 
5058 	TAILQ_FOREACH(vap, &ic->ic_vaps, iv_next) {
5059 		if (vap != this && vap->iv_state >= IEEE80211_S_RUN)
5060 			return 1;
5061 	}
5062 	return 0;
5063 }
5064 
5065 static int
5066 ath_newstate(struct ieee80211vap *vap, enum ieee80211_state nstate, int arg)
5067 {
5068 	struct ieee80211com *ic = vap->iv_ic;
5069 	struct ath_softc *sc = ic->ic_ifp->if_softc;
5070 	struct ath_vap *avp = ATH_VAP(vap);
5071 	struct ath_hal *ah = sc->sc_ah;
5072 	struct ieee80211_node *ni = NULL;
5073 	int i, error, stamode;
5074 	u_int32_t rfilt;
5075 	int csa_run_transition = 0;
5076 
5077 	static const HAL_LED_STATE leds[] = {
5078 	    HAL_LED_INIT,	/* IEEE80211_S_INIT */
5079 	    HAL_LED_SCAN,	/* IEEE80211_S_SCAN */
5080 	    HAL_LED_AUTH,	/* IEEE80211_S_AUTH */
5081 	    HAL_LED_ASSOC, 	/* IEEE80211_S_ASSOC */
5082 	    HAL_LED_RUN, 	/* IEEE80211_S_CAC */
5083 	    HAL_LED_RUN, 	/* IEEE80211_S_RUN */
5084 	    HAL_LED_RUN, 	/* IEEE80211_S_CSA */
5085 	    HAL_LED_RUN, 	/* IEEE80211_S_SLEEP */
5086 	};
5087 
5088 	DPRINTF(sc, ATH_DEBUG_STATE, "%s: %s -> %s\n", __func__,
5089 		ieee80211_state_name[vap->iv_state],
5090 		ieee80211_state_name[nstate]);
5091 
5092 	/*
5093 	 * net80211 _should_ have the comlock asserted at this point.
5094 	 * There are some comments around the calls to vap->iv_newstate
5095 	 * which indicate that it (newstate) may end up dropping the
5096 	 * lock.  This and the subsequent lock assert check after newstate
5097 	 * are an attempt to catch these and figure out how/why.
5098 	 */
5099 	IEEE80211_LOCK_ASSERT(ic);
5100 
5101 	if (vap->iv_state == IEEE80211_S_CSA && nstate == IEEE80211_S_RUN)
5102 		csa_run_transition = 1;
5103 
5104 	callout_drain(&sc->sc_cal_ch);
5105 	ath_hal_setledstate(ah, leds[nstate]);	/* set LED */
5106 
5107 	if (nstate == IEEE80211_S_SCAN) {
5108 		/*
5109 		 * Scanning: turn off beacon miss and don't beacon.
5110 		 * Mark beacon state so when we reach RUN state we'll
5111 		 * [re]setup beacons.  Unblock the task q thread so
5112 		 * deferred interrupt processing is done.
5113 		 */
5114 		ath_hal_intrset(ah,
5115 		    sc->sc_imask &~ (HAL_INT_SWBA | HAL_INT_BMISS));
5116 		sc->sc_imask &= ~(HAL_INT_SWBA | HAL_INT_BMISS);
5117 		sc->sc_beacons = 0;
5118 		taskqueue_unblock(sc->sc_tq);
5119 		taskqueue_unblock(sc->sc_tx_tq);
5120 	}
5121 
5122 	ni = ieee80211_ref_node(vap->iv_bss);
5123 	rfilt = ath_calcrxfilter(sc);
5124 	stamode = (vap->iv_opmode == IEEE80211_M_STA ||
5125 		   vap->iv_opmode == IEEE80211_M_AHDEMO ||
5126 		   vap->iv_opmode == IEEE80211_M_IBSS);
5127 	if (stamode && nstate == IEEE80211_S_RUN) {
5128 		sc->sc_curaid = ni->ni_associd;
5129 		IEEE80211_ADDR_COPY(sc->sc_curbssid, ni->ni_bssid);
5130 		ath_hal_setassocid(ah, sc->sc_curbssid, sc->sc_curaid);
5131 	}
5132 	DPRINTF(sc, ATH_DEBUG_STATE, "%s: RX filter 0x%x bssid %s aid 0x%x\n",
5133 	   __func__, rfilt, ether_sprintf(sc->sc_curbssid), sc->sc_curaid);
5134 	ath_hal_setrxfilter(ah, rfilt);
5135 
5136 	/* XXX is this to restore keycache on resume? */
5137 	if (vap->iv_opmode != IEEE80211_M_STA &&
5138 	    (vap->iv_flags & IEEE80211_F_PRIVACY)) {
5139 		for (i = 0; i < IEEE80211_WEP_NKID; i++)
5140 			if (ath_hal_keyisvalid(ah, i))
5141 				ath_hal_keysetmac(ah, i, ni->ni_bssid);
5142 	}
5143 
5144 	/*
5145 	 * Invoke the parent method to do net80211 work.
5146 	 */
5147 	error = avp->av_newstate(vap, nstate, arg);
5148 	if (error != 0)
5149 		goto bad;
5150 
5151 	/*
5152 	 * See above: ensure av_newstate() doesn't drop the lock
5153 	 * on us.
5154 	 */
5155 	IEEE80211_LOCK_ASSERT(ic);
5156 
5157 	if (nstate == IEEE80211_S_RUN) {
5158 		/* NB: collect bss node again, it may have changed */
5159 		ieee80211_free_node(ni);
5160 		ni = ieee80211_ref_node(vap->iv_bss);
5161 
5162 		DPRINTF(sc, ATH_DEBUG_STATE,
5163 		    "%s(RUN): iv_flags 0x%08x bintvl %d bssid %s "
5164 		    "capinfo 0x%04x chan %d\n", __func__,
5165 		    vap->iv_flags, ni->ni_intval, ether_sprintf(ni->ni_bssid),
5166 		    ni->ni_capinfo, ieee80211_chan2ieee(ic, ic->ic_curchan));
5167 
5168 		switch (vap->iv_opmode) {
5169 #ifdef IEEE80211_SUPPORT_TDMA
5170 		case IEEE80211_M_AHDEMO:
5171 			if ((vap->iv_caps & IEEE80211_C_TDMA) == 0)
5172 				break;
5173 			/* fall thru... */
5174 #endif
5175 		case IEEE80211_M_HOSTAP:
5176 		case IEEE80211_M_IBSS:
5177 		case IEEE80211_M_MBSS:
5178 			/*
5179 			 * Allocate and setup the beacon frame.
5180 			 *
5181 			 * Stop any previous beacon DMA.  This may be
5182 			 * necessary, for example, when an ibss merge
5183 			 * causes reconfiguration; there will be a state
5184 			 * transition from RUN->RUN that means we may
5185 			 * be called with beacon transmission active.
5186 			 */
5187 			ath_hal_stoptxdma(ah, sc->sc_bhalq);
5188 
5189 			error = ath_beacon_alloc(sc, ni);
5190 			if (error != 0)
5191 				goto bad;
5192 			/*
5193 			 * If joining an adhoc network defer beacon timer
5194 			 * configuration to the next beacon frame so we
5195 			 * have a current TSF to use.  Otherwise we're
5196 			 * starting an ibss/bss so there's no need to delay;
5197 			 * if this is the first vap moving to RUN state, then
5198 			 * beacon state needs to be [re]configured.
5199 			 */
5200 			if (vap->iv_opmode == IEEE80211_M_IBSS &&
5201 			    ni->ni_tstamp.tsf != 0) {
5202 				sc->sc_syncbeacon = 1;
5203 			} else if (!sc->sc_beacons) {
5204 #ifdef IEEE80211_SUPPORT_TDMA
5205 				if (vap->iv_caps & IEEE80211_C_TDMA)
5206 					ath_tdma_config(sc, vap);
5207 				else
5208 #endif
5209 					ath_beacon_config(sc, vap);
5210 				sc->sc_beacons = 1;
5211 			}
5212 			break;
5213 		case IEEE80211_M_STA:
5214 			/*
5215 			 * Defer beacon timer configuration to the next
5216 			 * beacon frame so we have a current TSF to use
5217 			 * (any TSF collected when scanning is likely old).
5218 			 * However if it's due to a CSA -> RUN transition,
5219 			 * force a beacon update so we pick up a lack of
5220 			 * beacons from an AP in CAC and thus force a
5221 			 * scan.
5222 			 *
5223 			 * And, there's also corner cases here where
5224 			 * after a scan, the AP may have disappeared.
5225 			 * In that case, we may not receive an actual
5226 			 * beacon to update the beacon timer and thus we
5227 			 * won't get notified of the missing beacons.
5228 			 */
5229 			sc->sc_syncbeacon = 1;
5230 #if 0
5231 			if (csa_run_transition)
5232 #endif
5233 				ath_beacon_config(sc, vap);
5234 
5235 			/*
5236 			 * PR: kern/175227
5237 			 *
5238 			 * Reconfigure beacons during reset; as otherwise
5239 			 * we won't get the beacon timers reprogrammed
5240 			 * after a reset and thus we won't pick up a
5241 			 * beacon miss interrupt.
5242 			 *
5243 			 * Hopefully we'll see a beacon before the BMISS
5244 			 * timer fires (too often), leading to a STA
5245 			 * disassociation.
5246 			 */
5247 			sc->sc_beacons = 1;
5248 			break;
5249 		case IEEE80211_M_MONITOR:
5250 			/*
5251 			 * Monitor mode vaps have only INIT->RUN and RUN->RUN
5252 			 * transitions so we must re-enable interrupts here to
5253 			 * handle the case of a single monitor mode vap.
5254 			 */
5255 			ath_hal_intrset(ah, sc->sc_imask);
5256 			break;
5257 		case IEEE80211_M_WDS:
5258 			break;
5259 		default:
5260 			break;
5261 		}
5262 		/*
5263 		 * Let the hal process statistics collected during a
5264 		 * scan so it can provide calibrated noise floor data.
5265 		 */
5266 		ath_hal_process_noisefloor(ah);
5267 		/*
5268 		 * Reset rssi stats; maybe not the best place...
5269 		 */
5270 		sc->sc_halstats.ns_avgbrssi = ATH_RSSI_DUMMY_MARKER;
5271 		sc->sc_halstats.ns_avgrssi = ATH_RSSI_DUMMY_MARKER;
5272 		sc->sc_halstats.ns_avgtxrssi = ATH_RSSI_DUMMY_MARKER;
5273 		/*
5274 		 * Finally, start any timers and the task q thread
5275 		 * (in case we didn't go through SCAN state).
5276 		 */
5277 		if (ath_longcalinterval != 0) {
5278 			/* start periodic recalibration timer */
5279 			callout_reset(&sc->sc_cal_ch, 1, ath_calibrate, sc);
5280 		} else {
5281 			DPRINTF(sc, ATH_DEBUG_CALIBRATE,
5282 			    "%s: calibration disabled\n", __func__);
5283 		}
5284 		taskqueue_unblock(sc->sc_tq);
5285 		taskqueue_unblock(sc->sc_tx_tq);
5286 	} else if (nstate == IEEE80211_S_INIT) {
5287 		/*
5288 		 * If there are no vaps left in RUN state then
5289 		 * shutdown host/driver operation:
5290 		 * o disable interrupts
5291 		 * o disable the task queue thread
5292 		 * o mark beacon processing as stopped
5293 		 */
5294 		if (!ath_isanyrunningvaps(vap)) {
5295 			sc->sc_imask &= ~(HAL_INT_SWBA | HAL_INT_BMISS);
5296 			/* disable interrupts  */
5297 			ath_hal_intrset(ah, sc->sc_imask &~ HAL_INT_GLOBAL);
5298 			taskqueue_block(sc->sc_tq);
5299 			taskqueue_block(sc->sc_tx_tq);
5300 			sc->sc_beacons = 0;
5301 		}
5302 #ifdef IEEE80211_SUPPORT_TDMA
5303 		ath_hal_setcca(ah, AH_TRUE);
5304 #endif
5305 	}
5306 bad:
5307 	ieee80211_free_node(ni);
5308 	return error;
5309 }
5310 
5311 /*
5312  * Allocate a key cache slot to the station so we can
5313  * setup a mapping from key index to node. The key cache
5314  * slot is needed for managing antenna state and for
5315  * compression when stations do not use crypto.  We do
5316  * it uniliaterally here; if crypto is employed this slot
5317  * will be reassigned.
5318  */
5319 static void
5320 ath_setup_stationkey(struct ieee80211_node *ni)
5321 {
5322 	struct ieee80211vap *vap = ni->ni_vap;
5323 	struct ath_softc *sc = vap->iv_ic->ic_ifp->if_softc;
5324 	ieee80211_keyix keyix, rxkeyix;
5325 
5326 	/* XXX should take a locked ref to vap->iv_bss */
5327 	if (!ath_key_alloc(vap, &ni->ni_ucastkey, &keyix, &rxkeyix)) {
5328 		/*
5329 		 * Key cache is full; we'll fall back to doing
5330 		 * the more expensive lookup in software.  Note
5331 		 * this also means no h/w compression.
5332 		 */
5333 		/* XXX msg+statistic */
5334 	} else {
5335 		/* XXX locking? */
5336 		ni->ni_ucastkey.wk_keyix = keyix;
5337 		ni->ni_ucastkey.wk_rxkeyix = rxkeyix;
5338 		/* NB: must mark device key to get called back on delete */
5339 		ni->ni_ucastkey.wk_flags |= IEEE80211_KEY_DEVKEY;
5340 		IEEE80211_ADDR_COPY(ni->ni_ucastkey.wk_macaddr, ni->ni_macaddr);
5341 		/* NB: this will create a pass-thru key entry */
5342 		ath_keyset(sc, vap, &ni->ni_ucastkey, vap->iv_bss);
5343 	}
5344 }
5345 
5346 /*
5347  * Setup driver-specific state for a newly associated node.
5348  * Note that we're called also on a re-associate, the isnew
5349  * param tells us if this is the first time or not.
5350  */
5351 static void
5352 ath_newassoc(struct ieee80211_node *ni, int isnew)
5353 {
5354 	struct ath_node *an = ATH_NODE(ni);
5355 	struct ieee80211vap *vap = ni->ni_vap;
5356 	struct ath_softc *sc = vap->iv_ic->ic_ifp->if_softc;
5357 	const struct ieee80211_txparam *tp = ni->ni_txparms;
5358 
5359 	an->an_mcastrix = ath_tx_findrix(sc, tp->mcastrate);
5360 	an->an_mgmtrix = ath_tx_findrix(sc, tp->mgmtrate);
5361 
5362 	ath_rate_newassoc(sc, an, isnew);
5363 	if (isnew &&
5364 	    (vap->iv_flags & IEEE80211_F_PRIVACY) == 0 && sc->sc_hasclrkey &&
5365 	    ni->ni_ucastkey.wk_keyix == IEEE80211_KEYIX_NONE)
5366 		ath_setup_stationkey(ni);
5367 }
5368 
5369 static int
5370 ath_setregdomain(struct ieee80211com *ic, struct ieee80211_regdomain *reg,
5371 	int nchans, struct ieee80211_channel chans[])
5372 {
5373 	struct ath_softc *sc = ic->ic_ifp->if_softc;
5374 	struct ath_hal *ah = sc->sc_ah;
5375 	HAL_STATUS status;
5376 
5377 	DPRINTF(sc, ATH_DEBUG_REGDOMAIN,
5378 	    "%s: rd %u cc %u location %c%s\n",
5379 	    __func__, reg->regdomain, reg->country, reg->location,
5380 	    reg->ecm ? " ecm" : "");
5381 
5382 	status = ath_hal_set_channels(ah, chans, nchans,
5383 	    reg->country, reg->regdomain);
5384 	if (status != HAL_OK) {
5385 		DPRINTF(sc, ATH_DEBUG_REGDOMAIN, "%s: failed, status %u\n",
5386 		    __func__, status);
5387 		return EINVAL;		/* XXX */
5388 	}
5389 
5390 	return 0;
5391 }
5392 
5393 static void
5394 ath_getradiocaps(struct ieee80211com *ic,
5395 	int maxchans, int *nchans, struct ieee80211_channel chans[])
5396 {
5397 	struct ath_softc *sc = ic->ic_ifp->if_softc;
5398 	struct ath_hal *ah = sc->sc_ah;
5399 
5400 	DPRINTF(sc, ATH_DEBUG_REGDOMAIN, "%s: use rd %u cc %d\n",
5401 	    __func__, SKU_DEBUG, CTRY_DEFAULT);
5402 
5403 	/* XXX check return */
5404 	(void) ath_hal_getchannels(ah, chans, maxchans, nchans,
5405 	    HAL_MODE_ALL, CTRY_DEFAULT, SKU_DEBUG, AH_TRUE);
5406 
5407 }
5408 
5409 static int
5410 ath_getchannels(struct ath_softc *sc)
5411 {
5412 	struct ifnet *ifp = sc->sc_ifp;
5413 	struct ieee80211com *ic = ifp->if_l2com;
5414 	struct ath_hal *ah = sc->sc_ah;
5415 	HAL_STATUS status;
5416 
5417 	/*
5418 	 * Collect channel set based on EEPROM contents.
5419 	 */
5420 	status = ath_hal_init_channels(ah, ic->ic_channels, IEEE80211_CHAN_MAX,
5421 	    &ic->ic_nchans, HAL_MODE_ALL, CTRY_DEFAULT, SKU_NONE, AH_TRUE);
5422 	if (status != HAL_OK) {
5423 		if_printf(ifp, "%s: unable to collect channel list from hal, "
5424 		    "status %d\n", __func__, status);
5425 		return EINVAL;
5426 	}
5427 	(void) ath_hal_getregdomain(ah, &sc->sc_eerd);
5428 	ath_hal_getcountrycode(ah, &sc->sc_eecc);	/* NB: cannot fail */
5429 	/* XXX map Atheros sku's to net80211 SKU's */
5430 	/* XXX net80211 types too small */
5431 	ic->ic_regdomain.regdomain = (uint16_t) sc->sc_eerd;
5432 	ic->ic_regdomain.country = (uint16_t) sc->sc_eecc;
5433 	ic->ic_regdomain.isocc[0] = ' ';	/* XXX don't know */
5434 	ic->ic_regdomain.isocc[1] = ' ';
5435 
5436 	ic->ic_regdomain.ecm = 1;
5437 	ic->ic_regdomain.location = 'I';
5438 
5439 	DPRINTF(sc, ATH_DEBUG_REGDOMAIN,
5440 	    "%s: eeprom rd %u cc %u (mapped rd %u cc %u) location %c%s\n",
5441 	    __func__, sc->sc_eerd, sc->sc_eecc,
5442 	    ic->ic_regdomain.regdomain, ic->ic_regdomain.country,
5443 	    ic->ic_regdomain.location, ic->ic_regdomain.ecm ? " ecm" : "");
5444 	return 0;
5445 }
5446 
5447 static int
5448 ath_rate_setup(struct ath_softc *sc, u_int mode)
5449 {
5450 	struct ath_hal *ah = sc->sc_ah;
5451 	const HAL_RATE_TABLE *rt;
5452 
5453 	switch (mode) {
5454 	case IEEE80211_MODE_11A:
5455 		rt = ath_hal_getratetable(ah, HAL_MODE_11A);
5456 		break;
5457 	case IEEE80211_MODE_HALF:
5458 		rt = ath_hal_getratetable(ah, HAL_MODE_11A_HALF_RATE);
5459 		break;
5460 	case IEEE80211_MODE_QUARTER:
5461 		rt = ath_hal_getratetable(ah, HAL_MODE_11A_QUARTER_RATE);
5462 		break;
5463 	case IEEE80211_MODE_11B:
5464 		rt = ath_hal_getratetable(ah, HAL_MODE_11B);
5465 		break;
5466 	case IEEE80211_MODE_11G:
5467 		rt = ath_hal_getratetable(ah, HAL_MODE_11G);
5468 		break;
5469 	case IEEE80211_MODE_TURBO_A:
5470 		rt = ath_hal_getratetable(ah, HAL_MODE_108A);
5471 		break;
5472 	case IEEE80211_MODE_TURBO_G:
5473 		rt = ath_hal_getratetable(ah, HAL_MODE_108G);
5474 		break;
5475 	case IEEE80211_MODE_STURBO_A:
5476 		rt = ath_hal_getratetable(ah, HAL_MODE_TURBO);
5477 		break;
5478 	case IEEE80211_MODE_11NA:
5479 		rt = ath_hal_getratetable(ah, HAL_MODE_11NA_HT20);
5480 		break;
5481 	case IEEE80211_MODE_11NG:
5482 		rt = ath_hal_getratetable(ah, HAL_MODE_11NG_HT20);
5483 		break;
5484 	default:
5485 		DPRINTF(sc, ATH_DEBUG_ANY, "%s: invalid mode %u\n",
5486 			__func__, mode);
5487 		return 0;
5488 	}
5489 	sc->sc_rates[mode] = rt;
5490 	return (rt != NULL);
5491 }
5492 
5493 static void
5494 ath_setcurmode(struct ath_softc *sc, enum ieee80211_phymode mode)
5495 {
5496 #define	N(a)	(sizeof(a)/sizeof(a[0]))
5497 	/* NB: on/off times from the Atheros NDIS driver, w/ permission */
5498 	static const struct {
5499 		u_int		rate;		/* tx/rx 802.11 rate */
5500 		u_int16_t	timeOn;		/* LED on time (ms) */
5501 		u_int16_t	timeOff;	/* LED off time (ms) */
5502 	} blinkrates[] = {
5503 		{ 108,  40,  10 },
5504 		{  96,  44,  11 },
5505 		{  72,  50,  13 },
5506 		{  48,  57,  14 },
5507 		{  36,  67,  16 },
5508 		{  24,  80,  20 },
5509 		{  22, 100,  25 },
5510 		{  18, 133,  34 },
5511 		{  12, 160,  40 },
5512 		{  10, 200,  50 },
5513 		{   6, 240,  58 },
5514 		{   4, 267,  66 },
5515 		{   2, 400, 100 },
5516 		{   0, 500, 130 },
5517 		/* XXX half/quarter rates */
5518 	};
5519 	const HAL_RATE_TABLE *rt;
5520 	int i, j;
5521 
5522 	memset(sc->sc_rixmap, 0xff, sizeof(sc->sc_rixmap));
5523 	rt = sc->sc_rates[mode];
5524 	KASSERT(rt != NULL, ("no h/w rate set for phy mode %u", mode));
5525 	for (i = 0; i < rt->rateCount; i++) {
5526 		uint8_t ieeerate = rt->info[i].dot11Rate & IEEE80211_RATE_VAL;
5527 		if (rt->info[i].phy != IEEE80211_T_HT)
5528 			sc->sc_rixmap[ieeerate] = i;
5529 		else
5530 			sc->sc_rixmap[ieeerate | IEEE80211_RATE_MCS] = i;
5531 	}
5532 	memset(sc->sc_hwmap, 0, sizeof(sc->sc_hwmap));
5533 	for (i = 0; i < N(sc->sc_hwmap); i++) {
5534 		if (i >= rt->rateCount) {
5535 			sc->sc_hwmap[i].ledon = (500 * hz) / 1000;
5536 			sc->sc_hwmap[i].ledoff = (130 * hz) / 1000;
5537 			continue;
5538 		}
5539 		sc->sc_hwmap[i].ieeerate =
5540 			rt->info[i].dot11Rate & IEEE80211_RATE_VAL;
5541 		if (rt->info[i].phy == IEEE80211_T_HT)
5542 			sc->sc_hwmap[i].ieeerate |= IEEE80211_RATE_MCS;
5543 		sc->sc_hwmap[i].txflags = IEEE80211_RADIOTAP_F_DATAPAD;
5544 		if (rt->info[i].shortPreamble ||
5545 		    rt->info[i].phy == IEEE80211_T_OFDM)
5546 			sc->sc_hwmap[i].txflags |= IEEE80211_RADIOTAP_F_SHORTPRE;
5547 		sc->sc_hwmap[i].rxflags = sc->sc_hwmap[i].txflags;
5548 		for (j = 0; j < N(blinkrates)-1; j++)
5549 			if (blinkrates[j].rate == sc->sc_hwmap[i].ieeerate)
5550 				break;
5551 		/* NB: this uses the last entry if the rate isn't found */
5552 		/* XXX beware of overlow */
5553 		sc->sc_hwmap[i].ledon = (blinkrates[j].timeOn * hz) / 1000;
5554 		sc->sc_hwmap[i].ledoff = (blinkrates[j].timeOff * hz) / 1000;
5555 	}
5556 	sc->sc_currates = rt;
5557 	sc->sc_curmode = mode;
5558 	/*
5559 	 * All protection frames are transmited at 2Mb/s for
5560 	 * 11g, otherwise at 1Mb/s.
5561 	 */
5562 	if (mode == IEEE80211_MODE_11G)
5563 		sc->sc_protrix = ath_tx_findrix(sc, 2*2);
5564 	else
5565 		sc->sc_protrix = ath_tx_findrix(sc, 2*1);
5566 	/* NB: caller is responsible for resetting rate control state */
5567 #undef N
5568 }
5569 
5570 static void
5571 ath_watchdog(void *arg)
5572 {
5573 	struct ath_softc *sc = arg;
5574 	int do_reset = 0;
5575 
5576 	if (sc->sc_wd_timer != 0 && --sc->sc_wd_timer == 0) {
5577 		struct ifnet *ifp = sc->sc_ifp;
5578 		uint32_t hangs;
5579 
5580 		if (ath_hal_gethangstate(sc->sc_ah, 0xffff, &hangs) &&
5581 		    hangs != 0) {
5582 			if_printf(ifp, "%s hang detected (0x%x)\n",
5583 			    hangs & 0xff ? "bb" : "mac", hangs);
5584 		} else
5585 			if_printf(ifp, "device timeout\n");
5586 		do_reset = 1;
5587 		ifp->if_oerrors++;
5588 		sc->sc_stats.ast_watchdog++;
5589 	}
5590 
5591 	/*
5592 	 * We can't hold the lock across the ath_reset() call.
5593 	 *
5594 	 * And since this routine can't hold a lock and sleep,
5595 	 * do the reset deferred.
5596 	 */
5597 	if (do_reset) {
5598 		taskqueue_enqueue(sc->sc_tq, &sc->sc_resettask);
5599 	}
5600 
5601 	callout_schedule(&sc->sc_wd_ch, hz);
5602 }
5603 
5604 /*
5605  * Fetch the rate control statistics for the given node.
5606  */
5607 static int
5608 ath_ioctl_ratestats(struct ath_softc *sc, struct ath_rateioctl *rs)
5609 {
5610 	struct ath_node *an;
5611 	struct ieee80211com *ic = sc->sc_ifp->if_l2com;
5612 	struct ieee80211_node *ni;
5613 	int error = 0;
5614 
5615 	/* Perform a lookup on the given node */
5616 	ni = ieee80211_find_node(&ic->ic_sta, rs->is_u.macaddr);
5617 	if (ni == NULL) {
5618 		error = EINVAL;
5619 		goto bad;
5620 	}
5621 
5622 	/* Lock the ath_node */
5623 	an = ATH_NODE(ni);
5624 	ATH_NODE_LOCK(an);
5625 
5626 	/* Fetch the rate control stats for this node */
5627 	error = ath_rate_fetch_node_stats(sc, an, rs);
5628 
5629 	/* No matter what happens here, just drop through */
5630 
5631 	/* Unlock the ath_node */
5632 	ATH_NODE_UNLOCK(an);
5633 
5634 	/* Unref the node */
5635 	ieee80211_node_decref(ni);
5636 
5637 bad:
5638 	return (error);
5639 }
5640 
5641 #ifdef ATH_DIAGAPI
5642 /*
5643  * Diagnostic interface to the HAL.  This is used by various
5644  * tools to do things like retrieve register contents for
5645  * debugging.  The mechanism is intentionally opaque so that
5646  * it can change frequently w/o concern for compatiblity.
5647  */
5648 static int
5649 ath_ioctl_diag(struct ath_softc *sc, struct ath_diag *ad)
5650 {
5651 	struct ath_hal *ah = sc->sc_ah;
5652 	u_int id = ad->ad_id & ATH_DIAG_ID;
5653 	void *indata = NULL;
5654 	void *outdata = NULL;
5655 	u_int32_t insize = ad->ad_in_size;
5656 	u_int32_t outsize = ad->ad_out_size;
5657 	int error = 0;
5658 
5659 	if (ad->ad_id & ATH_DIAG_IN) {
5660 		/*
5661 		 * Copy in data.
5662 		 */
5663 		indata = malloc(insize, M_TEMP, M_NOWAIT);
5664 		if (indata == NULL) {
5665 			error = ENOMEM;
5666 			goto bad;
5667 		}
5668 		error = copyin(ad->ad_in_data, indata, insize);
5669 		if (error)
5670 			goto bad;
5671 	}
5672 	if (ad->ad_id & ATH_DIAG_DYN) {
5673 		/*
5674 		 * Allocate a buffer for the results (otherwise the HAL
5675 		 * returns a pointer to a buffer where we can read the
5676 		 * results).  Note that we depend on the HAL leaving this
5677 		 * pointer for us to use below in reclaiming the buffer;
5678 		 * may want to be more defensive.
5679 		 */
5680 		outdata = malloc(outsize, M_TEMP, M_NOWAIT);
5681 		if (outdata == NULL) {
5682 			error = ENOMEM;
5683 			goto bad;
5684 		}
5685 	}
5686 	if (ath_hal_getdiagstate(ah, id, indata, insize, &outdata, &outsize)) {
5687 		if (outsize < ad->ad_out_size)
5688 			ad->ad_out_size = outsize;
5689 		if (outdata != NULL)
5690 			error = copyout(outdata, ad->ad_out_data,
5691 					ad->ad_out_size);
5692 	} else {
5693 		error = EINVAL;
5694 	}
5695 bad:
5696 	if ((ad->ad_id & ATH_DIAG_IN) && indata != NULL)
5697 		free(indata, M_TEMP);
5698 	if ((ad->ad_id & ATH_DIAG_DYN) && outdata != NULL)
5699 		free(outdata, M_TEMP);
5700 	return error;
5701 }
5702 #endif /* ATH_DIAGAPI */
5703 
5704 static int
5705 ath_ioctl(struct ifnet *ifp, u_long cmd, caddr_t data)
5706 {
5707 #define	IS_RUNNING(ifp) \
5708 	((ifp->if_flags & IFF_UP) && (ifp->if_drv_flags & IFF_DRV_RUNNING))
5709 	struct ath_softc *sc = ifp->if_softc;
5710 	struct ieee80211com *ic = ifp->if_l2com;
5711 	struct ifreq *ifr = (struct ifreq *)data;
5712 	const HAL_RATE_TABLE *rt;
5713 	int error = 0;
5714 
5715 	switch (cmd) {
5716 	case SIOCSIFFLAGS:
5717 		ATH_LOCK(sc);
5718 		if (IS_RUNNING(ifp)) {
5719 			/*
5720 			 * To avoid rescanning another access point,
5721 			 * do not call ath_init() here.  Instead,
5722 			 * only reflect promisc mode settings.
5723 			 */
5724 			ath_mode_init(sc);
5725 		} else if (ifp->if_flags & IFF_UP) {
5726 			/*
5727 			 * Beware of being called during attach/detach
5728 			 * to reset promiscuous mode.  In that case we
5729 			 * will still be marked UP but not RUNNING.
5730 			 * However trying to re-init the interface
5731 			 * is the wrong thing to do as we've already
5732 			 * torn down much of our state.  There's
5733 			 * probably a better way to deal with this.
5734 			 */
5735 			if (!sc->sc_invalid)
5736 				ath_init(sc);	/* XXX lose error */
5737 		} else {
5738 			ath_stop_locked(ifp);
5739 #ifdef notyet
5740 			/* XXX must wakeup in places like ath_vap_delete */
5741 			if (!sc->sc_invalid)
5742 				ath_hal_setpower(sc->sc_ah, HAL_PM_FULL_SLEEP);
5743 #endif
5744 		}
5745 		ATH_UNLOCK(sc);
5746 		break;
5747 	case SIOCGIFMEDIA:
5748 	case SIOCSIFMEDIA:
5749 		error = ifmedia_ioctl(ifp, ifr, &ic->ic_media, cmd);
5750 		break;
5751 	case SIOCGATHSTATS:
5752 		/* NB: embed these numbers to get a consistent view */
5753 		sc->sc_stats.ast_tx_packets = ifp->if_opackets;
5754 		sc->sc_stats.ast_rx_packets = ifp->if_ipackets;
5755 		sc->sc_stats.ast_tx_rssi = ATH_RSSI(sc->sc_halstats.ns_avgtxrssi);
5756 		sc->sc_stats.ast_rx_rssi = ATH_RSSI(sc->sc_halstats.ns_avgrssi);
5757 #ifdef IEEE80211_SUPPORT_TDMA
5758 		sc->sc_stats.ast_tdma_tsfadjp = TDMA_AVG(sc->sc_avgtsfdeltap);
5759 		sc->sc_stats.ast_tdma_tsfadjm = TDMA_AVG(sc->sc_avgtsfdeltam);
5760 #endif
5761 		rt = sc->sc_currates;
5762 		sc->sc_stats.ast_tx_rate =
5763 		    rt->info[sc->sc_txrix].dot11Rate &~ IEEE80211_RATE_BASIC;
5764 		if (rt->info[sc->sc_txrix].phy & IEEE80211_T_HT)
5765 			sc->sc_stats.ast_tx_rate |= IEEE80211_RATE_MCS;
5766 		return copyout(&sc->sc_stats,
5767 		    ifr->ifr_data, sizeof (sc->sc_stats));
5768 	case SIOCGATHAGSTATS:
5769 		return copyout(&sc->sc_aggr_stats,
5770 		    ifr->ifr_data, sizeof (sc->sc_aggr_stats));
5771 	case SIOCZATHSTATS:
5772 		error = priv_check(curthread, PRIV_DRIVER);
5773 		if (error == 0) {
5774 			memset(&sc->sc_stats, 0, sizeof(sc->sc_stats));
5775 			memset(&sc->sc_aggr_stats, 0,
5776 			    sizeof(sc->sc_aggr_stats));
5777 			memset(&sc->sc_intr_stats, 0,
5778 			    sizeof(sc->sc_intr_stats));
5779 		}
5780 		break;
5781 #ifdef ATH_DIAGAPI
5782 	case SIOCGATHDIAG:
5783 		error = ath_ioctl_diag(sc, (struct ath_diag *) ifr);
5784 		break;
5785 	case SIOCGATHPHYERR:
5786 		error = ath_ioctl_phyerr(sc,(struct ath_diag*) ifr);
5787 		break;
5788 #endif
5789 	case SIOCGATHSPECTRAL:
5790 		error = ath_ioctl_spectral(sc,(struct ath_diag*) ifr);
5791 		break;
5792 	case SIOCGATHNODERATESTATS:
5793 		error = ath_ioctl_ratestats(sc, (struct ath_rateioctl *) ifr);
5794 		break;
5795 	case SIOCGIFADDR:
5796 		error = ether_ioctl(ifp, cmd, data);
5797 		break;
5798 	default:
5799 		error = EINVAL;
5800 		break;
5801 	}
5802 	return error;
5803 #undef IS_RUNNING
5804 }
5805 
5806 /*
5807  * Announce various information on device/driver attach.
5808  */
5809 static void
5810 ath_announce(struct ath_softc *sc)
5811 {
5812 	struct ifnet *ifp = sc->sc_ifp;
5813 	struct ath_hal *ah = sc->sc_ah;
5814 
5815 	if_printf(ifp, "AR%s mac %d.%d RF%s phy %d.%d\n",
5816 		ath_hal_mac_name(ah), ah->ah_macVersion, ah->ah_macRev,
5817 		ath_hal_rf_name(ah), ah->ah_phyRev >> 4, ah->ah_phyRev & 0xf);
5818 	if_printf(ifp, "2GHz radio: 0x%.4x; 5GHz radio: 0x%.4x\n",
5819 		ah->ah_analog2GhzRev, ah->ah_analog5GhzRev);
5820 	if (bootverbose) {
5821 		int i;
5822 		for (i = 0; i <= WME_AC_VO; i++) {
5823 			struct ath_txq *txq = sc->sc_ac2q[i];
5824 			if_printf(ifp, "Use hw queue %u for %s traffic\n",
5825 				txq->axq_qnum, ieee80211_wme_acnames[i]);
5826 		}
5827 		if_printf(ifp, "Use hw queue %u for CAB traffic\n",
5828 			sc->sc_cabq->axq_qnum);
5829 		if_printf(ifp, "Use hw queue %u for beacons\n", sc->sc_bhalq);
5830 	}
5831 	if (ath_rxbuf != ATH_RXBUF)
5832 		if_printf(ifp, "using %u rx buffers\n", ath_rxbuf);
5833 	if (ath_txbuf != ATH_TXBUF)
5834 		if_printf(ifp, "using %u tx buffers\n", ath_txbuf);
5835 	if (sc->sc_mcastkey && bootverbose)
5836 		if_printf(ifp, "using multicast key search\n");
5837 }
5838 
5839 static void
5840 ath_dfs_tasklet(void *p, int npending)
5841 {
5842 	struct ath_softc *sc = (struct ath_softc *) p;
5843 	struct ifnet *ifp = sc->sc_ifp;
5844 	struct ieee80211com *ic = ifp->if_l2com;
5845 
5846 	/*
5847 	 * If previous processing has found a radar event,
5848 	 * signal this to the net80211 layer to begin DFS
5849 	 * processing.
5850 	 */
5851 	if (ath_dfs_process_radar_event(sc, sc->sc_curchan)) {
5852 		/* DFS event found, initiate channel change */
5853 		/*
5854 		 * XXX doesn't currently tell us whether the event
5855 		 * XXX was found in the primary or extension
5856 		 * XXX channel!
5857 		 */
5858 		IEEE80211_LOCK(ic);
5859 		ieee80211_dfs_notify_radar(ic, sc->sc_curchan);
5860 		IEEE80211_UNLOCK(ic);
5861 	}
5862 }
5863 
5864 /*
5865  * Enable/disable power save.  This must be called with
5866  * no TX driver locks currently held, so it should only
5867  * be called from the RX path (which doesn't hold any
5868  * TX driver locks.)
5869  */
5870 static void
5871 ath_node_powersave(struct ieee80211_node *ni, int enable)
5872 {
5873 #ifdef	ATH_SW_PSQ
5874 	struct ath_node *an = ATH_NODE(ni);
5875 	struct ieee80211com *ic = ni->ni_ic;
5876 	struct ath_softc *sc = ic->ic_ifp->if_softc;
5877 	struct ath_vap *avp = ATH_VAP(ni->ni_vap);
5878 
5879 	ATH_NODE_UNLOCK_ASSERT(an);
5880 	/* XXX and no TXQ locks should be held here */
5881 
5882 	DPRINTF(sc, ATH_DEBUG_NODE_PWRSAVE, "%s: ni=%p, enable=%d\n",
5883 	    __func__, ni, enable);
5884 
5885 	/* Suspend or resume software queue handling */
5886 	if (enable)
5887 		ath_tx_node_sleep(sc, an);
5888 	else
5889 		ath_tx_node_wakeup(sc, an);
5890 
5891 	/* Update net80211 state */
5892 	avp->av_node_ps(ni, enable);
5893 #else
5894 	struct ath_vap *avp = ATH_VAP(ni->ni_vap);
5895 
5896 	/* Update net80211 state */
5897 	avp->av_node_ps(ni, enable);
5898 #endif/* ATH_SW_PSQ */
5899 }
5900 
5901 /*
5902  * Notification from net80211 that the powersave queue state has
5903  * changed.
5904  *
5905  * Since the software queue also may have some frames:
5906  *
5907  * + if the node software queue has frames and the TID state
5908  *   is 0, we set the TIM;
5909  * + if the node and the stack are both empty, we clear the TIM bit.
5910  * + If the stack tries to set the bit, always set it.
5911  * + If the stack tries to clear the bit, only clear it if the
5912  *   software queue in question is also cleared.
5913  *
5914  * TODO: this is called during node teardown; so let's ensure this
5915  * is all correctly handled and that the TIM bit is cleared.
5916  * It may be that the node flush is called _AFTER_ the net80211
5917  * stack clears the TIM.
5918  *
5919  * Here is the racy part.  Since it's possible >1 concurrent,
5920  * overlapping TXes will appear complete with a TX completion in
5921  * another thread, it's possible that the concurrent TIM calls will
5922  * clash.  We can't hold the node lock here because setting the
5923  * TIM grabs the net80211 comlock and this may cause a LOR.
5924  * The solution is either to totally serialise _everything_ at
5925  * this point (ie, all TX, completion and any reset/flush go into
5926  * one taskqueue) or a new "ath TIM lock" needs to be created that
5927  * just wraps the driver state change and this call to avp->av_set_tim().
5928  *
5929  * The same race exists in the net80211 power save queue handling
5930  * as well.  Since multiple transmitting threads may queue frames
5931  * into the driver, as well as ps-poll and the driver transmitting
5932  * frames (and thus clearing the psq), it's quite possible that
5933  * a packet entering the PSQ and a ps-poll being handled will
5934  * race, causing the TIM to be cleared and not re-set.
5935  */
5936 static int
5937 ath_node_set_tim(struct ieee80211_node *ni, int enable)
5938 {
5939 #ifdef	ATH_SW_PSQ
5940 	struct ieee80211com *ic = ni->ni_ic;
5941 	struct ath_softc *sc = ic->ic_ifp->if_softc;
5942 	struct ath_node *an = ATH_NODE(ni);
5943 	struct ath_vap *avp = ATH_VAP(ni->ni_vap);
5944 	int changed = 0;
5945 
5946 	ATH_NODE_UNLOCK_ASSERT(an);
5947 
5948 	/*
5949 	 * For now, just track and then update the TIM.
5950 	 */
5951 	ATH_NODE_LOCK(an);
5952 	an->an_stack_psq = enable;
5953 
5954 	/*
5955 	 * This will get called for all operating modes,
5956 	 * even if avp->av_set_tim is unset.
5957 	 * It's currently set for hostap/ibss modes; but
5958 	 * the same infrastructure is used for both STA
5959 	 * and AP/IBSS node power save.
5960 	 */
5961 	if (avp->av_set_tim == NULL) {
5962 		ATH_NODE_UNLOCK(an);
5963 		return (0);
5964 	}
5965 
5966 	/*
5967 	 * If setting the bit, always set it here.
5968 	 * If clearing the bit, only clear it if the
5969 	 * software queue is also empty.
5970 	 *
5971 	 * If the node has left power save, just clear the TIM
5972 	 * bit regardless of the state of the power save queue.
5973 	 *
5974 	 * XXX TODO: although atomics are used, it's quite possible
5975 	 * that a race will occur between this and setting/clearing
5976 	 * in another thread.  TX completion will occur always in
5977 	 * one thread, however setting/clearing the TIM bit can come
5978 	 * from a variety of different process contexts!
5979 	 */
5980 	if (enable && an->an_tim_set == 1) {
5981 		DPRINTF(sc, ATH_DEBUG_NODE_PWRSAVE,
5982 		    "%s: an=%p, enable=%d, tim_set=1, ignoring\n",
5983 		    __func__, an, enable);
5984 		ATH_NODE_UNLOCK(an);
5985 	} else if (enable) {
5986 		DPRINTF(sc, ATH_DEBUG_NODE_PWRSAVE,
5987 		    "%s: an=%p, enable=%d, enabling TIM\n",
5988 		    __func__, an, enable);
5989 		an->an_tim_set = 1;
5990 		ATH_NODE_UNLOCK(an);
5991 		changed = avp->av_set_tim(ni, enable);
5992 	} else if (atomic_load_acq_int(&an->an_swq_depth) == 0) {
5993 		/* disable */
5994 		DPRINTF(sc, ATH_DEBUG_NODE_PWRSAVE,
5995 		    "%s: an=%p, enable=%d, an_swq_depth == 0, disabling\n",
5996 		    __func__, an, enable);
5997 		an->an_tim_set = 0;
5998 		ATH_NODE_UNLOCK(an);
5999 		changed = avp->av_set_tim(ni, enable);
6000 	} else if (! an->an_is_powersave) {
6001 		/*
6002 		 * disable regardless; the node isn't in powersave now
6003 		 */
6004 		DPRINTF(sc, ATH_DEBUG_NODE_PWRSAVE,
6005 		    "%s: an=%p, enable=%d, an_pwrsave=0, disabling\n",
6006 		    __func__, an, enable);
6007 		an->an_tim_set = 0;
6008 		ATH_NODE_UNLOCK(an);
6009 		changed = avp->av_set_tim(ni, enable);
6010 	} else {
6011 		/*
6012 		 * psq disable, node is currently in powersave, node
6013 		 * software queue isn't empty, so don't clear the TIM bit
6014 		 * for now.
6015 		 */
6016 		ATH_NODE_UNLOCK(an);
6017 		DPRINTF(sc, ATH_DEBUG_NODE_PWRSAVE,
6018 		    "%s: enable=%d, an_swq_depth > 0, ignoring\n",
6019 		    __func__, enable);
6020 		changed = 0;
6021 	}
6022 
6023 	return (changed);
6024 #else
6025 	struct ath_vap *avp = ATH_VAP(ni->ni_vap);
6026 
6027 	/*
6028 	 * Some operating modes don't set av_set_tim(), so don't
6029 	 * update it here.
6030 	 */
6031 	if (avp->av_set_tim == NULL)
6032 		return (0);
6033 
6034 	return (avp->av_set_tim(ni, enable));
6035 #endif /* ATH_SW_PSQ */
6036 }
6037 
6038 /*
6039  * Set or update the TIM from the software queue.
6040  *
6041  * Check the software queue depth before attempting to do lock
6042  * anything; that avoids trying to obtain the lock.  Then,
6043  * re-check afterwards to ensure nothing has changed in the
6044  * meantime.
6045  *
6046  * set:   This is designed to be called from the TX path, after
6047  *        a frame has been queued; to see if the swq > 0.
6048  *
6049  * clear: This is designed to be called from the buffer completion point
6050  *        (right now it's ath_tx_default_comp()) where the state of
6051  *        a software queue has changed.
6052  *
6053  * It makes sense to place it at buffer free / completion rather
6054  * than after each software queue operation, as there's no real
6055  * point in churning the TIM bit as the last frames in the software
6056  * queue are transmitted.  If they fail and we retry them, we'd
6057  * just be setting the TIM bit again anyway.
6058  */
6059 void
6060 ath_tx_update_tim(struct ath_softc *sc, struct ieee80211_node *ni,
6061      int enable)
6062 {
6063 #ifdef	ATH_SW_PSQ
6064 	struct ath_node *an;
6065 	struct ath_vap *avp;
6066 
6067 	/* Don't do this for broadcast/etc frames */
6068 	if (ni == NULL)
6069 		return;
6070 
6071 	an = ATH_NODE(ni);
6072 	avp = ATH_VAP(ni->ni_vap);
6073 
6074 	/*
6075 	 * And for operating modes without the TIM handler set, let's
6076 	 * just skip those.
6077 	 */
6078 	if (avp->av_set_tim == NULL)
6079 		return;
6080 
6081 	ATH_NODE_UNLOCK_ASSERT(an);
6082 
6083 	if (enable) {
6084 		/*
6085 		 * Don't bother grabbing the lock unless the queue is not
6086 		 * empty.
6087 		 */
6088 		if (atomic_load_acq_int(&an->an_swq_depth) == 0)
6089 			return;
6090 
6091 		ATH_NODE_LOCK(an);
6092 		if (an->an_is_powersave &&
6093 		    an->an_tim_set == 0 &&
6094 		    atomic_load_acq_int(&an->an_swq_depth) != 0) {
6095 			DPRINTF(sc, ATH_DEBUG_NODE_PWRSAVE,
6096 			    "%s: an=%p, swq_depth>0, tim_set=0, set!\n",
6097 			    __func__, an);
6098 			an->an_tim_set = 1;
6099 			ATH_NODE_UNLOCK(an);
6100 			(void) avp->av_set_tim(ni, 1);
6101 		} else {
6102 			ATH_NODE_UNLOCK(an);
6103 		}
6104 	} else {
6105 		/*
6106 		 * Don't bother grabbing the lock unless the queue is empty.
6107 		 */
6108 		if (atomic_load_acq_int(&an->an_swq_depth) != 0)
6109 			return;
6110 
6111 		ATH_NODE_LOCK(an);
6112 		if (an->an_is_powersave &&
6113 		    an->an_stack_psq == 0 &&
6114 		    an->an_tim_set == 1 &&
6115 		    atomic_load_acq_int(&an->an_swq_depth) == 0) {
6116 			DPRINTF(sc, ATH_DEBUG_NODE_PWRSAVE,
6117 			    "%s: an=%p, swq_depth=0, tim_set=1, psq_set=0,"
6118 			    " clear!\n",
6119 			    __func__, an);
6120 			an->an_tim_set = 0;
6121 			ATH_NODE_UNLOCK(an);
6122 			(void) avp->av_set_tim(ni, 0);
6123 		} else {
6124 			ATH_NODE_UNLOCK(an);
6125 		}
6126 	}
6127 #else
6128 	return;
6129 #endif	/* ATH_SW_PSQ */
6130 }
6131 
6132 MODULE_VERSION(if_ath, 1);
6133 MODULE_DEPEND(if_ath, wlan, 1, 1, 1);          /* 802.11 media layer */
6134 #if	defined(IEEE80211_ALQ) || defined(AH_DEBUG_ALQ)
6135 MODULE_DEPEND(if_ath, alq, 1, 1, 1);
6136 #endif
6137