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