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