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