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