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