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