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