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