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