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