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