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