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