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