xref: /freebsd/sys/dev/ath/if_ath.c (revision c2bce4a2fcf3083607e00a1734b47c249751c8a8)
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_GTT)
1359 			sc->sc_stats.ast_tx_timeout++;
1360 		if (status & HAL_INT_CST)
1361 			sc->sc_stats.ast_tx_cst++;
1362 		if (status & HAL_INT_MIB) {
1363 			sc->sc_stats.ast_mib++;
1364 			/*
1365 			 * Disable interrupts until we service the MIB
1366 			 * interrupt; otherwise it will continue to fire.
1367 			 */
1368 			ath_hal_intrset(ah, 0);
1369 			/*
1370 			 * Let the hal handle the event.  We assume it will
1371 			 * clear whatever condition caused the interrupt.
1372 			 */
1373 			ath_hal_mibevent(ah, &sc->sc_halstats);
1374 			ath_hal_intrset(ah, sc->sc_imask);
1375 		}
1376 		if (status & HAL_INT_RXORN) {
1377 			/* NB: hal marks HAL_INT_FATAL when RXORN is fatal */
1378 			sc->sc_stats.ast_rxorn++;
1379 		}
1380 	}
1381 }
1382 
1383 static void
1384 ath_fatal_proc(void *arg, int pending)
1385 {
1386 	struct ath_softc *sc = arg;
1387 	struct ifnet *ifp = sc->sc_ifp;
1388 	u_int32_t *state;
1389 	u_int32_t len;
1390 	void *sp;
1391 
1392 	if_printf(ifp, "hardware error; resetting\n");
1393 	/*
1394 	 * Fatal errors are unrecoverable.  Typically these
1395 	 * are caused by DMA errors.  Collect h/w state from
1396 	 * the hal so we can diagnose what's going on.
1397 	 */
1398 	if (ath_hal_getfatalstate(sc->sc_ah, &sp, &len)) {
1399 		KASSERT(len >= 6*sizeof(u_int32_t), ("len %u bytes", len));
1400 		state = sp;
1401 		if_printf(ifp, "0x%08x 0x%08x 0x%08x, 0x%08x 0x%08x 0x%08x\n",
1402 		    state[0], state[1] , state[2], state[3],
1403 		    state[4], state[5]);
1404 	}
1405 	ath_reset(ifp);
1406 }
1407 
1408 static void
1409 ath_bmiss_vap(struct ieee80211vap *vap)
1410 {
1411 	/*
1412 	 * Workaround phantom bmiss interrupts by sanity-checking
1413 	 * the time of our last rx'd frame.  If it is within the
1414 	 * beacon miss interval then ignore the interrupt.  If it's
1415 	 * truly a bmiss we'll get another interrupt soon and that'll
1416 	 * be dispatched up for processing.  Note this applies only
1417 	 * for h/w beacon miss events.
1418 	 */
1419 	if ((vap->iv_flags_ext & IEEE80211_FEXT_SWBMISS) == 0) {
1420 		struct ifnet *ifp = vap->iv_ic->ic_ifp;
1421 		struct ath_softc *sc = ifp->if_softc;
1422 		u_int64_t lastrx = sc->sc_lastrx;
1423 		u_int64_t tsf = ath_hal_gettsf64(sc->sc_ah);
1424 		u_int bmisstimeout =
1425 			vap->iv_bmissthreshold * vap->iv_bss->ni_intval * 1024;
1426 
1427 		DPRINTF(sc, ATH_DEBUG_BEACON,
1428 		    "%s: tsf %llu lastrx %lld (%llu) bmiss %u\n",
1429 		    __func__, (unsigned long long) tsf,
1430 		    (unsigned long long)(tsf - lastrx),
1431 		    (unsigned long long) lastrx, bmisstimeout);
1432 
1433 		if (tsf - lastrx <= bmisstimeout) {
1434 			sc->sc_stats.ast_bmiss_phantom++;
1435 			return;
1436 		}
1437 	}
1438 	ATH_VAP(vap)->av_bmiss(vap);
1439 }
1440 
1441 static int
1442 ath_hal_gethangstate(struct ath_hal *ah, uint32_t mask, uint32_t *hangs)
1443 {
1444 	uint32_t rsize;
1445 	void *sp;
1446 
1447 	if (!ath_hal_getdiagstate(ah, HAL_DIAG_CHECK_HANGS, &mask, sizeof(mask), &sp, &rsize))
1448 		return 0;
1449 	KASSERT(rsize == sizeof(uint32_t), ("resultsize %u", rsize));
1450 	*hangs = *(uint32_t *)sp;
1451 	return 1;
1452 }
1453 
1454 static void
1455 ath_bmiss_proc(void *arg, int pending)
1456 {
1457 	struct ath_softc *sc = arg;
1458 	struct ifnet *ifp = sc->sc_ifp;
1459 	uint32_t hangs;
1460 
1461 	DPRINTF(sc, ATH_DEBUG_ANY, "%s: pending %u\n", __func__, pending);
1462 
1463 	if (ath_hal_gethangstate(sc->sc_ah, 0xff, &hangs) && hangs != 0) {
1464 		if_printf(ifp, "bb hang detected (0x%x), resetting\n", hangs);
1465 		ath_reset(ifp);
1466 	} else
1467 		ieee80211_beacon_miss(ifp->if_l2com);
1468 }
1469 
1470 /*
1471  * Handle TKIP MIC setup to deal hardware that doesn't do MIC
1472  * calcs together with WME.  If necessary disable the crypto
1473  * hardware and mark the 802.11 state so keys will be setup
1474  * with the MIC work done in software.
1475  */
1476 static void
1477 ath_settkipmic(struct ath_softc *sc)
1478 {
1479 	struct ifnet *ifp = sc->sc_ifp;
1480 	struct ieee80211com *ic = ifp->if_l2com;
1481 
1482 	if ((ic->ic_cryptocaps & IEEE80211_CRYPTO_TKIP) && !sc->sc_wmetkipmic) {
1483 		if (ic->ic_flags & IEEE80211_F_WME) {
1484 			ath_hal_settkipmic(sc->sc_ah, AH_FALSE);
1485 			ic->ic_cryptocaps &= ~IEEE80211_CRYPTO_TKIPMIC;
1486 		} else {
1487 			ath_hal_settkipmic(sc->sc_ah, AH_TRUE);
1488 			ic->ic_cryptocaps |= IEEE80211_CRYPTO_TKIPMIC;
1489 		}
1490 	}
1491 }
1492 
1493 static void
1494 ath_init(void *arg)
1495 {
1496 	struct ath_softc *sc = (struct ath_softc *) arg;
1497 	struct ifnet *ifp = sc->sc_ifp;
1498 	struct ieee80211com *ic = ifp->if_l2com;
1499 	struct ath_hal *ah = sc->sc_ah;
1500 	HAL_STATUS status;
1501 
1502 	DPRINTF(sc, ATH_DEBUG_ANY, "%s: if_flags 0x%x\n",
1503 		__func__, ifp->if_flags);
1504 
1505 	ATH_LOCK(sc);
1506 	/*
1507 	 * Stop anything previously setup.  This is safe
1508 	 * whether this is the first time through or not.
1509 	 */
1510 	ath_stop_locked(ifp);
1511 
1512 	/*
1513 	 * The basic interface to setting the hardware in a good
1514 	 * state is ``reset''.  On return the hardware is known to
1515 	 * be powered up and with interrupts disabled.  This must
1516 	 * be followed by initialization of the appropriate bits
1517 	 * and then setup of the interrupt mask.
1518 	 */
1519 	ath_settkipmic(sc);
1520 	if (!ath_hal_reset(ah, sc->sc_opmode, ic->ic_curchan, AH_FALSE, &status)) {
1521 		if_printf(ifp, "unable to reset hardware; hal status %u\n",
1522 			status);
1523 		ATH_UNLOCK(sc);
1524 		return;
1525 	}
1526 	ath_chan_change(sc, ic->ic_curchan);
1527 
1528 	/*
1529 	 * Likewise this is set during reset so update
1530 	 * state cached in the driver.
1531 	 */
1532 	sc->sc_diversity = ath_hal_getdiversity(ah);
1533 	sc->sc_lastlongcal = 0;
1534 	sc->sc_resetcal = 1;
1535 	sc->sc_lastcalreset = 0;
1536 	sc->sc_lastani = 0;
1537 	sc->sc_lastshortcal = 0;
1538 	sc->sc_doresetcal = AH_FALSE;
1539 
1540 	/*
1541 	 * Setup the hardware after reset: the key cache
1542 	 * is filled as needed and the receive engine is
1543 	 * set going.  Frame transmit is handled entirely
1544 	 * in the frame output path; there's nothing to do
1545 	 * here except setup the interrupt mask.
1546 	 */
1547 	if (ath_startrecv(sc) != 0) {
1548 		if_printf(ifp, "unable to start recv logic\n");
1549 		ATH_UNLOCK(sc);
1550 		return;
1551 	}
1552 
1553 	/*
1554 	 * Enable interrupts.
1555 	 */
1556 	sc->sc_imask = HAL_INT_RX | HAL_INT_TX
1557 		  | HAL_INT_RXEOL | HAL_INT_RXORN
1558 		  | HAL_INT_FATAL | HAL_INT_GLOBAL;
1559 	/*
1560 	 * Enable MIB interrupts when there are hardware phy counters.
1561 	 * Note we only do this (at the moment) for station mode.
1562 	 */
1563 	if (sc->sc_needmib && ic->ic_opmode == IEEE80211_M_STA)
1564 		sc->sc_imask |= HAL_INT_MIB;
1565 
1566 	/* Enable global TX timeout and carrier sense timeout if available */
1567 	if (ath_hal_gtxto_supported(ah))
1568 		sc->sc_imask |= HAL_INT_GTT;
1569 
1570 	DPRINTF(sc, ATH_DEBUG_RESET, "%s: imask=0x%x\n",
1571 		__func__, sc->sc_imask);
1572 
1573 	ifp->if_drv_flags |= IFF_DRV_RUNNING;
1574 	callout_reset(&sc->sc_wd_ch, hz, ath_watchdog, sc);
1575 	ath_hal_intrset(ah, sc->sc_imask);
1576 
1577 	ATH_UNLOCK(sc);
1578 
1579 #ifdef ATH_TX99_DIAG
1580 	if (sc->sc_tx99 != NULL)
1581 		sc->sc_tx99->start(sc->sc_tx99);
1582 	else
1583 #endif
1584 	ieee80211_start_all(ic);		/* start all vap's */
1585 }
1586 
1587 static void
1588 ath_stop_locked(struct ifnet *ifp)
1589 {
1590 	struct ath_softc *sc = ifp->if_softc;
1591 	struct ath_hal *ah = sc->sc_ah;
1592 
1593 	DPRINTF(sc, ATH_DEBUG_ANY, "%s: invalid %u if_flags 0x%x\n",
1594 		__func__, sc->sc_invalid, ifp->if_flags);
1595 
1596 	ATH_LOCK_ASSERT(sc);
1597 	if (ifp->if_drv_flags & IFF_DRV_RUNNING) {
1598 		/*
1599 		 * Shutdown the hardware and driver:
1600 		 *    reset 802.11 state machine
1601 		 *    turn off timers
1602 		 *    disable interrupts
1603 		 *    turn off the radio
1604 		 *    clear transmit machinery
1605 		 *    clear receive machinery
1606 		 *    drain and release tx queues
1607 		 *    reclaim beacon resources
1608 		 *    power down hardware
1609 		 *
1610 		 * Note that some of this work is not possible if the
1611 		 * hardware is gone (invalid).
1612 		 */
1613 #ifdef ATH_TX99_DIAG
1614 		if (sc->sc_tx99 != NULL)
1615 			sc->sc_tx99->stop(sc->sc_tx99);
1616 #endif
1617 		callout_stop(&sc->sc_wd_ch);
1618 		sc->sc_wd_timer = 0;
1619 		ifp->if_drv_flags &= ~IFF_DRV_RUNNING;
1620 		if (!sc->sc_invalid) {
1621 			if (sc->sc_softled) {
1622 				callout_stop(&sc->sc_ledtimer);
1623 				ath_hal_gpioset(ah, sc->sc_ledpin,
1624 					!sc->sc_ledon);
1625 				sc->sc_blinking = 0;
1626 			}
1627 			ath_hal_intrset(ah, 0);
1628 		}
1629 		ath_draintxq(sc);
1630 		if (!sc->sc_invalid) {
1631 			ath_stoprecv(sc);
1632 			ath_hal_phydisable(ah);
1633 		} else
1634 			sc->sc_rxlink = NULL;
1635 		ath_beacon_free(sc);	/* XXX not needed */
1636 	}
1637 }
1638 
1639 static void
1640 ath_stop(struct ifnet *ifp)
1641 {
1642 	struct ath_softc *sc = ifp->if_softc;
1643 
1644 	ATH_LOCK(sc);
1645 	ath_stop_locked(ifp);
1646 	ATH_UNLOCK(sc);
1647 }
1648 
1649 /*
1650  * Reset the hardware w/o losing operational state.  This is
1651  * basically a more efficient way of doing ath_stop, ath_init,
1652  * followed by state transitions to the current 802.11
1653  * operational state.  Used to recover from various errors and
1654  * to reset or reload hardware state.
1655  */
1656 int
1657 ath_reset(struct ifnet *ifp)
1658 {
1659 	struct ath_softc *sc = ifp->if_softc;
1660 	struct ieee80211com *ic = ifp->if_l2com;
1661 	struct ath_hal *ah = sc->sc_ah;
1662 	HAL_STATUS status;
1663 
1664 	ath_hal_intrset(ah, 0);		/* disable interrupts */
1665 	ath_draintxq(sc);		/* stop xmit side */
1666 	ath_stoprecv(sc);		/* stop recv side */
1667 	ath_settkipmic(sc);		/* configure TKIP MIC handling */
1668 	/* NB: indicate channel change so we do a full reset */
1669 	if (!ath_hal_reset(ah, sc->sc_opmode, ic->ic_curchan, AH_TRUE, &status))
1670 		if_printf(ifp, "%s: unable to reset hardware; hal status %u\n",
1671 			__func__, status);
1672 	sc->sc_diversity = ath_hal_getdiversity(ah);
1673 	if (ath_startrecv(sc) != 0)	/* restart recv */
1674 		if_printf(ifp, "%s: unable to start recv logic\n", __func__);
1675 	/*
1676 	 * We may be doing a reset in response to an ioctl
1677 	 * that changes the channel so update any state that
1678 	 * might change as a result.
1679 	 */
1680 	ath_chan_change(sc, ic->ic_curchan);
1681 	if (sc->sc_beacons) {		/* restart beacons */
1682 #ifdef IEEE80211_SUPPORT_TDMA
1683 		if (sc->sc_tdma)
1684 			ath_tdma_config(sc, NULL);
1685 		else
1686 #endif
1687 			ath_beacon_config(sc, NULL);
1688 	}
1689 	ath_hal_intrset(ah, sc->sc_imask);
1690 
1691 	ath_start(ifp);			/* restart xmit */
1692 	return 0;
1693 }
1694 
1695 static int
1696 ath_reset_vap(struct ieee80211vap *vap, u_long cmd)
1697 {
1698 	struct ieee80211com *ic = vap->iv_ic;
1699 	struct ifnet *ifp = ic->ic_ifp;
1700 	struct ath_softc *sc = ifp->if_softc;
1701 	struct ath_hal *ah = sc->sc_ah;
1702 
1703 	switch (cmd) {
1704 	case IEEE80211_IOC_TXPOWER:
1705 		/*
1706 		 * If per-packet TPC is enabled, then we have nothing
1707 		 * to do; otherwise we need to force the global limit.
1708 		 * All this can happen directly; no need to reset.
1709 		 */
1710 		if (!ath_hal_gettpc(ah))
1711 			ath_hal_settxpowlimit(ah, ic->ic_txpowlimit);
1712 		return 0;
1713 	}
1714 	return ath_reset(ifp);
1715 }
1716 
1717 struct ath_buf *
1718 _ath_getbuf_locked(struct ath_softc *sc)
1719 {
1720 	struct ath_buf *bf;
1721 
1722 	ATH_TXBUF_LOCK_ASSERT(sc);
1723 
1724 	bf = STAILQ_FIRST(&sc->sc_txbuf);
1725 	if (bf != NULL && (bf->bf_flags & ATH_BUF_BUSY) == 0)
1726 		STAILQ_REMOVE_HEAD(&sc->sc_txbuf, bf_list);
1727 	else
1728 		bf = NULL;
1729 	if (bf == NULL) {
1730 		DPRINTF(sc, ATH_DEBUG_XMIT, "%s: %s\n", __func__,
1731 		    STAILQ_FIRST(&sc->sc_txbuf) == NULL ?
1732 			"out of xmit buffers" : "xmit buffer busy");
1733 	}
1734 	return bf;
1735 }
1736 
1737 struct ath_buf *
1738 ath_getbuf(struct ath_softc *sc)
1739 {
1740 	struct ath_buf *bf;
1741 
1742 	ATH_TXBUF_LOCK(sc);
1743 	bf = _ath_getbuf_locked(sc);
1744 	if (bf == NULL) {
1745 		struct ifnet *ifp = sc->sc_ifp;
1746 
1747 		DPRINTF(sc, ATH_DEBUG_XMIT, "%s: stop queue\n", __func__);
1748 		sc->sc_stats.ast_tx_qstop++;
1749 		ifp->if_drv_flags |= IFF_DRV_OACTIVE;
1750 	}
1751 	ATH_TXBUF_UNLOCK(sc);
1752 	return bf;
1753 }
1754 
1755 static void
1756 ath_start(struct ifnet *ifp)
1757 {
1758 	struct ath_softc *sc = ifp->if_softc;
1759 	struct ieee80211_node *ni;
1760 	struct ath_buf *bf;
1761 	struct mbuf *m, *next;
1762 	ath_bufhead frags;
1763 
1764 	if ((ifp->if_drv_flags & IFF_DRV_RUNNING) == 0 || sc->sc_invalid)
1765 		return;
1766 	for (;;) {
1767 		/*
1768 		 * Grab a TX buffer and associated resources.
1769 		 */
1770 		bf = ath_getbuf(sc);
1771 		if (bf == NULL)
1772 			break;
1773 
1774 		IFQ_DEQUEUE(&ifp->if_snd, m);
1775 		if (m == NULL) {
1776 			ATH_TXBUF_LOCK(sc);
1777 			STAILQ_INSERT_HEAD(&sc->sc_txbuf, bf, bf_list);
1778 			ATH_TXBUF_UNLOCK(sc);
1779 			break;
1780 		}
1781 		ni = (struct ieee80211_node *) m->m_pkthdr.rcvif;
1782 		/*
1783 		 * Check for fragmentation.  If this frame
1784 		 * has been broken up verify we have enough
1785 		 * buffers to send all the fragments so all
1786 		 * go out or none...
1787 		 */
1788 		STAILQ_INIT(&frags);
1789 		if ((m->m_flags & M_FRAG) &&
1790 		    !ath_txfrag_setup(sc, &frags, m, ni)) {
1791 			DPRINTF(sc, ATH_DEBUG_XMIT,
1792 			    "%s: out of txfrag buffers\n", __func__);
1793 			sc->sc_stats.ast_tx_nofrag++;
1794 			ifp->if_oerrors++;
1795 			ath_freetx(m);
1796 			goto bad;
1797 		}
1798 		ifp->if_opackets++;
1799 	nextfrag:
1800 		/*
1801 		 * Pass the frame to the h/w for transmission.
1802 		 * Fragmented frames have each frag chained together
1803 		 * with m_nextpkt.  We know there are sufficient ath_buf's
1804 		 * to send all the frags because of work done by
1805 		 * ath_txfrag_setup.  We leave m_nextpkt set while
1806 		 * calling ath_tx_start so it can use it to extend the
1807 		 * the tx duration to cover the subsequent frag and
1808 		 * so it can reclaim all the mbufs in case of an error;
1809 		 * ath_tx_start clears m_nextpkt once it commits to
1810 		 * handing the frame to the hardware.
1811 		 */
1812 		next = m->m_nextpkt;
1813 		if (ath_tx_start(sc, ni, bf, m)) {
1814 	bad:
1815 			ifp->if_oerrors++;
1816 	reclaim:
1817 			bf->bf_m = NULL;
1818 			bf->bf_node = NULL;
1819 			ATH_TXBUF_LOCK(sc);
1820 			STAILQ_INSERT_HEAD(&sc->sc_txbuf, bf, bf_list);
1821 			ath_txfrag_cleanup(sc, &frags, ni);
1822 			ATH_TXBUF_UNLOCK(sc);
1823 			if (ni != NULL)
1824 				ieee80211_free_node(ni);
1825 			continue;
1826 		}
1827 		if (next != NULL) {
1828 			/*
1829 			 * Beware of state changing between frags.
1830 			 * XXX check sta power-save state?
1831 			 */
1832 			if (ni->ni_vap->iv_state != IEEE80211_S_RUN) {
1833 				DPRINTF(sc, ATH_DEBUG_XMIT,
1834 				    "%s: flush fragmented packet, state %s\n",
1835 				    __func__,
1836 				    ieee80211_state_name[ni->ni_vap->iv_state]);
1837 				ath_freetx(next);
1838 				goto reclaim;
1839 			}
1840 			m = next;
1841 			bf = STAILQ_FIRST(&frags);
1842 			KASSERT(bf != NULL, ("no buf for txfrag"));
1843 			STAILQ_REMOVE_HEAD(&frags, bf_list);
1844 			goto nextfrag;
1845 		}
1846 
1847 		sc->sc_wd_timer = 5;
1848 	}
1849 }
1850 
1851 static int
1852 ath_media_change(struct ifnet *ifp)
1853 {
1854 	int error = ieee80211_media_change(ifp);
1855 	/* NB: only the fixed rate can change and that doesn't need a reset */
1856 	return (error == ENETRESET ? 0 : error);
1857 }
1858 
1859 /*
1860  * Block/unblock tx+rx processing while a key change is done.
1861  * We assume the caller serializes key management operations
1862  * so we only need to worry about synchronization with other
1863  * uses that originate in the driver.
1864  */
1865 static void
1866 ath_key_update_begin(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 	taskqueue_block(sc->sc_tq);
1873 	IF_LOCK(&ifp->if_snd);		/* NB: doesn't block mgmt frames */
1874 }
1875 
1876 static void
1877 ath_key_update_end(struct ieee80211vap *vap)
1878 {
1879 	struct ifnet *ifp = vap->iv_ic->ic_ifp;
1880 	struct ath_softc *sc = ifp->if_softc;
1881 
1882 	DPRINTF(sc, ATH_DEBUG_KEYCACHE, "%s:\n", __func__);
1883 	IF_UNLOCK(&ifp->if_snd);
1884 	taskqueue_unblock(sc->sc_tq);
1885 }
1886 
1887 /*
1888  * Calculate the receive filter according to the
1889  * operating mode and state:
1890  *
1891  * o always accept unicast, broadcast, and multicast traffic
1892  * o accept PHY error frames when hardware doesn't have MIB support
1893  *   to count and we need them for ANI (sta mode only until recently)
1894  *   and we are not scanning (ANI is disabled)
1895  *   NB: older hal's add rx filter bits out of sight and we need to
1896  *	 blindly preserve them
1897  * o probe request frames are accepted only when operating in
1898  *   hostap, adhoc, mesh, or monitor modes
1899  * o enable promiscuous mode
1900  *   - when in monitor mode
1901  *   - if interface marked PROMISC (assumes bridge setting is filtered)
1902  * o accept beacons:
1903  *   - when operating in station mode for collecting rssi data when
1904  *     the station is otherwise quiet, or
1905  *   - when operating in adhoc mode so the 802.11 layer creates
1906  *     node table entries for peers,
1907  *   - when scanning
1908  *   - when doing s/w beacon miss (e.g. for ap+sta)
1909  *   - when operating in ap mode in 11g to detect overlapping bss that
1910  *     require protection
1911  *   - when operating in mesh mode to detect neighbors
1912  * o accept control frames:
1913  *   - when in monitor mode
1914  * XXX HT protection for 11n
1915  */
1916 static u_int32_t
1917 ath_calcrxfilter(struct ath_softc *sc)
1918 {
1919 	struct ifnet *ifp = sc->sc_ifp;
1920 	struct ieee80211com *ic = ifp->if_l2com;
1921 	u_int32_t rfilt;
1922 
1923 	rfilt = HAL_RX_FILTER_UCAST | HAL_RX_FILTER_BCAST | HAL_RX_FILTER_MCAST;
1924 	if (!sc->sc_needmib && !sc->sc_scanning)
1925 		rfilt |= HAL_RX_FILTER_PHYERR;
1926 	if (ic->ic_opmode != IEEE80211_M_STA)
1927 		rfilt |= HAL_RX_FILTER_PROBEREQ;
1928 	/* XXX ic->ic_monvaps != 0? */
1929 	if (ic->ic_opmode == IEEE80211_M_MONITOR || (ifp->if_flags & IFF_PROMISC))
1930 		rfilt |= HAL_RX_FILTER_PROM;
1931 	if (ic->ic_opmode == IEEE80211_M_STA ||
1932 	    ic->ic_opmode == IEEE80211_M_IBSS ||
1933 	    sc->sc_swbmiss || sc->sc_scanning)
1934 		rfilt |= HAL_RX_FILTER_BEACON;
1935 	/*
1936 	 * NB: We don't recalculate the rx filter when
1937 	 * ic_protmode changes; otherwise we could do
1938 	 * this only when ic_protmode != NONE.
1939 	 */
1940 	if (ic->ic_opmode == IEEE80211_M_HOSTAP &&
1941 	    IEEE80211_IS_CHAN_ANYG(ic->ic_curchan))
1942 		rfilt |= HAL_RX_FILTER_BEACON;
1943 
1944 #if 0
1945 	/*
1946 	 * Enable hardware PS-POLL RX only for hostap mode;
1947 	 * STA mode sends PS-POLL frames but never
1948 	 * receives them.
1949 	 */
1950 	if (ath_hal_getcapability(ah, HAL_CAP_HAS_PSPOLL,
1951 	    0, NULL) == HAL_OK &&
1952 	    ic->ic_opmode == IEEE80211_M_HOSTAP)
1953 		rfilt |= HAL_RX_FILTER_PSPOLL;
1954 #endif
1955 
1956 	if (sc->sc_nmeshvaps) {
1957 		rfilt |= HAL_RX_FILTER_BEACON;
1958 		if (sc->sc_hasbmatch)
1959 			rfilt |= HAL_RX_FILTER_BSSID;
1960 		else
1961 			rfilt |= HAL_RX_FILTER_PROM;
1962 	}
1963 	if (ic->ic_opmode == IEEE80211_M_MONITOR)
1964 		rfilt |= HAL_RX_FILTER_CONTROL;
1965 
1966 	/*
1967 	 * Enable RX of compressed BAR frames only when doing
1968 	 * 802.11n. Required for A-MPDU.
1969 	 */
1970 	if (IEEE80211_IS_CHAN_HT(ic->ic_curchan))
1971 		rfilt |= HAL_RX_FILTER_COMPBAR;
1972 
1973 	DPRINTF(sc, ATH_DEBUG_MODE, "%s: RX filter 0x%x, %s if_flags 0x%x\n",
1974 	    __func__, rfilt, ieee80211_opmode_name[ic->ic_opmode], ifp->if_flags);
1975 	return rfilt;
1976 }
1977 
1978 static void
1979 ath_update_promisc(struct ifnet *ifp)
1980 {
1981 	struct ath_softc *sc = ifp->if_softc;
1982 	u_int32_t rfilt;
1983 
1984 	/* configure rx filter */
1985 	rfilt = ath_calcrxfilter(sc);
1986 	ath_hal_setrxfilter(sc->sc_ah, rfilt);
1987 
1988 	DPRINTF(sc, ATH_DEBUG_MODE, "%s: RX filter 0x%x\n", __func__, rfilt);
1989 }
1990 
1991 static void
1992 ath_update_mcast(struct ifnet *ifp)
1993 {
1994 	struct ath_softc *sc = ifp->if_softc;
1995 	u_int32_t mfilt[2];
1996 
1997 	/* calculate and install multicast filter */
1998 	if ((ifp->if_flags & IFF_ALLMULTI) == 0) {
1999 		struct ifmultiaddr *ifma;
2000 		/*
2001 		 * Merge multicast addresses to form the hardware filter.
2002 		 */
2003 		mfilt[0] = mfilt[1] = 0;
2004 		if_maddr_rlock(ifp);	/* XXX need some fiddling to remove? */
2005 		TAILQ_FOREACH(ifma, &ifp->if_multiaddrs, ifma_link) {
2006 			caddr_t dl;
2007 			u_int32_t val;
2008 			u_int8_t pos;
2009 
2010 			/* calculate XOR of eight 6bit values */
2011 			dl = LLADDR((struct sockaddr_dl *) ifma->ifma_addr);
2012 			val = LE_READ_4(dl + 0);
2013 			pos = (val >> 18) ^ (val >> 12) ^ (val >> 6) ^ val;
2014 			val = LE_READ_4(dl + 3);
2015 			pos ^= (val >> 18) ^ (val >> 12) ^ (val >> 6) ^ val;
2016 			pos &= 0x3f;
2017 			mfilt[pos / 32] |= (1 << (pos % 32));
2018 		}
2019 		if_maddr_runlock(ifp);
2020 	} else
2021 		mfilt[0] = mfilt[1] = ~0;
2022 	ath_hal_setmcastfilter(sc->sc_ah, mfilt[0], mfilt[1]);
2023 	DPRINTF(sc, ATH_DEBUG_MODE, "%s: MC filter %08x:%08x\n",
2024 		__func__, mfilt[0], mfilt[1]);
2025 }
2026 
2027 static void
2028 ath_mode_init(struct ath_softc *sc)
2029 {
2030 	struct ifnet *ifp = sc->sc_ifp;
2031 	struct ath_hal *ah = sc->sc_ah;
2032 	u_int32_t rfilt;
2033 
2034 	/* configure rx filter */
2035 	rfilt = ath_calcrxfilter(sc);
2036 	ath_hal_setrxfilter(ah, rfilt);
2037 
2038 	/* configure operational mode */
2039 	ath_hal_setopmode(ah);
2040 
2041 	/* handle any link-level address change */
2042 	ath_hal_setmac(ah, IF_LLADDR(ifp));
2043 
2044 	/* calculate and install multicast filter */
2045 	ath_update_mcast(ifp);
2046 }
2047 
2048 /*
2049  * Set the slot time based on the current setting.
2050  */
2051 static void
2052 ath_setslottime(struct ath_softc *sc)
2053 {
2054 	struct ieee80211com *ic = sc->sc_ifp->if_l2com;
2055 	struct ath_hal *ah = sc->sc_ah;
2056 	u_int usec;
2057 
2058 	if (IEEE80211_IS_CHAN_HALF(ic->ic_curchan))
2059 		usec = 13;
2060 	else if (IEEE80211_IS_CHAN_QUARTER(ic->ic_curchan))
2061 		usec = 21;
2062 	else if (IEEE80211_IS_CHAN_ANYG(ic->ic_curchan)) {
2063 		/* honor short/long slot time only in 11g */
2064 		/* XXX shouldn't honor on pure g or turbo g channel */
2065 		if (ic->ic_flags & IEEE80211_F_SHSLOT)
2066 			usec = HAL_SLOT_TIME_9;
2067 		else
2068 			usec = HAL_SLOT_TIME_20;
2069 	} else
2070 		usec = HAL_SLOT_TIME_9;
2071 
2072 	DPRINTF(sc, ATH_DEBUG_RESET,
2073 	    "%s: chan %u MHz flags 0x%x %s slot, %u usec\n",
2074 	    __func__, ic->ic_curchan->ic_freq, ic->ic_curchan->ic_flags,
2075 	    ic->ic_flags & IEEE80211_F_SHSLOT ? "short" : "long", usec);
2076 
2077 	ath_hal_setslottime(ah, usec);
2078 	sc->sc_updateslot = OK;
2079 }
2080 
2081 /*
2082  * Callback from the 802.11 layer to update the
2083  * slot time based on the current setting.
2084  */
2085 static void
2086 ath_updateslot(struct ifnet *ifp)
2087 {
2088 	struct ath_softc *sc = ifp->if_softc;
2089 	struct ieee80211com *ic = ifp->if_l2com;
2090 
2091 	/*
2092 	 * When not coordinating the BSS, change the hardware
2093 	 * immediately.  For other operation we defer the change
2094 	 * until beacon updates have propagated to the stations.
2095 	 */
2096 	if (ic->ic_opmode == IEEE80211_M_HOSTAP ||
2097 	    ic->ic_opmode == IEEE80211_M_MBSS)
2098 		sc->sc_updateslot = UPDATE;
2099 	else
2100 		ath_setslottime(sc);
2101 }
2102 
2103 /*
2104  * Setup a h/w transmit queue for beacons.
2105  */
2106 static int
2107 ath_beaconq_setup(struct ath_hal *ah)
2108 {
2109 	HAL_TXQ_INFO qi;
2110 
2111 	memset(&qi, 0, sizeof(qi));
2112 	qi.tqi_aifs = HAL_TXQ_USEDEFAULT;
2113 	qi.tqi_cwmin = HAL_TXQ_USEDEFAULT;
2114 	qi.tqi_cwmax = HAL_TXQ_USEDEFAULT;
2115 	/* NB: for dynamic turbo, don't enable any other interrupts */
2116 	qi.tqi_qflags = HAL_TXQ_TXDESCINT_ENABLE;
2117 	return ath_hal_setuptxqueue(ah, HAL_TX_QUEUE_BEACON, &qi);
2118 }
2119 
2120 /*
2121  * Setup the transmit queue parameters for the beacon queue.
2122  */
2123 static int
2124 ath_beaconq_config(struct ath_softc *sc)
2125 {
2126 #define	ATH_EXPONENT_TO_VALUE(v)	((1<<(v))-1)
2127 	struct ieee80211com *ic = sc->sc_ifp->if_l2com;
2128 	struct ath_hal *ah = sc->sc_ah;
2129 	HAL_TXQ_INFO qi;
2130 
2131 	ath_hal_gettxqueueprops(ah, sc->sc_bhalq, &qi);
2132 	if (ic->ic_opmode == IEEE80211_M_HOSTAP ||
2133 	    ic->ic_opmode == IEEE80211_M_MBSS) {
2134 		/*
2135 		 * Always burst out beacon and CAB traffic.
2136 		 */
2137 		qi.tqi_aifs = ATH_BEACON_AIFS_DEFAULT;
2138 		qi.tqi_cwmin = ATH_BEACON_CWMIN_DEFAULT;
2139 		qi.tqi_cwmax = ATH_BEACON_CWMAX_DEFAULT;
2140 	} else {
2141 		struct wmeParams *wmep =
2142 			&ic->ic_wme.wme_chanParams.cap_wmeParams[WME_AC_BE];
2143 		/*
2144 		 * Adhoc mode; important thing is to use 2x cwmin.
2145 		 */
2146 		qi.tqi_aifs = wmep->wmep_aifsn;
2147 		qi.tqi_cwmin = 2*ATH_EXPONENT_TO_VALUE(wmep->wmep_logcwmin);
2148 		qi.tqi_cwmax = ATH_EXPONENT_TO_VALUE(wmep->wmep_logcwmax);
2149 	}
2150 
2151 	if (!ath_hal_settxqueueprops(ah, sc->sc_bhalq, &qi)) {
2152 		device_printf(sc->sc_dev, "unable to update parameters for "
2153 			"beacon hardware queue!\n");
2154 		return 0;
2155 	} else {
2156 		ath_hal_resettxqueue(ah, sc->sc_bhalq); /* push to h/w */
2157 		return 1;
2158 	}
2159 #undef ATH_EXPONENT_TO_VALUE
2160 }
2161 
2162 /*
2163  * Allocate and setup an initial beacon frame.
2164  */
2165 static int
2166 ath_beacon_alloc(struct ath_softc *sc, struct ieee80211_node *ni)
2167 {
2168 	struct ieee80211vap *vap = ni->ni_vap;
2169 	struct ath_vap *avp = ATH_VAP(vap);
2170 	struct ath_buf *bf;
2171 	struct mbuf *m;
2172 	int error;
2173 
2174 	bf = avp->av_bcbuf;
2175 	if (bf->bf_m != NULL) {
2176 		bus_dmamap_unload(sc->sc_dmat, bf->bf_dmamap);
2177 		m_freem(bf->bf_m);
2178 		bf->bf_m = NULL;
2179 	}
2180 	if (bf->bf_node != NULL) {
2181 		ieee80211_free_node(bf->bf_node);
2182 		bf->bf_node = NULL;
2183 	}
2184 
2185 	/*
2186 	 * NB: the beacon data buffer must be 32-bit aligned;
2187 	 * we assume the mbuf routines will return us something
2188 	 * with this alignment (perhaps should assert).
2189 	 */
2190 	m = ieee80211_beacon_alloc(ni, &avp->av_boff);
2191 	if (m == NULL) {
2192 		device_printf(sc->sc_dev, "%s: cannot get mbuf\n", __func__);
2193 		sc->sc_stats.ast_be_nombuf++;
2194 		return ENOMEM;
2195 	}
2196 	error = bus_dmamap_load_mbuf_sg(sc->sc_dmat, bf->bf_dmamap, m,
2197 				     bf->bf_segs, &bf->bf_nseg,
2198 				     BUS_DMA_NOWAIT);
2199 	if (error != 0) {
2200 		device_printf(sc->sc_dev,
2201 		    "%s: cannot map mbuf, bus_dmamap_load_mbuf_sg returns %d\n",
2202 		    __func__, error);
2203 		m_freem(m);
2204 		return error;
2205 	}
2206 
2207 	/*
2208 	 * Calculate a TSF adjustment factor required for staggered
2209 	 * beacons.  Note that we assume the format of the beacon
2210 	 * frame leaves the tstamp field immediately following the
2211 	 * header.
2212 	 */
2213 	if (sc->sc_stagbeacons && avp->av_bslot > 0) {
2214 		uint64_t tsfadjust;
2215 		struct ieee80211_frame *wh;
2216 
2217 		/*
2218 		 * The beacon interval is in TU's; the TSF is in usecs.
2219 		 * We figure out how many TU's to add to align the timestamp
2220 		 * then convert to TSF units and handle byte swapping before
2221 		 * inserting it in the frame.  The hardware will then add this
2222 		 * each time a beacon frame is sent.  Note that we align vap's
2223 		 * 1..N and leave vap 0 untouched.  This means vap 0 has a
2224 		 * timestamp in one beacon interval while the others get a
2225 		 * timstamp aligned to the next interval.
2226 		 */
2227 		tsfadjust = ni->ni_intval *
2228 		    (ATH_BCBUF - avp->av_bslot) / ATH_BCBUF;
2229 		tsfadjust = htole64(tsfadjust << 10);	/* TU -> TSF */
2230 
2231 		DPRINTF(sc, ATH_DEBUG_BEACON,
2232 		    "%s: %s beacons bslot %d intval %u tsfadjust %llu\n",
2233 		    __func__, sc->sc_stagbeacons ? "stagger" : "burst",
2234 		    avp->av_bslot, ni->ni_intval,
2235 		    (long long unsigned) le64toh(tsfadjust));
2236 
2237 		wh = mtod(m, struct ieee80211_frame *);
2238 		memcpy(&wh[1], &tsfadjust, sizeof(tsfadjust));
2239 	}
2240 	bf->bf_m = m;
2241 	bf->bf_node = ieee80211_ref_node(ni);
2242 
2243 	return 0;
2244 }
2245 
2246 /*
2247  * Setup the beacon frame for transmit.
2248  */
2249 static void
2250 ath_beacon_setup(struct ath_softc *sc, struct ath_buf *bf)
2251 {
2252 #define	USE_SHPREAMBLE(_ic) \
2253 	(((_ic)->ic_flags & (IEEE80211_F_SHPREAMBLE | IEEE80211_F_USEBARKER))\
2254 		== IEEE80211_F_SHPREAMBLE)
2255 	struct ieee80211_node *ni = bf->bf_node;
2256 	struct ieee80211com *ic = ni->ni_ic;
2257 	struct mbuf *m = bf->bf_m;
2258 	struct ath_hal *ah = sc->sc_ah;
2259 	struct ath_desc *ds;
2260 	int flags, antenna;
2261 	const HAL_RATE_TABLE *rt;
2262 	u_int8_t rix, rate;
2263 
2264 	DPRINTF(sc, ATH_DEBUG_BEACON_PROC, "%s: m %p len %u\n",
2265 		__func__, m, m->m_len);
2266 
2267 	/* setup descriptors */
2268 	ds = bf->bf_desc;
2269 
2270 	flags = HAL_TXDESC_NOACK;
2271 	if (ic->ic_opmode == IEEE80211_M_IBSS && sc->sc_hasveol) {
2272 		ds->ds_link = bf->bf_daddr;	/* self-linked */
2273 		flags |= HAL_TXDESC_VEOL;
2274 		/*
2275 		 * Let hardware handle antenna switching.
2276 		 */
2277 		antenna = sc->sc_txantenna;
2278 	} else {
2279 		ds->ds_link = 0;
2280 		/*
2281 		 * Switch antenna every 4 beacons.
2282 		 * XXX assumes two antenna
2283 		 */
2284 		if (sc->sc_txantenna != 0)
2285 			antenna = sc->sc_txantenna;
2286 		else if (sc->sc_stagbeacons && sc->sc_nbcnvaps != 0)
2287 			antenna = ((sc->sc_stats.ast_be_xmit / sc->sc_nbcnvaps) & 4 ? 2 : 1);
2288 		else
2289 			antenna = (sc->sc_stats.ast_be_xmit & 4 ? 2 : 1);
2290 	}
2291 
2292 	KASSERT(bf->bf_nseg == 1,
2293 		("multi-segment beacon frame; nseg %u", bf->bf_nseg));
2294 	ds->ds_data = bf->bf_segs[0].ds_addr;
2295 	/*
2296 	 * Calculate rate code.
2297 	 * XXX everything at min xmit rate
2298 	 */
2299 	rix = 0;
2300 	rt = sc->sc_currates;
2301 	rate = rt->info[rix].rateCode;
2302 	if (USE_SHPREAMBLE(ic))
2303 		rate |= rt->info[rix].shortPreamble;
2304 	ath_hal_setuptxdesc(ah, ds
2305 		, m->m_len + IEEE80211_CRC_LEN	/* frame length */
2306 		, sizeof(struct ieee80211_frame)/* header length */
2307 		, HAL_PKT_TYPE_BEACON		/* Atheros packet type */
2308 		, ni->ni_txpower		/* txpower XXX */
2309 		, rate, 1			/* series 0 rate/tries */
2310 		, HAL_TXKEYIX_INVALID		/* no encryption */
2311 		, antenna			/* antenna mode */
2312 		, flags				/* no ack, veol for beacons */
2313 		, 0				/* rts/cts rate */
2314 		, 0				/* rts/cts duration */
2315 	);
2316 	/* NB: beacon's BufLen must be a multiple of 4 bytes */
2317 	ath_hal_filltxdesc(ah, ds
2318 		, roundup(m->m_len, 4)		/* buffer length */
2319 		, AH_TRUE			/* first segment */
2320 		, AH_TRUE			/* last segment */
2321 		, ds				/* first descriptor */
2322 	);
2323 #if 0
2324 	ath_desc_swap(ds);
2325 #endif
2326 #undef USE_SHPREAMBLE
2327 }
2328 
2329 static void
2330 ath_beacon_update(struct ieee80211vap *vap, int item)
2331 {
2332 	struct ieee80211_beacon_offsets *bo = &ATH_VAP(vap)->av_boff;
2333 
2334 	setbit(bo->bo_flags, item);
2335 }
2336 
2337 /*
2338  * Append the contents of src to dst; both queues
2339  * are assumed to be locked.
2340  */
2341 static void
2342 ath_txqmove(struct ath_txq *dst, struct ath_txq *src)
2343 {
2344 	STAILQ_CONCAT(&dst->axq_q, &src->axq_q);
2345 	dst->axq_link = src->axq_link;
2346 	src->axq_link = NULL;
2347 	dst->axq_depth += src->axq_depth;
2348 	src->axq_depth = 0;
2349 }
2350 
2351 /*
2352  * Transmit a beacon frame at SWBA.  Dynamic updates to the
2353  * frame contents are done as needed and the slot time is
2354  * also adjusted based on current state.
2355  */
2356 static void
2357 ath_beacon_proc(void *arg, int pending)
2358 {
2359 	struct ath_softc *sc = arg;
2360 	struct ath_hal *ah = sc->sc_ah;
2361 	struct ieee80211vap *vap;
2362 	struct ath_buf *bf;
2363 	int slot, otherant;
2364 	uint32_t bfaddr;
2365 
2366 	DPRINTF(sc, ATH_DEBUG_BEACON_PROC, "%s: pending %u\n",
2367 		__func__, pending);
2368 	/*
2369 	 * Check if the previous beacon has gone out.  If
2370 	 * not don't try to post another, skip this period
2371 	 * and wait for the next.  Missed beacons indicate
2372 	 * a problem and should not occur.  If we miss too
2373 	 * many consecutive beacons reset the device.
2374 	 */
2375 	if (ath_hal_numtxpending(ah, sc->sc_bhalq) != 0) {
2376 		sc->sc_bmisscount++;
2377 		sc->sc_stats.ast_be_missed++;
2378 		DPRINTF(sc, ATH_DEBUG_BEACON,
2379 			"%s: missed %u consecutive beacons\n",
2380 			__func__, sc->sc_bmisscount);
2381 		if (sc->sc_bmisscount >= ath_bstuck_threshold)
2382 			taskqueue_enqueue(sc->sc_tq, &sc->sc_bstucktask);
2383 		return;
2384 	}
2385 	if (sc->sc_bmisscount != 0) {
2386 		DPRINTF(sc, ATH_DEBUG_BEACON,
2387 			"%s: resume beacon xmit after %u misses\n",
2388 			__func__, sc->sc_bmisscount);
2389 		sc->sc_bmisscount = 0;
2390 	}
2391 
2392 	if (sc->sc_stagbeacons) {			/* staggered beacons */
2393 		struct ieee80211com *ic = sc->sc_ifp->if_l2com;
2394 		uint32_t tsftu;
2395 
2396 		tsftu = ath_hal_gettsf32(ah) >> 10;
2397 		/* XXX lintval */
2398 		slot = ((tsftu % ic->ic_lintval) * ATH_BCBUF) / ic->ic_lintval;
2399 		vap = sc->sc_bslot[(slot+1) % ATH_BCBUF];
2400 		bfaddr = 0;
2401 		if (vap != NULL && vap->iv_state >= IEEE80211_S_RUN) {
2402 			bf = ath_beacon_generate(sc, vap);
2403 			if (bf != NULL)
2404 				bfaddr = bf->bf_daddr;
2405 		}
2406 	} else {					/* burst'd beacons */
2407 		uint32_t *bflink = &bfaddr;
2408 
2409 		for (slot = 0; slot < ATH_BCBUF; slot++) {
2410 			vap = sc->sc_bslot[slot];
2411 			if (vap != NULL && vap->iv_state >= IEEE80211_S_RUN) {
2412 				bf = ath_beacon_generate(sc, vap);
2413 				if (bf != NULL) {
2414 					*bflink = bf->bf_daddr;
2415 					bflink = &bf->bf_desc->ds_link;
2416 				}
2417 			}
2418 		}
2419 		*bflink = 0;				/* terminate list */
2420 	}
2421 
2422 	/*
2423 	 * Handle slot time change when a non-ERP station joins/leaves
2424 	 * an 11g network.  The 802.11 layer notifies us via callback,
2425 	 * we mark updateslot, then wait one beacon before effecting
2426 	 * the change.  This gives associated stations at least one
2427 	 * beacon interval to note the state change.
2428 	 */
2429 	/* XXX locking */
2430 	if (sc->sc_updateslot == UPDATE) {
2431 		sc->sc_updateslot = COMMIT;	/* commit next beacon */
2432 		sc->sc_slotupdate = slot;
2433 	} else if (sc->sc_updateslot == COMMIT && sc->sc_slotupdate == slot)
2434 		ath_setslottime(sc);		/* commit change to h/w */
2435 
2436 	/*
2437 	 * Check recent per-antenna transmit statistics and flip
2438 	 * the default antenna if noticeably more frames went out
2439 	 * on the non-default antenna.
2440 	 * XXX assumes 2 anntenae
2441 	 */
2442 	if (!sc->sc_diversity && (!sc->sc_stagbeacons || slot == 0)) {
2443 		otherant = sc->sc_defant & 1 ? 2 : 1;
2444 		if (sc->sc_ant_tx[otherant] > sc->sc_ant_tx[sc->sc_defant] + 2)
2445 			ath_setdefantenna(sc, otherant);
2446 		sc->sc_ant_tx[1] = sc->sc_ant_tx[2] = 0;
2447 	}
2448 
2449 	if (bfaddr != 0) {
2450 		/*
2451 		 * Stop any current dma and put the new frame on the queue.
2452 		 * This should never fail since we check above that no frames
2453 		 * are still pending on the queue.
2454 		 */
2455 		if (!ath_hal_stoptxdma(ah, sc->sc_bhalq)) {
2456 			DPRINTF(sc, ATH_DEBUG_ANY,
2457 				"%s: beacon queue %u did not stop?\n",
2458 				__func__, sc->sc_bhalq);
2459 		}
2460 		/* NB: cabq traffic should already be queued and primed */
2461 		ath_hal_puttxbuf(ah, sc->sc_bhalq, bfaddr);
2462 		ath_hal_txstart(ah, sc->sc_bhalq);
2463 
2464 		sc->sc_stats.ast_be_xmit++;
2465 	}
2466 }
2467 
2468 static struct ath_buf *
2469 ath_beacon_generate(struct ath_softc *sc, struct ieee80211vap *vap)
2470 {
2471 	struct ath_vap *avp = ATH_VAP(vap);
2472 	struct ath_txq *cabq = sc->sc_cabq;
2473 	struct ath_buf *bf;
2474 	struct mbuf *m;
2475 	int nmcastq, error;
2476 
2477 	KASSERT(vap->iv_state >= IEEE80211_S_RUN,
2478 	    ("not running, state %d", vap->iv_state));
2479 	KASSERT(avp->av_bcbuf != NULL, ("no beacon buffer"));
2480 
2481 	/*
2482 	 * Update dynamic beacon contents.  If this returns
2483 	 * non-zero then we need to remap the memory because
2484 	 * the beacon frame changed size (probably because
2485 	 * of the TIM bitmap).
2486 	 */
2487 	bf = avp->av_bcbuf;
2488 	m = bf->bf_m;
2489 	nmcastq = avp->av_mcastq.axq_depth;
2490 	if (ieee80211_beacon_update(bf->bf_node, &avp->av_boff, m, nmcastq)) {
2491 		/* XXX too conservative? */
2492 		bus_dmamap_unload(sc->sc_dmat, bf->bf_dmamap);
2493 		error = bus_dmamap_load_mbuf_sg(sc->sc_dmat, bf->bf_dmamap, m,
2494 					     bf->bf_segs, &bf->bf_nseg,
2495 					     BUS_DMA_NOWAIT);
2496 		if (error != 0) {
2497 			if_printf(vap->iv_ifp,
2498 			    "%s: bus_dmamap_load_mbuf_sg failed, error %u\n",
2499 			    __func__, error);
2500 			return NULL;
2501 		}
2502 	}
2503 	if ((avp->av_boff.bo_tim[4] & 1) && cabq->axq_depth) {
2504 		DPRINTF(sc, ATH_DEBUG_BEACON,
2505 		    "%s: cabq did not drain, mcastq %u cabq %u\n",
2506 		    __func__, nmcastq, cabq->axq_depth);
2507 		sc->sc_stats.ast_cabq_busy++;
2508 		if (sc->sc_nvaps > 1 && sc->sc_stagbeacons) {
2509 			/*
2510 			 * CABQ traffic from a previous vap is still pending.
2511 			 * We must drain the q before this beacon frame goes
2512 			 * out as otherwise this vap's stations will get cab
2513 			 * frames from a different vap.
2514 			 * XXX could be slow causing us to miss DBA
2515 			 */
2516 			ath_tx_draintxq(sc, cabq);
2517 		}
2518 	}
2519 	ath_beacon_setup(sc, bf);
2520 	bus_dmamap_sync(sc->sc_dmat, bf->bf_dmamap, BUS_DMASYNC_PREWRITE);
2521 
2522 	/*
2523 	 * Enable the CAB queue before the beacon queue to
2524 	 * insure cab frames are triggered by this beacon.
2525 	 */
2526 	if (avp->av_boff.bo_tim[4] & 1) {
2527 		struct ath_hal *ah = sc->sc_ah;
2528 
2529 		/* NB: only at DTIM */
2530 		ATH_TXQ_LOCK(cabq);
2531 		ATH_TXQ_LOCK(&avp->av_mcastq);
2532 		if (nmcastq) {
2533 			struct ath_buf *bfm;
2534 
2535 			/*
2536 			 * Move frames from the s/w mcast q to the h/w cab q.
2537 			 * XXX MORE_DATA bit
2538 			 */
2539 			bfm = STAILQ_FIRST(&avp->av_mcastq.axq_q);
2540 			if (cabq->axq_link != NULL) {
2541 				*cabq->axq_link = bfm->bf_daddr;
2542 			} else
2543 				ath_hal_puttxbuf(ah, cabq->axq_qnum,
2544 					bfm->bf_daddr);
2545 			ath_txqmove(cabq, &avp->av_mcastq);
2546 
2547 			sc->sc_stats.ast_cabq_xmit += nmcastq;
2548 		}
2549 		/* NB: gated by beacon so safe to start here */
2550 		ath_hal_txstart(ah, cabq->axq_qnum);
2551 		ATH_TXQ_UNLOCK(cabq);
2552 		ATH_TXQ_UNLOCK(&avp->av_mcastq);
2553 	}
2554 	return bf;
2555 }
2556 
2557 static void
2558 ath_beacon_start_adhoc(struct ath_softc *sc, struct ieee80211vap *vap)
2559 {
2560 	struct ath_vap *avp = ATH_VAP(vap);
2561 	struct ath_hal *ah = sc->sc_ah;
2562 	struct ath_buf *bf;
2563 	struct mbuf *m;
2564 	int error;
2565 
2566 	KASSERT(avp->av_bcbuf != NULL, ("no beacon buffer"));
2567 
2568 	/*
2569 	 * Update dynamic beacon contents.  If this returns
2570 	 * non-zero then we need to remap the memory because
2571 	 * the beacon frame changed size (probably because
2572 	 * of the TIM bitmap).
2573 	 */
2574 	bf = avp->av_bcbuf;
2575 	m = bf->bf_m;
2576 	if (ieee80211_beacon_update(bf->bf_node, &avp->av_boff, m, 0)) {
2577 		/* XXX too conservative? */
2578 		bus_dmamap_unload(sc->sc_dmat, bf->bf_dmamap);
2579 		error = bus_dmamap_load_mbuf_sg(sc->sc_dmat, bf->bf_dmamap, m,
2580 					     bf->bf_segs, &bf->bf_nseg,
2581 					     BUS_DMA_NOWAIT);
2582 		if (error != 0) {
2583 			if_printf(vap->iv_ifp,
2584 			    "%s: bus_dmamap_load_mbuf_sg failed, error %u\n",
2585 			    __func__, error);
2586 			return;
2587 		}
2588 	}
2589 	ath_beacon_setup(sc, bf);
2590 	bus_dmamap_sync(sc->sc_dmat, bf->bf_dmamap, BUS_DMASYNC_PREWRITE);
2591 
2592 	/* NB: caller is known to have already stopped tx dma */
2593 	ath_hal_puttxbuf(ah, sc->sc_bhalq, bf->bf_daddr);
2594 	ath_hal_txstart(ah, sc->sc_bhalq);
2595 }
2596 
2597 /*
2598  * Reset the hardware after detecting beacons have stopped.
2599  */
2600 static void
2601 ath_bstuck_proc(void *arg, int pending)
2602 {
2603 	struct ath_softc *sc = arg;
2604 	struct ifnet *ifp = sc->sc_ifp;
2605 
2606 	if_printf(ifp, "stuck beacon; resetting (bmiss count %u)\n",
2607 		sc->sc_bmisscount);
2608 	sc->sc_stats.ast_bstuck++;
2609 	ath_reset(ifp);
2610 }
2611 
2612 /*
2613  * Reclaim beacon resources and return buffer to the pool.
2614  */
2615 static void
2616 ath_beacon_return(struct ath_softc *sc, struct ath_buf *bf)
2617 {
2618 
2619 	if (bf->bf_m != NULL) {
2620 		bus_dmamap_unload(sc->sc_dmat, bf->bf_dmamap);
2621 		m_freem(bf->bf_m);
2622 		bf->bf_m = NULL;
2623 	}
2624 	if (bf->bf_node != NULL) {
2625 		ieee80211_free_node(bf->bf_node);
2626 		bf->bf_node = NULL;
2627 	}
2628 	STAILQ_INSERT_TAIL(&sc->sc_bbuf, bf, bf_list);
2629 }
2630 
2631 /*
2632  * Reclaim beacon resources.
2633  */
2634 static void
2635 ath_beacon_free(struct ath_softc *sc)
2636 {
2637 	struct ath_buf *bf;
2638 
2639 	STAILQ_FOREACH(bf, &sc->sc_bbuf, bf_list) {
2640 		if (bf->bf_m != NULL) {
2641 			bus_dmamap_unload(sc->sc_dmat, bf->bf_dmamap);
2642 			m_freem(bf->bf_m);
2643 			bf->bf_m = NULL;
2644 		}
2645 		if (bf->bf_node != NULL) {
2646 			ieee80211_free_node(bf->bf_node);
2647 			bf->bf_node = NULL;
2648 		}
2649 	}
2650 }
2651 
2652 /*
2653  * Configure the beacon and sleep timers.
2654  *
2655  * When operating as an AP this resets the TSF and sets
2656  * up the hardware to notify us when we need to issue beacons.
2657  *
2658  * When operating in station mode this sets up the beacon
2659  * timers according to the timestamp of the last received
2660  * beacon and the current TSF, configures PCF and DTIM
2661  * handling, programs the sleep registers so the hardware
2662  * will wakeup in time to receive beacons, and configures
2663  * the beacon miss handling so we'll receive a BMISS
2664  * interrupt when we stop seeing beacons from the AP
2665  * we've associated with.
2666  */
2667 static void
2668 ath_beacon_config(struct ath_softc *sc, struct ieee80211vap *vap)
2669 {
2670 #define	TSF_TO_TU(_h,_l) \
2671 	((((u_int32_t)(_h)) << 22) | (((u_int32_t)(_l)) >> 10))
2672 #define	FUDGE	2
2673 	struct ath_hal *ah = sc->sc_ah;
2674 	struct ieee80211com *ic = sc->sc_ifp->if_l2com;
2675 	struct ieee80211_node *ni;
2676 	u_int32_t nexttbtt, intval, tsftu;
2677 	u_int64_t tsf;
2678 
2679 	if (vap == NULL)
2680 		vap = TAILQ_FIRST(&ic->ic_vaps);	/* XXX */
2681 	ni = vap->iv_bss;
2682 
2683 	/* extract tstamp from last beacon and convert to TU */
2684 	nexttbtt = TSF_TO_TU(LE_READ_4(ni->ni_tstamp.data + 4),
2685 			     LE_READ_4(ni->ni_tstamp.data));
2686 	if (ic->ic_opmode == IEEE80211_M_HOSTAP ||
2687 	    ic->ic_opmode == IEEE80211_M_MBSS) {
2688 		/*
2689 		 * For multi-bss ap/mesh support beacons are either staggered
2690 		 * evenly over N slots or burst together.  For the former
2691 		 * arrange for the SWBA to be delivered for each slot.
2692 		 * Slots that are not occupied will generate nothing.
2693 		 */
2694 		/* NB: the beacon interval is kept internally in TU's */
2695 		intval = ni->ni_intval & HAL_BEACON_PERIOD;
2696 		if (sc->sc_stagbeacons)
2697 			intval /= ATH_BCBUF;
2698 	} else {
2699 		/* NB: the beacon interval is kept internally in TU's */
2700 		intval = ni->ni_intval & HAL_BEACON_PERIOD;
2701 	}
2702 	if (nexttbtt == 0)		/* e.g. for ap mode */
2703 		nexttbtt = intval;
2704 	else if (intval)		/* NB: can be 0 for monitor mode */
2705 		nexttbtt = roundup(nexttbtt, intval);
2706 	DPRINTF(sc, ATH_DEBUG_BEACON, "%s: nexttbtt %u intval %u (%u)\n",
2707 		__func__, nexttbtt, intval, ni->ni_intval);
2708 	if (ic->ic_opmode == IEEE80211_M_STA && !sc->sc_swbmiss) {
2709 		HAL_BEACON_STATE bs;
2710 		int dtimperiod, dtimcount;
2711 		int cfpperiod, cfpcount;
2712 
2713 		/*
2714 		 * Setup dtim and cfp parameters according to
2715 		 * last beacon we received (which may be none).
2716 		 */
2717 		dtimperiod = ni->ni_dtim_period;
2718 		if (dtimperiod <= 0)		/* NB: 0 if not known */
2719 			dtimperiod = 1;
2720 		dtimcount = ni->ni_dtim_count;
2721 		if (dtimcount >= dtimperiod)	/* NB: sanity check */
2722 			dtimcount = 0;		/* XXX? */
2723 		cfpperiod = 1;			/* NB: no PCF support yet */
2724 		cfpcount = 0;
2725 		/*
2726 		 * Pull nexttbtt forward to reflect the current
2727 		 * TSF and calculate dtim+cfp state for the result.
2728 		 */
2729 		tsf = ath_hal_gettsf64(ah);
2730 		tsftu = TSF_TO_TU(tsf>>32, tsf) + FUDGE;
2731 		do {
2732 			nexttbtt += intval;
2733 			if (--dtimcount < 0) {
2734 				dtimcount = dtimperiod - 1;
2735 				if (--cfpcount < 0)
2736 					cfpcount = cfpperiod - 1;
2737 			}
2738 		} while (nexttbtt < tsftu);
2739 		memset(&bs, 0, sizeof(bs));
2740 		bs.bs_intval = intval;
2741 		bs.bs_nexttbtt = nexttbtt;
2742 		bs.bs_dtimperiod = dtimperiod*intval;
2743 		bs.bs_nextdtim = bs.bs_nexttbtt + dtimcount*intval;
2744 		bs.bs_cfpperiod = cfpperiod*bs.bs_dtimperiod;
2745 		bs.bs_cfpnext = bs.bs_nextdtim + cfpcount*bs.bs_dtimperiod;
2746 		bs.bs_cfpmaxduration = 0;
2747 #if 0
2748 		/*
2749 		 * The 802.11 layer records the offset to the DTIM
2750 		 * bitmap while receiving beacons; use it here to
2751 		 * enable h/w detection of our AID being marked in
2752 		 * the bitmap vector (to indicate frames for us are
2753 		 * pending at the AP).
2754 		 * XXX do DTIM handling in s/w to WAR old h/w bugs
2755 		 * XXX enable based on h/w rev for newer chips
2756 		 */
2757 		bs.bs_timoffset = ni->ni_timoff;
2758 #endif
2759 		/*
2760 		 * Calculate the number of consecutive beacons to miss
2761 		 * before taking a BMISS interrupt.
2762 		 * Note that we clamp the result to at most 10 beacons.
2763 		 */
2764 		bs.bs_bmissthreshold = vap->iv_bmissthreshold;
2765 		if (bs.bs_bmissthreshold > 10)
2766 			bs.bs_bmissthreshold = 10;
2767 		else if (bs.bs_bmissthreshold <= 0)
2768 			bs.bs_bmissthreshold = 1;
2769 
2770 		/*
2771 		 * Calculate sleep duration.  The configuration is
2772 		 * given in ms.  We insure a multiple of the beacon
2773 		 * period is used.  Also, if the sleep duration is
2774 		 * greater than the DTIM period then it makes senses
2775 		 * to make it a multiple of that.
2776 		 *
2777 		 * XXX fixed at 100ms
2778 		 */
2779 		bs.bs_sleepduration =
2780 			roundup(IEEE80211_MS_TO_TU(100), bs.bs_intval);
2781 		if (bs.bs_sleepduration > bs.bs_dtimperiod)
2782 			bs.bs_sleepduration = roundup(bs.bs_sleepduration, bs.bs_dtimperiod);
2783 
2784 		DPRINTF(sc, ATH_DEBUG_BEACON,
2785 			"%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"
2786 			, __func__
2787 			, tsf, tsftu
2788 			, bs.bs_intval
2789 			, bs.bs_nexttbtt
2790 			, bs.bs_dtimperiod
2791 			, bs.bs_nextdtim
2792 			, bs.bs_bmissthreshold
2793 			, bs.bs_sleepduration
2794 			, bs.bs_cfpperiod
2795 			, bs.bs_cfpmaxduration
2796 			, bs.bs_cfpnext
2797 			, bs.bs_timoffset
2798 		);
2799 		ath_hal_intrset(ah, 0);
2800 		ath_hal_beacontimers(ah, &bs);
2801 		sc->sc_imask |= HAL_INT_BMISS;
2802 		ath_hal_intrset(ah, sc->sc_imask);
2803 	} else {
2804 		ath_hal_intrset(ah, 0);
2805 		if (nexttbtt == intval)
2806 			intval |= HAL_BEACON_RESET_TSF;
2807 		if (ic->ic_opmode == IEEE80211_M_IBSS) {
2808 			/*
2809 			 * In IBSS mode enable the beacon timers but only
2810 			 * enable SWBA interrupts if we need to manually
2811 			 * prepare beacon frames.  Otherwise we use a
2812 			 * self-linked tx descriptor and let the hardware
2813 			 * deal with things.
2814 			 */
2815 			intval |= HAL_BEACON_ENA;
2816 			if (!sc->sc_hasveol)
2817 				sc->sc_imask |= HAL_INT_SWBA;
2818 			if ((intval & HAL_BEACON_RESET_TSF) == 0) {
2819 				/*
2820 				 * Pull nexttbtt forward to reflect
2821 				 * the current TSF.
2822 				 */
2823 				tsf = ath_hal_gettsf64(ah);
2824 				tsftu = TSF_TO_TU(tsf>>32, tsf) + FUDGE;
2825 				do {
2826 					nexttbtt += intval;
2827 				} while (nexttbtt < tsftu);
2828 			}
2829 			ath_beaconq_config(sc);
2830 		} else if (ic->ic_opmode == IEEE80211_M_HOSTAP ||
2831 		    ic->ic_opmode == IEEE80211_M_MBSS) {
2832 			/*
2833 			 * In AP/mesh mode we enable the beacon timers
2834 			 * and SWBA interrupts to prepare beacon frames.
2835 			 */
2836 			intval |= HAL_BEACON_ENA;
2837 			sc->sc_imask |= HAL_INT_SWBA;	/* beacon prepare */
2838 			ath_beaconq_config(sc);
2839 		}
2840 		ath_hal_beaconinit(ah, nexttbtt, intval);
2841 		sc->sc_bmisscount = 0;
2842 		ath_hal_intrset(ah, sc->sc_imask);
2843 		/*
2844 		 * When using a self-linked beacon descriptor in
2845 		 * ibss mode load it once here.
2846 		 */
2847 		if (ic->ic_opmode == IEEE80211_M_IBSS && sc->sc_hasveol)
2848 			ath_beacon_start_adhoc(sc, vap);
2849 	}
2850 	sc->sc_syncbeacon = 0;
2851 #undef FUDGE
2852 #undef TSF_TO_TU
2853 }
2854 
2855 static void
2856 ath_load_cb(void *arg, bus_dma_segment_t *segs, int nsegs, int error)
2857 {
2858 	bus_addr_t *paddr = (bus_addr_t*) arg;
2859 	KASSERT(error == 0, ("error %u on bus_dma callback", error));
2860 	*paddr = segs->ds_addr;
2861 }
2862 
2863 static int
2864 ath_descdma_setup(struct ath_softc *sc,
2865 	struct ath_descdma *dd, ath_bufhead *head,
2866 	const char *name, int nbuf, int ndesc)
2867 {
2868 #define	DS2PHYS(_dd, _ds) \
2869 	((_dd)->dd_desc_paddr + ((caddr_t)(_ds) - (caddr_t)(_dd)->dd_desc))
2870 	struct ifnet *ifp = sc->sc_ifp;
2871 	struct ath_desc *ds;
2872 	struct ath_buf *bf;
2873 	int i, bsize, error;
2874 
2875 	DPRINTF(sc, ATH_DEBUG_RESET, "%s: %s DMA: %u buffers %u desc/buf\n",
2876 	    __func__, name, nbuf, ndesc);
2877 
2878 	dd->dd_name = name;
2879 	dd->dd_desc_len = sizeof(struct ath_desc) * nbuf * ndesc;
2880 
2881 	/*
2882 	 * Setup DMA descriptor area.
2883 	 */
2884 	error = bus_dma_tag_create(bus_get_dma_tag(sc->sc_dev),	/* parent */
2885 		       PAGE_SIZE, 0,		/* alignment, bounds */
2886 		       BUS_SPACE_MAXADDR_32BIT,	/* lowaddr */
2887 		       BUS_SPACE_MAXADDR,	/* highaddr */
2888 		       NULL, NULL,		/* filter, filterarg */
2889 		       dd->dd_desc_len,		/* maxsize */
2890 		       1,			/* nsegments */
2891 		       dd->dd_desc_len,		/* maxsegsize */
2892 		       BUS_DMA_ALLOCNOW,	/* flags */
2893 		       NULL,			/* lockfunc */
2894 		       NULL,			/* lockarg */
2895 		       &dd->dd_dmat);
2896 	if (error != 0) {
2897 		if_printf(ifp, "cannot allocate %s DMA tag\n", dd->dd_name);
2898 		return error;
2899 	}
2900 
2901 	/* allocate descriptors */
2902 	error = bus_dmamap_create(dd->dd_dmat, BUS_DMA_NOWAIT, &dd->dd_dmamap);
2903 	if (error != 0) {
2904 		if_printf(ifp, "unable to create dmamap for %s descriptors, "
2905 			"error %u\n", dd->dd_name, error);
2906 		goto fail0;
2907 	}
2908 
2909 	error = bus_dmamem_alloc(dd->dd_dmat, (void**) &dd->dd_desc,
2910 				 BUS_DMA_NOWAIT | BUS_DMA_COHERENT,
2911 				 &dd->dd_dmamap);
2912 	if (error != 0) {
2913 		if_printf(ifp, "unable to alloc memory for %u %s descriptors, "
2914 			"error %u\n", nbuf * ndesc, dd->dd_name, error);
2915 		goto fail1;
2916 	}
2917 
2918 	error = bus_dmamap_load(dd->dd_dmat, dd->dd_dmamap,
2919 				dd->dd_desc, dd->dd_desc_len,
2920 				ath_load_cb, &dd->dd_desc_paddr,
2921 				BUS_DMA_NOWAIT);
2922 	if (error != 0) {
2923 		if_printf(ifp, "unable to map %s descriptors, error %u\n",
2924 			dd->dd_name, error);
2925 		goto fail2;
2926 	}
2927 
2928 	ds = dd->dd_desc;
2929 	DPRINTF(sc, ATH_DEBUG_RESET, "%s: %s DMA map: %p (%lu) -> %p (%lu)\n",
2930 	    __func__, dd->dd_name, ds, (u_long) dd->dd_desc_len,
2931 	    (caddr_t) dd->dd_desc_paddr, /*XXX*/ (u_long) dd->dd_desc_len);
2932 
2933 	/* allocate rx buffers */
2934 	bsize = sizeof(struct ath_buf) * nbuf;
2935 	bf = malloc(bsize, M_ATHDEV, M_NOWAIT | M_ZERO);
2936 	if (bf == NULL) {
2937 		if_printf(ifp, "malloc of %s buffers failed, size %u\n",
2938 			dd->dd_name, bsize);
2939 		goto fail3;
2940 	}
2941 	dd->dd_bufptr = bf;
2942 
2943 	STAILQ_INIT(head);
2944 	for (i = 0; i < nbuf; i++, bf++, ds += ndesc) {
2945 		bf->bf_desc = ds;
2946 		bf->bf_daddr = DS2PHYS(dd, ds);
2947 		error = bus_dmamap_create(sc->sc_dmat, BUS_DMA_NOWAIT,
2948 				&bf->bf_dmamap);
2949 		if (error != 0) {
2950 			if_printf(ifp, "unable to create dmamap for %s "
2951 				"buffer %u, error %u\n", dd->dd_name, i, error);
2952 			ath_descdma_cleanup(sc, dd, head);
2953 			return error;
2954 		}
2955 		STAILQ_INSERT_TAIL(head, bf, bf_list);
2956 	}
2957 	return 0;
2958 fail3:
2959 	bus_dmamap_unload(dd->dd_dmat, dd->dd_dmamap);
2960 fail2:
2961 	bus_dmamem_free(dd->dd_dmat, dd->dd_desc, dd->dd_dmamap);
2962 fail1:
2963 	bus_dmamap_destroy(dd->dd_dmat, dd->dd_dmamap);
2964 fail0:
2965 	bus_dma_tag_destroy(dd->dd_dmat);
2966 	memset(dd, 0, sizeof(*dd));
2967 	return error;
2968 #undef DS2PHYS
2969 }
2970 
2971 static void
2972 ath_descdma_cleanup(struct ath_softc *sc,
2973 	struct ath_descdma *dd, ath_bufhead *head)
2974 {
2975 	struct ath_buf *bf;
2976 	struct ieee80211_node *ni;
2977 
2978 	bus_dmamap_unload(dd->dd_dmat, dd->dd_dmamap);
2979 	bus_dmamem_free(dd->dd_dmat, dd->dd_desc, dd->dd_dmamap);
2980 	bus_dmamap_destroy(dd->dd_dmat, dd->dd_dmamap);
2981 	bus_dma_tag_destroy(dd->dd_dmat);
2982 
2983 	STAILQ_FOREACH(bf, head, bf_list) {
2984 		if (bf->bf_m) {
2985 			m_freem(bf->bf_m);
2986 			bf->bf_m = NULL;
2987 		}
2988 		if (bf->bf_dmamap != NULL) {
2989 			bus_dmamap_destroy(sc->sc_dmat, bf->bf_dmamap);
2990 			bf->bf_dmamap = NULL;
2991 		}
2992 		ni = bf->bf_node;
2993 		bf->bf_node = NULL;
2994 		if (ni != NULL) {
2995 			/*
2996 			 * Reclaim node reference.
2997 			 */
2998 			ieee80211_free_node(ni);
2999 		}
3000 	}
3001 
3002 	STAILQ_INIT(head);
3003 	free(dd->dd_bufptr, M_ATHDEV);
3004 	memset(dd, 0, sizeof(*dd));
3005 }
3006 
3007 static int
3008 ath_desc_alloc(struct ath_softc *sc)
3009 {
3010 	int error;
3011 
3012 	error = ath_descdma_setup(sc, &sc->sc_rxdma, &sc->sc_rxbuf,
3013 			"rx", ath_rxbuf, 1);
3014 	if (error != 0)
3015 		return error;
3016 
3017 	error = ath_descdma_setup(sc, &sc->sc_txdma, &sc->sc_txbuf,
3018 			"tx", ath_txbuf, ATH_TXDESC);
3019 	if (error != 0) {
3020 		ath_descdma_cleanup(sc, &sc->sc_rxdma, &sc->sc_rxbuf);
3021 		return error;
3022 	}
3023 
3024 	error = ath_descdma_setup(sc, &sc->sc_bdma, &sc->sc_bbuf,
3025 			"beacon", ATH_BCBUF, 1);
3026 	if (error != 0) {
3027 		ath_descdma_cleanup(sc, &sc->sc_txdma, &sc->sc_txbuf);
3028 		ath_descdma_cleanup(sc, &sc->sc_rxdma, &sc->sc_rxbuf);
3029 		return error;
3030 	}
3031 	return 0;
3032 }
3033 
3034 static void
3035 ath_desc_free(struct ath_softc *sc)
3036 {
3037 
3038 	if (sc->sc_bdma.dd_desc_len != 0)
3039 		ath_descdma_cleanup(sc, &sc->sc_bdma, &sc->sc_bbuf);
3040 	if (sc->sc_txdma.dd_desc_len != 0)
3041 		ath_descdma_cleanup(sc, &sc->sc_txdma, &sc->sc_txbuf);
3042 	if (sc->sc_rxdma.dd_desc_len != 0)
3043 		ath_descdma_cleanup(sc, &sc->sc_rxdma, &sc->sc_rxbuf);
3044 }
3045 
3046 static struct ieee80211_node *
3047 ath_node_alloc(struct ieee80211vap *vap, const uint8_t mac[IEEE80211_ADDR_LEN])
3048 {
3049 	struct ieee80211com *ic = vap->iv_ic;
3050 	struct ath_softc *sc = ic->ic_ifp->if_softc;
3051 	const size_t space = sizeof(struct ath_node) + sc->sc_rc->arc_space;
3052 	struct ath_node *an;
3053 
3054 	an = malloc(space, M_80211_NODE, M_NOWAIT|M_ZERO);
3055 	if (an == NULL) {
3056 		/* XXX stat+msg */
3057 		return NULL;
3058 	}
3059 	ath_rate_node_init(sc, an);
3060 
3061 	DPRINTF(sc, ATH_DEBUG_NODE, "%s: an %p\n", __func__, an);
3062 	return &an->an_node;
3063 }
3064 
3065 static void
3066 ath_node_free(struct ieee80211_node *ni)
3067 {
3068 	struct ieee80211com *ic = ni->ni_ic;
3069         struct ath_softc *sc = ic->ic_ifp->if_softc;
3070 
3071 	DPRINTF(sc, ATH_DEBUG_NODE, "%s: ni %p\n", __func__, ni);
3072 
3073 	ath_rate_node_cleanup(sc, ATH_NODE(ni));
3074 	sc->sc_node_free(ni);
3075 }
3076 
3077 static void
3078 ath_node_getsignal(const struct ieee80211_node *ni, int8_t *rssi, int8_t *noise)
3079 {
3080 	struct ieee80211com *ic = ni->ni_ic;
3081 	struct ath_softc *sc = ic->ic_ifp->if_softc;
3082 	struct ath_hal *ah = sc->sc_ah;
3083 
3084 	*rssi = ic->ic_node_getrssi(ni);
3085 	if (ni->ni_chan != IEEE80211_CHAN_ANYC)
3086 		*noise = ath_hal_getchannoise(ah, ni->ni_chan);
3087 	else
3088 		*noise = -95;		/* nominally correct */
3089 }
3090 
3091 static int
3092 ath_rxbuf_init(struct ath_softc *sc, struct ath_buf *bf)
3093 {
3094 	struct ath_hal *ah = sc->sc_ah;
3095 	int error;
3096 	struct mbuf *m;
3097 	struct ath_desc *ds;
3098 
3099 	m = bf->bf_m;
3100 	if (m == NULL) {
3101 		/*
3102 		 * NB: by assigning a page to the rx dma buffer we
3103 		 * implicitly satisfy the Atheros requirement that
3104 		 * this buffer be cache-line-aligned and sized to be
3105 		 * multiple of the cache line size.  Not doing this
3106 		 * causes weird stuff to happen (for the 5210 at least).
3107 		 */
3108 		m = m_getcl(M_DONTWAIT, MT_DATA, M_PKTHDR);
3109 		if (m == NULL) {
3110 			DPRINTF(sc, ATH_DEBUG_ANY,
3111 				"%s: no mbuf/cluster\n", __func__);
3112 			sc->sc_stats.ast_rx_nombuf++;
3113 			return ENOMEM;
3114 		}
3115 		m->m_pkthdr.len = m->m_len = m->m_ext.ext_size;
3116 
3117 		error = bus_dmamap_load_mbuf_sg(sc->sc_dmat,
3118 					     bf->bf_dmamap, m,
3119 					     bf->bf_segs, &bf->bf_nseg,
3120 					     BUS_DMA_NOWAIT);
3121 		if (error != 0) {
3122 			DPRINTF(sc, ATH_DEBUG_ANY,
3123 			    "%s: bus_dmamap_load_mbuf_sg failed; error %d\n",
3124 			    __func__, error);
3125 			sc->sc_stats.ast_rx_busdma++;
3126 			m_freem(m);
3127 			return error;
3128 		}
3129 		KASSERT(bf->bf_nseg == 1,
3130 			("multi-segment packet; nseg %u", bf->bf_nseg));
3131 		bf->bf_m = m;
3132 	}
3133 	bus_dmamap_sync(sc->sc_dmat, bf->bf_dmamap, BUS_DMASYNC_PREREAD);
3134 
3135 	/*
3136 	 * Setup descriptors.  For receive we always terminate
3137 	 * the descriptor list with a self-linked entry so we'll
3138 	 * not get overrun under high load (as can happen with a
3139 	 * 5212 when ANI processing enables PHY error frames).
3140 	 *
3141 	 * To insure the last descriptor is self-linked we create
3142 	 * each descriptor as self-linked and add it to the end.  As
3143 	 * each additional descriptor is added the previous self-linked
3144 	 * entry is ``fixed'' naturally.  This should be safe even
3145 	 * if DMA is happening.  When processing RX interrupts we
3146 	 * never remove/process the last, self-linked, entry on the
3147 	 * descriptor list.  This insures the hardware always has
3148 	 * someplace to write a new frame.
3149 	 */
3150 	/*
3151 	 * 11N: we can no longer afford to self link the last descriptor.
3152 	 * MAC acknowledges BA status as long as it copies frames to host
3153 	 * buffer (or rx fifo). This can incorrectly acknowledge packets
3154 	 * to a sender if last desc is self-linked.
3155 	 */
3156 	ds = bf->bf_desc;
3157 	if (sc->sc_rxslink)
3158 		ds->ds_link = bf->bf_daddr;	/* link to self */
3159 	else
3160 		ds->ds_link = 0;		/* terminate the list */
3161 	ds->ds_data = bf->bf_segs[0].ds_addr;
3162 	ath_hal_setuprxdesc(ah, ds
3163 		, m->m_len		/* buffer size */
3164 		, 0
3165 	);
3166 
3167 	if (sc->sc_rxlink != NULL)
3168 		*sc->sc_rxlink = bf->bf_daddr;
3169 	sc->sc_rxlink = &ds->ds_link;
3170 	return 0;
3171 }
3172 
3173 /*
3174  * Extend 15-bit time stamp from rx descriptor to
3175  * a full 64-bit TSF using the specified TSF.
3176  */
3177 static __inline u_int64_t
3178 ath_extend_tsf(u_int32_t rstamp, u_int64_t tsf)
3179 {
3180 	if ((tsf & 0x7fff) < rstamp)
3181 		tsf -= 0x8000;
3182 	return ((tsf &~ 0x7fff) | rstamp);
3183 }
3184 
3185 /*
3186  * Intercept management frames to collect beacon rssi data
3187  * and to do ibss merges.
3188  */
3189 static void
3190 ath_recv_mgmt(struct ieee80211_node *ni, struct mbuf *m,
3191 	int subtype, int rssi, int nf)
3192 {
3193 	struct ieee80211vap *vap = ni->ni_vap;
3194 	struct ath_softc *sc = vap->iv_ic->ic_ifp->if_softc;
3195 
3196 	/*
3197 	 * Call up first so subsequent work can use information
3198 	 * potentially stored in the node (e.g. for ibss merge).
3199 	 */
3200 	ATH_VAP(vap)->av_recv_mgmt(ni, m, subtype, rssi, nf);
3201 	switch (subtype) {
3202 	case IEEE80211_FC0_SUBTYPE_BEACON:
3203 		/* update rssi statistics for use by the hal */
3204 		ATH_RSSI_LPF(sc->sc_halstats.ns_avgbrssi, rssi);
3205 		if (sc->sc_syncbeacon &&
3206 		    ni == vap->iv_bss && vap->iv_state == IEEE80211_S_RUN) {
3207 			/*
3208 			 * Resync beacon timers using the tsf of the beacon
3209 			 * frame we just received.
3210 			 */
3211 			ath_beacon_config(sc, vap);
3212 		}
3213 		/* fall thru... */
3214 	case IEEE80211_FC0_SUBTYPE_PROBE_RESP:
3215 		if (vap->iv_opmode == IEEE80211_M_IBSS &&
3216 		    vap->iv_state == IEEE80211_S_RUN) {
3217 			uint32_t rstamp = sc->sc_lastrs->rs_tstamp;
3218 			uint64_t tsf = ath_extend_tsf(rstamp,
3219 				ath_hal_gettsf64(sc->sc_ah));
3220 			/*
3221 			 * Handle ibss merge as needed; check the tsf on the
3222 			 * frame before attempting the merge.  The 802.11 spec
3223 			 * says the station should change it's bssid to match
3224 			 * the oldest station with the same ssid, where oldest
3225 			 * is determined by the tsf.  Note that hardware
3226 			 * reconfiguration happens through callback to
3227 			 * ath_newstate as the state machine will go from
3228 			 * RUN -> RUN when this happens.
3229 			 */
3230 			if (le64toh(ni->ni_tstamp.tsf) >= tsf) {
3231 				DPRINTF(sc, ATH_DEBUG_STATE,
3232 				    "ibss merge, rstamp %u tsf %ju "
3233 				    "tstamp %ju\n", rstamp, (uintmax_t)tsf,
3234 				    (uintmax_t)ni->ni_tstamp.tsf);
3235 				(void) ieee80211_ibss_merge(ni);
3236 			}
3237 		}
3238 		break;
3239 	}
3240 }
3241 
3242 /*
3243  * Set the default antenna.
3244  */
3245 static void
3246 ath_setdefantenna(struct ath_softc *sc, u_int antenna)
3247 {
3248 	struct ath_hal *ah = sc->sc_ah;
3249 
3250 	/* XXX block beacon interrupts */
3251 	ath_hal_setdefantenna(ah, antenna);
3252 	if (sc->sc_defant != antenna)
3253 		sc->sc_stats.ast_ant_defswitch++;
3254 	sc->sc_defant = antenna;
3255 	sc->sc_rxotherant = 0;
3256 }
3257 
3258 static void
3259 ath_rx_tap(struct ifnet *ifp, struct mbuf *m,
3260 	const struct ath_rx_status *rs, u_int64_t tsf, int16_t nf)
3261 {
3262 #define	CHAN_HT20	htole32(IEEE80211_CHAN_HT20)
3263 #define	CHAN_HT40U	htole32(IEEE80211_CHAN_HT40U)
3264 #define	CHAN_HT40D	htole32(IEEE80211_CHAN_HT40D)
3265 #define	CHAN_HT		(CHAN_HT20|CHAN_HT40U|CHAN_HT40D)
3266 	struct ath_softc *sc = ifp->if_softc;
3267 	const HAL_RATE_TABLE *rt;
3268 	uint8_t rix;
3269 
3270 	rt = sc->sc_currates;
3271 	KASSERT(rt != NULL, ("no rate table, mode %u", sc->sc_curmode));
3272 	rix = rt->rateCodeToIndex[rs->rs_rate];
3273 	sc->sc_rx_th.wr_rate = sc->sc_hwmap[rix].ieeerate;
3274 	sc->sc_rx_th.wr_flags = sc->sc_hwmap[rix].rxflags;
3275 #ifdef AH_SUPPORT_AR5416
3276 	sc->sc_rx_th.wr_chan_flags &= ~CHAN_HT;
3277 	if (sc->sc_rx_th.wr_rate & IEEE80211_RATE_MCS) {	/* HT rate */
3278 		struct ieee80211com *ic = ifp->if_l2com;
3279 
3280 		if ((rs->rs_flags & HAL_RX_2040) == 0)
3281 			sc->sc_rx_th.wr_chan_flags |= CHAN_HT20;
3282 		else if (IEEE80211_IS_CHAN_HT40U(ic->ic_curchan))
3283 			sc->sc_rx_th.wr_chan_flags |= CHAN_HT40U;
3284 		else
3285 			sc->sc_rx_th.wr_chan_flags |= CHAN_HT40D;
3286 		if ((rs->rs_flags & HAL_RX_GI) == 0)
3287 			sc->sc_rx_th.wr_flags |= IEEE80211_RADIOTAP_F_SHORTGI;
3288 	}
3289 #endif
3290 	sc->sc_rx_th.wr_tsf = htole64(ath_extend_tsf(rs->rs_tstamp, tsf));
3291 	if (rs->rs_status & HAL_RXERR_CRC)
3292 		sc->sc_rx_th.wr_flags |= IEEE80211_RADIOTAP_F_BADFCS;
3293 	/* XXX propagate other error flags from descriptor */
3294 	sc->sc_rx_th.wr_antnoise = nf;
3295 	sc->sc_rx_th.wr_antsignal = nf + rs->rs_rssi;
3296 	sc->sc_rx_th.wr_antenna = rs->rs_antenna;
3297 #undef CHAN_HT
3298 #undef CHAN_HT20
3299 #undef CHAN_HT40U
3300 #undef CHAN_HT40D
3301 }
3302 
3303 static void
3304 ath_handle_micerror(struct ieee80211com *ic,
3305 	struct ieee80211_frame *wh, int keyix)
3306 {
3307 	struct ieee80211_node *ni;
3308 
3309 	/* XXX recheck MIC to deal w/ chips that lie */
3310 	/* XXX discard MIC errors on !data frames */
3311 	ni = ieee80211_find_rxnode(ic, (const struct ieee80211_frame_min *) wh);
3312 	if (ni != NULL) {
3313 		ieee80211_notify_michael_failure(ni->ni_vap, wh, keyix);
3314 		ieee80211_free_node(ni);
3315 	}
3316 }
3317 
3318 static void
3319 ath_rx_proc(void *arg, int npending)
3320 {
3321 #define	PA2DESC(_sc, _pa) \
3322 	((struct ath_desc *)((caddr_t)(_sc)->sc_rxdma.dd_desc + \
3323 		((_pa) - (_sc)->sc_rxdma.dd_desc_paddr)))
3324 	struct ath_softc *sc = arg;
3325 	struct ath_buf *bf;
3326 	struct ifnet *ifp = sc->sc_ifp;
3327 	struct ieee80211com *ic = ifp->if_l2com;
3328 	struct ath_hal *ah = sc->sc_ah;
3329 	struct ath_desc *ds;
3330 	struct ath_rx_status *rs;
3331 	struct mbuf *m;
3332 	struct ieee80211_node *ni;
3333 	int len, type, ngood;
3334 	HAL_STATUS status;
3335 	int16_t nf;
3336 	u_int64_t tsf;
3337 
3338 	DPRINTF(sc, ATH_DEBUG_RX_PROC, "%s: pending %u\n", __func__, npending);
3339 	ngood = 0;
3340 	nf = ath_hal_getchannoise(ah, sc->sc_curchan);
3341 	sc->sc_stats.ast_rx_noise = nf;
3342 	tsf = ath_hal_gettsf64(ah);
3343 	do {
3344 		bf = STAILQ_FIRST(&sc->sc_rxbuf);
3345 		if (sc->sc_rxslink && bf == NULL) {	/* NB: shouldn't happen */
3346 			if_printf(ifp, "%s: no buffer!\n", __func__);
3347 			break;
3348 		} else if (bf == NULL) {
3349 			/*
3350 			 * End of List:
3351 			 * this can happen for non-self-linked RX chains
3352 			 */
3353 			sc->sc_stats.ast_rx_hitqueueend++;
3354 			break;
3355 		}
3356 		m = bf->bf_m;
3357 		if (m == NULL) {		/* NB: shouldn't happen */
3358 			/*
3359 			 * If mbuf allocation failed previously there
3360 			 * will be no mbuf; try again to re-populate it.
3361 			 */
3362 			/* XXX make debug msg */
3363 			if_printf(ifp, "%s: no mbuf!\n", __func__);
3364 			STAILQ_REMOVE_HEAD(&sc->sc_rxbuf, bf_list);
3365 			goto rx_next;
3366 		}
3367 		ds = bf->bf_desc;
3368 		if (ds->ds_link == bf->bf_daddr) {
3369 			/* NB: never process the self-linked entry at the end */
3370 			sc->sc_stats.ast_rx_hitqueueend++;
3371 			break;
3372 		}
3373 		/* XXX sync descriptor memory */
3374 		/*
3375 		 * Must provide the virtual address of the current
3376 		 * descriptor, the physical address, and the virtual
3377 		 * address of the next descriptor in the h/w chain.
3378 		 * This allows the HAL to look ahead to see if the
3379 		 * hardware is done with a descriptor by checking the
3380 		 * done bit in the following descriptor and the address
3381 		 * of the current descriptor the DMA engine is working
3382 		 * on.  All this is necessary because of our use of
3383 		 * a self-linked list to avoid rx overruns.
3384 		 */
3385 		rs = &bf->bf_status.ds_rxstat;
3386 		status = ath_hal_rxprocdesc(ah, ds,
3387 				bf->bf_daddr, PA2DESC(sc, ds->ds_link), rs);
3388 #ifdef ATH_DEBUG
3389 		if (sc->sc_debug & ATH_DEBUG_RECV_DESC)
3390 			ath_printrxbuf(sc, bf, 0, status == HAL_OK);
3391 #endif
3392 		if (status == HAL_EINPROGRESS)
3393 			break;
3394 		STAILQ_REMOVE_HEAD(&sc->sc_rxbuf, bf_list);
3395 
3396 		/* These aren't specifically errors */
3397 		if (rs->rs_flags & HAL_RX_GI)
3398 			sc->sc_stats.ast_rx_halfgi++;
3399 		if (rs->rs_flags & HAL_RX_2040)
3400 			sc->sc_stats.ast_rx_2040++;
3401 		if (rs->rs_flags & HAL_RX_DELIM_CRC_PRE)
3402 			sc->sc_stats.ast_rx_pre_crc_err++;
3403 		if (rs->rs_flags & HAL_RX_DELIM_CRC_POST)
3404 			sc->sc_stats.ast_rx_post_crc_err++;
3405 		if (rs->rs_flags & HAL_RX_DECRYPT_BUSY)
3406 			sc->sc_stats.ast_rx_decrypt_busy_err++;
3407 		if (rs->rs_flags & HAL_RX_HI_RX_CHAIN)
3408 			sc->sc_stats.ast_rx_hi_rx_chain++;
3409 
3410 		if (rs->rs_status != 0) {
3411 			if (rs->rs_status & HAL_RXERR_CRC)
3412 				sc->sc_stats.ast_rx_crcerr++;
3413 			if (rs->rs_status & HAL_RXERR_FIFO)
3414 				sc->sc_stats.ast_rx_fifoerr++;
3415 			if (rs->rs_status & HAL_RXERR_PHY) {
3416 				sc->sc_stats.ast_rx_phyerr++;
3417 				/* Be suitably paranoid about receiving phy errors out of the stats array bounds */
3418 				if (rs->rs_phyerr < 64)
3419 					sc->sc_stats.ast_rx_phy[rs->rs_phyerr]++;
3420 				goto rx_error;	/* NB: don't count in ierrors */
3421 			}
3422 			if (rs->rs_status & HAL_RXERR_DECRYPT) {
3423 				/*
3424 				 * Decrypt error.  If the error occurred
3425 				 * because there was no hardware key, then
3426 				 * let the frame through so the upper layers
3427 				 * can process it.  This is necessary for 5210
3428 				 * parts which have no way to setup a ``clear''
3429 				 * key cache entry.
3430 				 *
3431 				 * XXX do key cache faulting
3432 				 */
3433 				if (rs->rs_keyix == HAL_RXKEYIX_INVALID)
3434 					goto rx_accept;
3435 				sc->sc_stats.ast_rx_badcrypt++;
3436 			}
3437 			if (rs->rs_status & HAL_RXERR_MIC) {
3438 				sc->sc_stats.ast_rx_badmic++;
3439 				/*
3440 				 * Do minimal work required to hand off
3441 				 * the 802.11 header for notification.
3442 				 */
3443 				/* XXX frag's and qos frames */
3444 				len = rs->rs_datalen;
3445 				if (len >= sizeof (struct ieee80211_frame)) {
3446 					bus_dmamap_sync(sc->sc_dmat,
3447 					    bf->bf_dmamap,
3448 					    BUS_DMASYNC_POSTREAD);
3449 					ath_handle_micerror(ic,
3450 					    mtod(m, struct ieee80211_frame *),
3451 					    sc->sc_splitmic ?
3452 						rs->rs_keyix-32 : rs->rs_keyix);
3453 				}
3454 			}
3455 			ifp->if_ierrors++;
3456 rx_error:
3457 			/*
3458 			 * Cleanup any pending partial frame.
3459 			 */
3460 			if (sc->sc_rxpending != NULL) {
3461 				m_freem(sc->sc_rxpending);
3462 				sc->sc_rxpending = NULL;
3463 			}
3464 			/*
3465 			 * When a tap is present pass error frames
3466 			 * that have been requested.  By default we
3467 			 * pass decrypt+mic errors but others may be
3468 			 * interesting (e.g. crc).
3469 			 */
3470 			if (ieee80211_radiotap_active(ic) &&
3471 			    (rs->rs_status & sc->sc_monpass)) {
3472 				bus_dmamap_sync(sc->sc_dmat, bf->bf_dmamap,
3473 				    BUS_DMASYNC_POSTREAD);
3474 				/* NB: bpf needs the mbuf length setup */
3475 				len = rs->rs_datalen;
3476 				m->m_pkthdr.len = m->m_len = len;
3477 				ath_rx_tap(ifp, m, rs, tsf, nf);
3478 				ieee80211_radiotap_rx_all(ic, m);
3479 			}
3480 			/* XXX pass MIC errors up for s/w reclaculation */
3481 			goto rx_next;
3482 		}
3483 rx_accept:
3484 		/*
3485 		 * Sync and unmap the frame.  At this point we're
3486 		 * committed to passing the mbuf somewhere so clear
3487 		 * bf_m; this means a new mbuf must be allocated
3488 		 * when the rx descriptor is setup again to receive
3489 		 * another frame.
3490 		 */
3491 		bus_dmamap_sync(sc->sc_dmat, bf->bf_dmamap,
3492 		    BUS_DMASYNC_POSTREAD);
3493 		bus_dmamap_unload(sc->sc_dmat, bf->bf_dmamap);
3494 		bf->bf_m = NULL;
3495 
3496 		len = rs->rs_datalen;
3497 		m->m_len = len;
3498 
3499 		if (rs->rs_more) {
3500 			/*
3501 			 * Frame spans multiple descriptors; save
3502 			 * it for the next completed descriptor, it
3503 			 * will be used to construct a jumbogram.
3504 			 */
3505 			if (sc->sc_rxpending != NULL) {
3506 				/* NB: max frame size is currently 2 clusters */
3507 				sc->sc_stats.ast_rx_toobig++;
3508 				m_freem(sc->sc_rxpending);
3509 			}
3510 			m->m_pkthdr.rcvif = ifp;
3511 			m->m_pkthdr.len = len;
3512 			sc->sc_rxpending = m;
3513 			goto rx_next;
3514 		} else if (sc->sc_rxpending != NULL) {
3515 			/*
3516 			 * This is the second part of a jumbogram,
3517 			 * chain it to the first mbuf, adjust the
3518 			 * frame length, and clear the rxpending state.
3519 			 */
3520 			sc->sc_rxpending->m_next = m;
3521 			sc->sc_rxpending->m_pkthdr.len += len;
3522 			m = sc->sc_rxpending;
3523 			sc->sc_rxpending = NULL;
3524 		} else {
3525 			/*
3526 			 * Normal single-descriptor receive; setup
3527 			 * the rcvif and packet length.
3528 			 */
3529 			m->m_pkthdr.rcvif = ifp;
3530 			m->m_pkthdr.len = len;
3531 		}
3532 
3533 		ifp->if_ipackets++;
3534 		sc->sc_stats.ast_ant_rx[rs->rs_antenna]++;
3535 
3536 		/*
3537 		 * Populate the rx status block.  When there are bpf
3538 		 * listeners we do the additional work to provide
3539 		 * complete status.  Otherwise we fill in only the
3540 		 * material required by ieee80211_input.  Note that
3541 		 * noise setting is filled in above.
3542 		 */
3543 		if (ieee80211_radiotap_active(ic))
3544 			ath_rx_tap(ifp, m, rs, tsf, nf);
3545 
3546 		/*
3547 		 * From this point on we assume the frame is at least
3548 		 * as large as ieee80211_frame_min; verify that.
3549 		 */
3550 		if (len < IEEE80211_MIN_LEN) {
3551 			if (!ieee80211_radiotap_active(ic)) {
3552 				DPRINTF(sc, ATH_DEBUG_RECV,
3553 				    "%s: short packet %d\n", __func__, len);
3554 				sc->sc_stats.ast_rx_tooshort++;
3555 			} else {
3556 				/* NB: in particular this captures ack's */
3557 				ieee80211_radiotap_rx_all(ic, m);
3558 			}
3559 			m_freem(m);
3560 			goto rx_next;
3561 		}
3562 
3563 		if (IFF_DUMPPKTS(sc, ATH_DEBUG_RECV)) {
3564 			const HAL_RATE_TABLE *rt = sc->sc_currates;
3565 			uint8_t rix = rt->rateCodeToIndex[rs->rs_rate];
3566 
3567 			ieee80211_dump_pkt(ic, mtod(m, caddr_t), len,
3568 			    sc->sc_hwmap[rix].ieeerate, rs->rs_rssi);
3569 		}
3570 
3571 		m_adj(m, -IEEE80211_CRC_LEN);
3572 
3573 		/*
3574 		 * Locate the node for sender, track state, and then
3575 		 * pass the (referenced) node up to the 802.11 layer
3576 		 * for its use.
3577 		 */
3578 		ni = ieee80211_find_rxnode_withkey(ic,
3579 			mtod(m, const struct ieee80211_frame_min *),
3580 			rs->rs_keyix == HAL_RXKEYIX_INVALID ?
3581 				IEEE80211_KEYIX_NONE : rs->rs_keyix);
3582 		sc->sc_lastrs = rs;
3583 
3584 		/* Keep statistics on the number of aggregate packets received */
3585 		if (rs->rs_isaggr)
3586 			sc->sc_stats.ast_rx_agg++;
3587 
3588 		if (ni != NULL) {
3589 			/*
3590  			 * Only punt packets for ampdu reorder processing for 11n nodes;
3591  			 * net80211 enforces that M_AMPDU is only set for 11n nodes.
3592  			 */
3593 			if (ni->ni_flags & IEEE80211_NODE_HT)
3594 				m->m_flags |= M_AMPDU;
3595 
3596 			/*
3597 			 * Sending station is known, dispatch directly.
3598 			 */
3599 			type = ieee80211_input(ni, m, rs->rs_rssi, nf);
3600 			ieee80211_free_node(ni);
3601 			/*
3602 			 * Arrange to update the last rx timestamp only for
3603 			 * frames from our ap when operating in station mode.
3604 			 * This assumes the rx key is always setup when
3605 			 * associated.
3606 			 */
3607 			if (ic->ic_opmode == IEEE80211_M_STA &&
3608 			    rs->rs_keyix != HAL_RXKEYIX_INVALID)
3609 				ngood++;
3610 		} else {
3611 			type = ieee80211_input_all(ic, m, rs->rs_rssi, nf);
3612 		}
3613 		/*
3614 		 * Track rx rssi and do any rx antenna management.
3615 		 */
3616 		ATH_RSSI_LPF(sc->sc_halstats.ns_avgrssi, rs->rs_rssi);
3617 		if (sc->sc_diversity) {
3618 			/*
3619 			 * When using fast diversity, change the default rx
3620 			 * antenna if diversity chooses the other antenna 3
3621 			 * times in a row.
3622 			 */
3623 			if (sc->sc_defant != rs->rs_antenna) {
3624 				if (++sc->sc_rxotherant >= 3)
3625 					ath_setdefantenna(sc, rs->rs_antenna);
3626 			} else
3627 				sc->sc_rxotherant = 0;
3628 		}
3629 
3630 		/* Newer school diversity - kite specific for now */
3631 		/* XXX perhaps migrate the normal diversity code to this? */
3632 		if ((ah)->ah_rxAntCombDiversity)
3633 			(*(ah)->ah_rxAntCombDiversity)(ah, rs, ticks, hz);
3634 
3635 		if (sc->sc_softled) {
3636 			/*
3637 			 * Blink for any data frame.  Otherwise do a
3638 			 * heartbeat-style blink when idle.  The latter
3639 			 * is mainly for station mode where we depend on
3640 			 * periodic beacon frames to trigger the poll event.
3641 			 */
3642 			if (type == IEEE80211_FC0_TYPE_DATA) {
3643 				const HAL_RATE_TABLE *rt = sc->sc_currates;
3644 				ath_led_event(sc,
3645 				    rt->rateCodeToIndex[rs->rs_rate]);
3646 			} else if (ticks - sc->sc_ledevent >= sc->sc_ledidle)
3647 				ath_led_event(sc, 0);
3648 		}
3649 rx_next:
3650 		STAILQ_INSERT_TAIL(&sc->sc_rxbuf, bf, bf_list);
3651 	} while (ath_rxbuf_init(sc, bf) == 0);
3652 
3653 	/* rx signal state monitoring */
3654 	ath_hal_rxmonitor(ah, &sc->sc_halstats, sc->sc_curchan);
3655 	if (ngood)
3656 		sc->sc_lastrx = tsf;
3657 
3658 	if ((ifp->if_drv_flags & IFF_DRV_OACTIVE) == 0) {
3659 #ifdef IEEE80211_SUPPORT_SUPERG
3660 		ieee80211_ff_age_all(ic, 100);
3661 #endif
3662 		if (!IFQ_IS_EMPTY(&ifp->if_snd))
3663 			ath_start(ifp);
3664 	}
3665 #undef PA2DESC
3666 }
3667 
3668 static void
3669 ath_txq_init(struct ath_softc *sc, struct ath_txq *txq, int qnum)
3670 {
3671 	txq->axq_qnum = qnum;
3672 	txq->axq_ac = 0;
3673 	txq->axq_depth = 0;
3674 	txq->axq_intrcnt = 0;
3675 	txq->axq_link = NULL;
3676 	STAILQ_INIT(&txq->axq_q);
3677 	ATH_TXQ_LOCK_INIT(sc, txq);
3678 }
3679 
3680 /*
3681  * Setup a h/w transmit queue.
3682  */
3683 static struct ath_txq *
3684 ath_txq_setup(struct ath_softc *sc, int qtype, int subtype)
3685 {
3686 #define	N(a)	(sizeof(a)/sizeof(a[0]))
3687 	struct ath_hal *ah = sc->sc_ah;
3688 	HAL_TXQ_INFO qi;
3689 	int qnum;
3690 
3691 	memset(&qi, 0, sizeof(qi));
3692 	qi.tqi_subtype = subtype;
3693 	qi.tqi_aifs = HAL_TXQ_USEDEFAULT;
3694 	qi.tqi_cwmin = HAL_TXQ_USEDEFAULT;
3695 	qi.tqi_cwmax = HAL_TXQ_USEDEFAULT;
3696 	/*
3697 	 * Enable interrupts only for EOL and DESC conditions.
3698 	 * We mark tx descriptors to receive a DESC interrupt
3699 	 * when a tx queue gets deep; otherwise waiting for the
3700 	 * EOL to reap descriptors.  Note that this is done to
3701 	 * reduce interrupt load and this only defers reaping
3702 	 * descriptors, never transmitting frames.  Aside from
3703 	 * reducing interrupts this also permits more concurrency.
3704 	 * The only potential downside is if the tx queue backs
3705 	 * up in which case the top half of the kernel may backup
3706 	 * due to a lack of tx descriptors.
3707 	 */
3708 	qi.tqi_qflags = HAL_TXQ_TXEOLINT_ENABLE | HAL_TXQ_TXDESCINT_ENABLE;
3709 	qnum = ath_hal_setuptxqueue(ah, qtype, &qi);
3710 	if (qnum == -1) {
3711 		/*
3712 		 * NB: don't print a message, this happens
3713 		 * normally on parts with too few tx queues
3714 		 */
3715 		return NULL;
3716 	}
3717 	if (qnum >= N(sc->sc_txq)) {
3718 		device_printf(sc->sc_dev,
3719 			"hal qnum %u out of range, max %zu!\n",
3720 			qnum, N(sc->sc_txq));
3721 		ath_hal_releasetxqueue(ah, qnum);
3722 		return NULL;
3723 	}
3724 	if (!ATH_TXQ_SETUP(sc, qnum)) {
3725 		ath_txq_init(sc, &sc->sc_txq[qnum], qnum);
3726 		sc->sc_txqsetup |= 1<<qnum;
3727 	}
3728 	return &sc->sc_txq[qnum];
3729 #undef N
3730 }
3731 
3732 /*
3733  * Setup a hardware data transmit queue for the specified
3734  * access control.  The hal may not support all requested
3735  * queues in which case it will return a reference to a
3736  * previously setup queue.  We record the mapping from ac's
3737  * to h/w queues for use by ath_tx_start and also track
3738  * the set of h/w queues being used to optimize work in the
3739  * transmit interrupt handler and related routines.
3740  */
3741 static int
3742 ath_tx_setup(struct ath_softc *sc, int ac, int haltype)
3743 {
3744 #define	N(a)	(sizeof(a)/sizeof(a[0]))
3745 	struct ath_txq *txq;
3746 
3747 	if (ac >= N(sc->sc_ac2q)) {
3748 		device_printf(sc->sc_dev, "AC %u out of range, max %zu!\n",
3749 			ac, N(sc->sc_ac2q));
3750 		return 0;
3751 	}
3752 	txq = ath_txq_setup(sc, HAL_TX_QUEUE_DATA, haltype);
3753 	if (txq != NULL) {
3754 		txq->axq_ac = ac;
3755 		sc->sc_ac2q[ac] = txq;
3756 		return 1;
3757 	} else
3758 		return 0;
3759 #undef N
3760 }
3761 
3762 /*
3763  * Update WME parameters for a transmit queue.
3764  */
3765 static int
3766 ath_txq_update(struct ath_softc *sc, int ac)
3767 {
3768 #define	ATH_EXPONENT_TO_VALUE(v)	((1<<v)-1)
3769 #define	ATH_TXOP_TO_US(v)		(v<<5)
3770 	struct ifnet *ifp = sc->sc_ifp;
3771 	struct ieee80211com *ic = ifp->if_l2com;
3772 	struct ath_txq *txq = sc->sc_ac2q[ac];
3773 	struct wmeParams *wmep = &ic->ic_wme.wme_chanParams.cap_wmeParams[ac];
3774 	struct ath_hal *ah = sc->sc_ah;
3775 	HAL_TXQ_INFO qi;
3776 
3777 	ath_hal_gettxqueueprops(ah, txq->axq_qnum, &qi);
3778 #ifdef IEEE80211_SUPPORT_TDMA
3779 	if (sc->sc_tdma) {
3780 		/*
3781 		 * AIFS is zero so there's no pre-transmit wait.  The
3782 		 * burst time defines the slot duration and is configured
3783 		 * through net80211.  The QCU is setup to not do post-xmit
3784 		 * back off, lockout all lower-priority QCU's, and fire
3785 		 * off the DMA beacon alert timer which is setup based
3786 		 * on the slot configuration.
3787 		 */
3788 		qi.tqi_qflags = HAL_TXQ_TXOKINT_ENABLE
3789 			      | HAL_TXQ_TXERRINT_ENABLE
3790 			      | HAL_TXQ_TXURNINT_ENABLE
3791 			      | HAL_TXQ_TXEOLINT_ENABLE
3792 			      | HAL_TXQ_DBA_GATED
3793 			      | HAL_TXQ_BACKOFF_DISABLE
3794 			      | HAL_TXQ_ARB_LOCKOUT_GLOBAL
3795 			      ;
3796 		qi.tqi_aifs = 0;
3797 		/* XXX +dbaprep? */
3798 		qi.tqi_readyTime = sc->sc_tdmaslotlen;
3799 		qi.tqi_burstTime = qi.tqi_readyTime;
3800 	} else {
3801 #endif
3802 		qi.tqi_qflags = HAL_TXQ_TXOKINT_ENABLE
3803 			      | HAL_TXQ_TXERRINT_ENABLE
3804 			      | HAL_TXQ_TXDESCINT_ENABLE
3805 			      | HAL_TXQ_TXURNINT_ENABLE
3806 			      ;
3807 		qi.tqi_aifs = wmep->wmep_aifsn;
3808 		qi.tqi_cwmin = ATH_EXPONENT_TO_VALUE(wmep->wmep_logcwmin);
3809 		qi.tqi_cwmax = ATH_EXPONENT_TO_VALUE(wmep->wmep_logcwmax);
3810 		qi.tqi_readyTime = 0;
3811 		qi.tqi_burstTime = ATH_TXOP_TO_US(wmep->wmep_txopLimit);
3812 #ifdef IEEE80211_SUPPORT_TDMA
3813 	}
3814 #endif
3815 
3816 	DPRINTF(sc, ATH_DEBUG_RESET,
3817 	    "%s: Q%u qflags 0x%x aifs %u cwmin %u cwmax %u burstTime %u\n",
3818 	    __func__, txq->axq_qnum, qi.tqi_qflags,
3819 	    qi.tqi_aifs, qi.tqi_cwmin, qi.tqi_cwmax, qi.tqi_burstTime);
3820 
3821 	if (!ath_hal_settxqueueprops(ah, txq->axq_qnum, &qi)) {
3822 		if_printf(ifp, "unable to update hardware queue "
3823 			"parameters for %s traffic!\n",
3824 			ieee80211_wme_acnames[ac]);
3825 		return 0;
3826 	} else {
3827 		ath_hal_resettxqueue(ah, txq->axq_qnum); /* push to h/w */
3828 		return 1;
3829 	}
3830 #undef ATH_TXOP_TO_US
3831 #undef ATH_EXPONENT_TO_VALUE
3832 }
3833 
3834 /*
3835  * Callback from the 802.11 layer to update WME parameters.
3836  */
3837 static int
3838 ath_wme_update(struct ieee80211com *ic)
3839 {
3840 	struct ath_softc *sc = ic->ic_ifp->if_softc;
3841 
3842 	return !ath_txq_update(sc, WME_AC_BE) ||
3843 	    !ath_txq_update(sc, WME_AC_BK) ||
3844 	    !ath_txq_update(sc, WME_AC_VI) ||
3845 	    !ath_txq_update(sc, WME_AC_VO) ? EIO : 0;
3846 }
3847 
3848 /*
3849  * Reclaim resources for a setup queue.
3850  */
3851 static void
3852 ath_tx_cleanupq(struct ath_softc *sc, struct ath_txq *txq)
3853 {
3854 
3855 	ath_hal_releasetxqueue(sc->sc_ah, txq->axq_qnum);
3856 	ATH_TXQ_LOCK_DESTROY(txq);
3857 	sc->sc_txqsetup &= ~(1<<txq->axq_qnum);
3858 }
3859 
3860 /*
3861  * Reclaim all tx queue resources.
3862  */
3863 static void
3864 ath_tx_cleanup(struct ath_softc *sc)
3865 {
3866 	int i;
3867 
3868 	ATH_TXBUF_LOCK_DESTROY(sc);
3869 	for (i = 0; i < HAL_NUM_TX_QUEUES; i++)
3870 		if (ATH_TXQ_SETUP(sc, i))
3871 			ath_tx_cleanupq(sc, &sc->sc_txq[i]);
3872 }
3873 
3874 /*
3875  * Return h/w rate index for an IEEE rate (w/o basic rate bit)
3876  * using the current rates in sc_rixmap.
3877  */
3878 int
3879 ath_tx_findrix(const struct ath_softc *sc, uint8_t rate)
3880 {
3881 	int rix = sc->sc_rixmap[rate];
3882 	/* NB: return lowest rix for invalid rate */
3883 	return (rix == 0xff ? 0 : rix);
3884 }
3885 
3886 /*
3887  * Process completed xmit descriptors from the specified queue.
3888  */
3889 static int
3890 ath_tx_processq(struct ath_softc *sc, struct ath_txq *txq)
3891 {
3892 	struct ath_hal *ah = sc->sc_ah;
3893 	struct ifnet *ifp = sc->sc_ifp;
3894 	struct ieee80211com *ic = ifp->if_l2com;
3895 	struct ath_buf *bf, *last;
3896 	struct ath_desc *ds, *ds0;
3897 	struct ath_tx_status *ts;
3898 	struct ieee80211_node *ni;
3899 	struct ath_node *an;
3900 	int sr, lr, pri, nacked;
3901 	HAL_STATUS status;
3902 
3903 	DPRINTF(sc, ATH_DEBUG_TX_PROC, "%s: tx queue %u head %p link %p\n",
3904 		__func__, txq->axq_qnum,
3905 		(caddr_t)(uintptr_t) ath_hal_gettxbuf(sc->sc_ah, txq->axq_qnum),
3906 		txq->axq_link);
3907 	nacked = 0;
3908 	for (;;) {
3909 		ATH_TXQ_LOCK(txq);
3910 		txq->axq_intrcnt = 0;	/* reset periodic desc intr count */
3911 		bf = STAILQ_FIRST(&txq->axq_q);
3912 		if (bf == NULL) {
3913 			ATH_TXQ_UNLOCK(txq);
3914 			break;
3915 		}
3916 		ds0 = &bf->bf_desc[0];
3917 		ds = &bf->bf_desc[bf->bf_nseg - 1];
3918 		ts = &bf->bf_status.ds_txstat;
3919 		status = ath_hal_txprocdesc(ah, ds, ts);
3920 #ifdef ATH_DEBUG
3921 		if (sc->sc_debug & ATH_DEBUG_XMIT_DESC)
3922 			ath_printtxbuf(sc, bf, txq->axq_qnum, 0,
3923 			    status == HAL_OK);
3924 #endif
3925 		if (status == HAL_EINPROGRESS) {
3926 			ATH_TXQ_UNLOCK(txq);
3927 			break;
3928 		}
3929 		ATH_TXQ_REMOVE_HEAD(txq, bf_list);
3930 #ifdef IEEE80211_SUPPORT_TDMA
3931 		if (txq->axq_depth > 0) {
3932 			/*
3933 			 * More frames follow.  Mark the buffer busy
3934 			 * so it's not re-used while the hardware may
3935 			 * still re-read the link field in the descriptor.
3936 			 */
3937 			bf->bf_flags |= ATH_BUF_BUSY;
3938 		} else
3939 #else
3940 		if (txq->axq_depth == 0)
3941 #endif
3942 			txq->axq_link = NULL;
3943 		ATH_TXQ_UNLOCK(txq);
3944 
3945 		ni = bf->bf_node;
3946 		if (ni != NULL) {
3947 			an = ATH_NODE(ni);
3948 			if (ts->ts_status == 0) {
3949 				u_int8_t txant = ts->ts_antenna;
3950 				sc->sc_stats.ast_ant_tx[txant]++;
3951 				sc->sc_ant_tx[txant]++;
3952 				if (ts->ts_finaltsi != 0)
3953 					sc->sc_stats.ast_tx_altrate++;
3954 				pri = M_WME_GETAC(bf->bf_m);
3955 				if (pri >= WME_AC_VO)
3956 					ic->ic_wme.wme_hipri_traffic++;
3957 				if ((bf->bf_txflags & HAL_TXDESC_NOACK) == 0)
3958 					ni->ni_inact = ni->ni_inact_reload;
3959 			} else {
3960 				if (ts->ts_status & HAL_TXERR_XRETRY)
3961 					sc->sc_stats.ast_tx_xretries++;
3962 				if (ts->ts_status & HAL_TXERR_FIFO)
3963 					sc->sc_stats.ast_tx_fifoerr++;
3964 				if (ts->ts_status & HAL_TXERR_FILT)
3965 					sc->sc_stats.ast_tx_filtered++;
3966 				if (bf->bf_m->m_flags & M_FF)
3967 					sc->sc_stats.ast_ff_txerr++;
3968 			}
3969 			sr = ts->ts_shortretry;
3970 			lr = ts->ts_longretry;
3971 			sc->sc_stats.ast_tx_shortretry += sr;
3972 			sc->sc_stats.ast_tx_longretry += lr;
3973 			/*
3974 			 * Hand the descriptor to the rate control algorithm.
3975 			 */
3976 			if ((ts->ts_status & HAL_TXERR_FILT) == 0 &&
3977 			    (bf->bf_txflags & HAL_TXDESC_NOACK) == 0) {
3978 				/*
3979 				 * If frame was ack'd update statistics,
3980 				 * including the last rx time used to
3981 				 * workaround phantom bmiss interrupts.
3982 				 */
3983 				if (ts->ts_status == 0) {
3984 					nacked++;
3985 					sc->sc_stats.ast_tx_rssi = ts->ts_rssi;
3986 					ATH_RSSI_LPF(sc->sc_halstats.ns_avgtxrssi,
3987 						ts->ts_rssi);
3988 				}
3989 				ath_rate_tx_complete(sc, an, bf);
3990 			}
3991 			/*
3992 			 * Do any tx complete callback.  Note this must
3993 			 * be done before releasing the node reference.
3994 			 */
3995 			if (bf->bf_m->m_flags & M_TXCB)
3996 				ieee80211_process_callback(ni, bf->bf_m,
3997 				    (bf->bf_txflags & HAL_TXDESC_NOACK) == 0 ?
3998 				        ts->ts_status : HAL_TXERR_XRETRY);
3999 			ieee80211_free_node(ni);
4000 		}
4001 		bus_dmamap_sync(sc->sc_dmat, bf->bf_dmamap,
4002 		    BUS_DMASYNC_POSTWRITE);
4003 		bus_dmamap_unload(sc->sc_dmat, bf->bf_dmamap);
4004 
4005 		m_freem(bf->bf_m);
4006 		bf->bf_m = NULL;
4007 		bf->bf_node = NULL;
4008 
4009 		ATH_TXBUF_LOCK(sc);
4010 		last = STAILQ_LAST(&sc->sc_txbuf, ath_buf, bf_list);
4011 		if (last != NULL)
4012 			last->bf_flags &= ~ATH_BUF_BUSY;
4013 		STAILQ_INSERT_TAIL(&sc->sc_txbuf, bf, bf_list);
4014 		ATH_TXBUF_UNLOCK(sc);
4015 	}
4016 #ifdef IEEE80211_SUPPORT_SUPERG
4017 	/*
4018 	 * Flush fast-frame staging queue when traffic slows.
4019 	 */
4020 	if (txq->axq_depth <= 1)
4021 		ieee80211_ff_flush(ic, txq->axq_ac);
4022 #endif
4023 	return nacked;
4024 }
4025 
4026 static __inline int
4027 txqactive(struct ath_hal *ah, int qnum)
4028 {
4029 	u_int32_t txqs = 1<<qnum;
4030 	ath_hal_gettxintrtxqs(ah, &txqs);
4031 	return (txqs & (1<<qnum));
4032 }
4033 
4034 /*
4035  * Deferred processing of transmit interrupt; special-cased
4036  * for a single hardware transmit queue (e.g. 5210 and 5211).
4037  */
4038 static void
4039 ath_tx_proc_q0(void *arg, int npending)
4040 {
4041 	struct ath_softc *sc = arg;
4042 	struct ifnet *ifp = sc->sc_ifp;
4043 
4044 	if (txqactive(sc->sc_ah, 0) && ath_tx_processq(sc, &sc->sc_txq[0]))
4045 		sc->sc_lastrx = ath_hal_gettsf64(sc->sc_ah);
4046 	if (txqactive(sc->sc_ah, sc->sc_cabq->axq_qnum))
4047 		ath_tx_processq(sc, sc->sc_cabq);
4048 	ifp->if_drv_flags &= ~IFF_DRV_OACTIVE;
4049 	sc->sc_wd_timer = 0;
4050 
4051 	if (sc->sc_softled)
4052 		ath_led_event(sc, sc->sc_txrix);
4053 
4054 	ath_start(ifp);
4055 }
4056 
4057 /*
4058  * Deferred processing of transmit interrupt; special-cased
4059  * for four hardware queues, 0-3 (e.g. 5212 w/ WME support).
4060  */
4061 static void
4062 ath_tx_proc_q0123(void *arg, int npending)
4063 {
4064 	struct ath_softc *sc = arg;
4065 	struct ifnet *ifp = sc->sc_ifp;
4066 	int nacked;
4067 
4068 	/*
4069 	 * Process each active queue.
4070 	 */
4071 	nacked = 0;
4072 	if (txqactive(sc->sc_ah, 0))
4073 		nacked += ath_tx_processq(sc, &sc->sc_txq[0]);
4074 	if (txqactive(sc->sc_ah, 1))
4075 		nacked += ath_tx_processq(sc, &sc->sc_txq[1]);
4076 	if (txqactive(sc->sc_ah, 2))
4077 		nacked += ath_tx_processq(sc, &sc->sc_txq[2]);
4078 	if (txqactive(sc->sc_ah, 3))
4079 		nacked += ath_tx_processq(sc, &sc->sc_txq[3]);
4080 	if (txqactive(sc->sc_ah, sc->sc_cabq->axq_qnum))
4081 		ath_tx_processq(sc, sc->sc_cabq);
4082 	if (nacked)
4083 		sc->sc_lastrx = ath_hal_gettsf64(sc->sc_ah);
4084 
4085 	ifp->if_drv_flags &= ~IFF_DRV_OACTIVE;
4086 	sc->sc_wd_timer = 0;
4087 
4088 	if (sc->sc_softled)
4089 		ath_led_event(sc, sc->sc_txrix);
4090 
4091 	ath_start(ifp);
4092 }
4093 
4094 /*
4095  * Deferred processing of transmit interrupt.
4096  */
4097 static void
4098 ath_tx_proc(void *arg, int npending)
4099 {
4100 	struct ath_softc *sc = arg;
4101 	struct ifnet *ifp = sc->sc_ifp;
4102 	int i, nacked;
4103 
4104 	/*
4105 	 * Process each active queue.
4106 	 */
4107 	nacked = 0;
4108 	for (i = 0; i < HAL_NUM_TX_QUEUES; i++)
4109 		if (ATH_TXQ_SETUP(sc, i) && txqactive(sc->sc_ah, i))
4110 			nacked += ath_tx_processq(sc, &sc->sc_txq[i]);
4111 	if (nacked)
4112 		sc->sc_lastrx = ath_hal_gettsf64(sc->sc_ah);
4113 
4114 	ifp->if_drv_flags &= ~IFF_DRV_OACTIVE;
4115 	sc->sc_wd_timer = 0;
4116 
4117 	if (sc->sc_softled)
4118 		ath_led_event(sc, sc->sc_txrix);
4119 
4120 	ath_start(ifp);
4121 }
4122 
4123 static void
4124 ath_tx_draintxq(struct ath_softc *sc, struct ath_txq *txq)
4125 {
4126 #ifdef ATH_DEBUG
4127 	struct ath_hal *ah = sc->sc_ah;
4128 #endif
4129 	struct ieee80211_node *ni;
4130 	struct ath_buf *bf;
4131 	u_int ix;
4132 
4133 	/*
4134 	 * NB: this assumes output has been stopped and
4135 	 *     we do not need to block ath_tx_proc
4136 	 */
4137 	ATH_TXBUF_LOCK(sc);
4138 	bf = STAILQ_LAST(&sc->sc_txbuf, ath_buf, bf_list);
4139 	if (bf != NULL)
4140 		bf->bf_flags &= ~ATH_BUF_BUSY;
4141 	ATH_TXBUF_UNLOCK(sc);
4142 	for (ix = 0;; ix++) {
4143 		ATH_TXQ_LOCK(txq);
4144 		bf = STAILQ_FIRST(&txq->axq_q);
4145 		if (bf == NULL) {
4146 			txq->axq_link = NULL;
4147 			ATH_TXQ_UNLOCK(txq);
4148 			break;
4149 		}
4150 		ATH_TXQ_REMOVE_HEAD(txq, bf_list);
4151 		ATH_TXQ_UNLOCK(txq);
4152 #ifdef ATH_DEBUG
4153 		if (sc->sc_debug & ATH_DEBUG_RESET) {
4154 			struct ieee80211com *ic = sc->sc_ifp->if_l2com;
4155 
4156 			ath_printtxbuf(sc, bf, txq->axq_qnum, ix,
4157 				ath_hal_txprocdesc(ah, bf->bf_desc,
4158 				    &bf->bf_status.ds_txstat) == HAL_OK);
4159 			ieee80211_dump_pkt(ic, mtod(bf->bf_m, const uint8_t *),
4160 			    bf->bf_m->m_len, 0, -1);
4161 		}
4162 #endif /* ATH_DEBUG */
4163 		bus_dmamap_unload(sc->sc_dmat, bf->bf_dmamap);
4164 		ni = bf->bf_node;
4165 		bf->bf_node = NULL;
4166 		if (ni != NULL) {
4167 			/*
4168 			 * Do any callback and reclaim the node reference.
4169 			 */
4170 			if (bf->bf_m->m_flags & M_TXCB)
4171 				ieee80211_process_callback(ni, bf->bf_m, -1);
4172 			ieee80211_free_node(ni);
4173 		}
4174 		m_freem(bf->bf_m);
4175 		bf->bf_m = NULL;
4176 		bf->bf_flags &= ~ATH_BUF_BUSY;
4177 
4178 		ATH_TXBUF_LOCK(sc);
4179 		STAILQ_INSERT_TAIL(&sc->sc_txbuf, bf, bf_list);
4180 		ATH_TXBUF_UNLOCK(sc);
4181 	}
4182 }
4183 
4184 static void
4185 ath_tx_stopdma(struct ath_softc *sc, struct ath_txq *txq)
4186 {
4187 	struct ath_hal *ah = sc->sc_ah;
4188 
4189 	DPRINTF(sc, ATH_DEBUG_RESET, "%s: tx queue [%u] %p, link %p\n",
4190 	    __func__, txq->axq_qnum,
4191 	    (caddr_t)(uintptr_t) ath_hal_gettxbuf(ah, txq->axq_qnum),
4192 	    txq->axq_link);
4193 	(void) ath_hal_stoptxdma(ah, txq->axq_qnum);
4194 }
4195 
4196 /*
4197  * Drain the transmit queues and reclaim resources.
4198  */
4199 static void
4200 ath_draintxq(struct ath_softc *sc)
4201 {
4202 	struct ath_hal *ah = sc->sc_ah;
4203 	struct ifnet *ifp = sc->sc_ifp;
4204 	int i;
4205 
4206 	/* XXX return value */
4207 	if (!sc->sc_invalid) {
4208 		/* don't touch the hardware if marked invalid */
4209 		DPRINTF(sc, ATH_DEBUG_RESET, "%s: tx queue [%u] %p, link %p\n",
4210 		    __func__, sc->sc_bhalq,
4211 		    (caddr_t)(uintptr_t) ath_hal_gettxbuf(ah, sc->sc_bhalq),
4212 		    NULL);
4213 		(void) ath_hal_stoptxdma(ah, sc->sc_bhalq);
4214 		for (i = 0; i < HAL_NUM_TX_QUEUES; i++)
4215 			if (ATH_TXQ_SETUP(sc, i))
4216 				ath_tx_stopdma(sc, &sc->sc_txq[i]);
4217 	}
4218 	for (i = 0; i < HAL_NUM_TX_QUEUES; i++)
4219 		if (ATH_TXQ_SETUP(sc, i))
4220 			ath_tx_draintxq(sc, &sc->sc_txq[i]);
4221 #ifdef ATH_DEBUG
4222 	if (sc->sc_debug & ATH_DEBUG_RESET) {
4223 		struct ath_buf *bf = STAILQ_FIRST(&sc->sc_bbuf);
4224 		if (bf != NULL && bf->bf_m != NULL) {
4225 			ath_printtxbuf(sc, bf, sc->sc_bhalq, 0,
4226 				ath_hal_txprocdesc(ah, bf->bf_desc,
4227 				    &bf->bf_status.ds_txstat) == HAL_OK);
4228 			ieee80211_dump_pkt(ifp->if_l2com,
4229 			    mtod(bf->bf_m, const uint8_t *), bf->bf_m->m_len,
4230 			    0, -1);
4231 		}
4232 	}
4233 #endif /* ATH_DEBUG */
4234 	ifp->if_drv_flags &= ~IFF_DRV_OACTIVE;
4235 	sc->sc_wd_timer = 0;
4236 }
4237 
4238 /*
4239  * Disable the receive h/w in preparation for a reset.
4240  */
4241 static void
4242 ath_stoprecv(struct ath_softc *sc)
4243 {
4244 #define	PA2DESC(_sc, _pa) \
4245 	((struct ath_desc *)((caddr_t)(_sc)->sc_rxdma.dd_desc + \
4246 		((_pa) - (_sc)->sc_rxdma.dd_desc_paddr)))
4247 	struct ath_hal *ah = sc->sc_ah;
4248 
4249 	ath_hal_stoppcurecv(ah);	/* disable PCU */
4250 	ath_hal_setrxfilter(ah, 0);	/* clear recv filter */
4251 	ath_hal_stopdmarecv(ah);	/* disable DMA engine */
4252 	DELAY(3000);			/* 3ms is long enough for 1 frame */
4253 #ifdef ATH_DEBUG
4254 	if (sc->sc_debug & (ATH_DEBUG_RESET | ATH_DEBUG_FATAL)) {
4255 		struct ath_buf *bf;
4256 		u_int ix;
4257 
4258 		printf("%s: rx queue %p, link %p\n", __func__,
4259 			(caddr_t)(uintptr_t) ath_hal_getrxbuf(ah), sc->sc_rxlink);
4260 		ix = 0;
4261 		STAILQ_FOREACH(bf, &sc->sc_rxbuf, bf_list) {
4262 			struct ath_desc *ds = bf->bf_desc;
4263 			struct ath_rx_status *rs = &bf->bf_status.ds_rxstat;
4264 			HAL_STATUS status = ath_hal_rxprocdesc(ah, ds,
4265 				bf->bf_daddr, PA2DESC(sc, ds->ds_link), rs);
4266 			if (status == HAL_OK || (sc->sc_debug & ATH_DEBUG_FATAL))
4267 				ath_printrxbuf(sc, bf, ix, status == HAL_OK);
4268 			ix++;
4269 		}
4270 	}
4271 #endif
4272 	if (sc->sc_rxpending != NULL) {
4273 		m_freem(sc->sc_rxpending);
4274 		sc->sc_rxpending = NULL;
4275 	}
4276 	sc->sc_rxlink = NULL;		/* just in case */
4277 #undef PA2DESC
4278 }
4279 
4280 /*
4281  * Enable the receive h/w following a reset.
4282  */
4283 static int
4284 ath_startrecv(struct ath_softc *sc)
4285 {
4286 	struct ath_hal *ah = sc->sc_ah;
4287 	struct ath_buf *bf;
4288 
4289 	sc->sc_rxlink = NULL;
4290 	sc->sc_rxpending = NULL;
4291 	STAILQ_FOREACH(bf, &sc->sc_rxbuf, bf_list) {
4292 		int error = ath_rxbuf_init(sc, bf);
4293 		if (error != 0) {
4294 			DPRINTF(sc, ATH_DEBUG_RECV,
4295 				"%s: ath_rxbuf_init failed %d\n",
4296 				__func__, error);
4297 			return error;
4298 		}
4299 	}
4300 
4301 	bf = STAILQ_FIRST(&sc->sc_rxbuf);
4302 	ath_hal_putrxbuf(ah, bf->bf_daddr);
4303 	ath_hal_rxena(ah);		/* enable recv descriptors */
4304 	ath_mode_init(sc);		/* set filters, etc. */
4305 	ath_hal_startpcurecv(ah);	/* re-enable PCU/DMA engine */
4306 	return 0;
4307 }
4308 
4309 /*
4310  * Update internal state after a channel change.
4311  */
4312 static void
4313 ath_chan_change(struct ath_softc *sc, struct ieee80211_channel *chan)
4314 {
4315 	enum ieee80211_phymode mode;
4316 
4317 	/*
4318 	 * Change channels and update the h/w rate map
4319 	 * if we're switching; e.g. 11a to 11b/g.
4320 	 */
4321 	mode = ieee80211_chan2mode(chan);
4322 	if (mode != sc->sc_curmode)
4323 		ath_setcurmode(sc, mode);
4324 	sc->sc_curchan = chan;
4325 }
4326 
4327 /*
4328  * Set/change channels.  If the channel is really being changed,
4329  * it's done by resetting the chip.  To accomplish this we must
4330  * first cleanup any pending DMA, then restart stuff after a la
4331  * ath_init.
4332  */
4333 static int
4334 ath_chan_set(struct ath_softc *sc, struct ieee80211_channel *chan)
4335 {
4336 	struct ifnet *ifp = sc->sc_ifp;
4337 	struct ieee80211com *ic = ifp->if_l2com;
4338 	struct ath_hal *ah = sc->sc_ah;
4339 
4340 	DPRINTF(sc, ATH_DEBUG_RESET, "%s: %u (%u MHz, flags 0x%x)\n",
4341 	    __func__, ieee80211_chan2ieee(ic, chan),
4342 	    chan->ic_freq, chan->ic_flags);
4343 	if (chan != sc->sc_curchan) {
4344 		HAL_STATUS status;
4345 		/*
4346 		 * To switch channels clear any pending DMA operations;
4347 		 * wait long enough for the RX fifo to drain, reset the
4348 		 * hardware at the new frequency, and then re-enable
4349 		 * the relevant bits of the h/w.
4350 		 */
4351 		ath_hal_intrset(ah, 0);		/* disable interrupts */
4352 		ath_draintxq(sc);		/* clear pending tx frames */
4353 		ath_stoprecv(sc);		/* turn off frame recv */
4354 		if (!ath_hal_reset(ah, sc->sc_opmode, chan, AH_TRUE, &status)) {
4355 			if_printf(ifp, "%s: unable to reset "
4356 			    "channel %u (%u MHz, flags 0x%x), hal status %u\n",
4357 			    __func__, ieee80211_chan2ieee(ic, chan),
4358 			    chan->ic_freq, chan->ic_flags, status);
4359 			return EIO;
4360 		}
4361 		sc->sc_diversity = ath_hal_getdiversity(ah);
4362 
4363 		/*
4364 		 * Re-enable rx framework.
4365 		 */
4366 		if (ath_startrecv(sc) != 0) {
4367 			if_printf(ifp, "%s: unable to restart recv logic\n",
4368 			    __func__);
4369 			return EIO;
4370 		}
4371 
4372 		/*
4373 		 * Change channels and update the h/w rate map
4374 		 * if we're switching; e.g. 11a to 11b/g.
4375 		 */
4376 		ath_chan_change(sc, chan);
4377 
4378 		/*
4379 		 * Re-enable interrupts.
4380 		 */
4381 		ath_hal_intrset(ah, sc->sc_imask);
4382 	}
4383 	return 0;
4384 }
4385 
4386 /*
4387  * Periodically recalibrate the PHY to account
4388  * for temperature/environment changes.
4389  */
4390 static void
4391 ath_calibrate(void *arg)
4392 {
4393 	struct ath_softc *sc = arg;
4394 	struct ath_hal *ah = sc->sc_ah;
4395 	struct ifnet *ifp = sc->sc_ifp;
4396 	struct ieee80211com *ic = ifp->if_l2com;
4397 	HAL_BOOL longCal, isCalDone;
4398 	HAL_BOOL aniCal, shortCal = AH_FALSE;
4399 	int nextcal;
4400 
4401 	if (ic->ic_flags & IEEE80211_F_SCAN)	/* defer, off channel */
4402 		goto restart;
4403 	longCal = (ticks - sc->sc_lastlongcal >= ath_longcalinterval*hz);
4404 	aniCal = (ticks - sc->sc_lastani >= ath_anicalinterval*hz/1000);
4405 	if (sc->sc_doresetcal)
4406 		shortCal = (ticks - sc->sc_lastshortcal >= ath_shortcalinterval*hz/1000);
4407 
4408 	DPRINTF(sc, ATH_DEBUG_CALIBRATE, "%s: shortCal=%d; longCal=%d; aniCal=%d\n", __func__, shortCal, longCal, aniCal);
4409 	if (aniCal) {
4410 		sc->sc_stats.ast_ani_cal++;
4411 		sc->sc_lastani = ticks;
4412 		ath_hal_ani_poll(ah, sc->sc_curchan);
4413 	}
4414 
4415 	if (longCal) {
4416 		sc->sc_stats.ast_per_cal++;
4417 		sc->sc_lastlongcal = ticks;
4418 		if (ath_hal_getrfgain(ah) == HAL_RFGAIN_NEED_CHANGE) {
4419 			/*
4420 			 * Rfgain is out of bounds, reset the chip
4421 			 * to load new gain values.
4422 			 */
4423 			DPRINTF(sc, ATH_DEBUG_CALIBRATE,
4424 				"%s: rfgain change\n", __func__);
4425 			sc->sc_stats.ast_per_rfgain++;
4426 			ath_reset(ifp);
4427 		}
4428 		/*
4429 		 * If this long cal is after an idle period, then
4430 		 * reset the data collection state so we start fresh.
4431 		 */
4432 		if (sc->sc_resetcal) {
4433 			(void) ath_hal_calreset(ah, sc->sc_curchan);
4434 			sc->sc_lastcalreset = ticks;
4435 			sc->sc_lastshortcal = ticks;
4436 			sc->sc_resetcal = 0;
4437 			sc->sc_doresetcal = AH_TRUE;
4438 		}
4439 	}
4440 
4441 	/* Only call if we're doing a short/long cal, not for ANI calibration */
4442 	if (shortCal || longCal) {
4443 		if (ath_hal_calibrateN(ah, sc->sc_curchan, longCal, &isCalDone)) {
4444 			if (longCal) {
4445 				/*
4446 				 * Calibrate noise floor data again in case of change.
4447 				 */
4448 				ath_hal_process_noisefloor(ah);
4449 			}
4450 		} else {
4451 			DPRINTF(sc, ATH_DEBUG_ANY,
4452 				"%s: calibration of channel %u failed\n",
4453 				__func__, sc->sc_curchan->ic_freq);
4454 			sc->sc_stats.ast_per_calfail++;
4455 		}
4456 		if (shortCal)
4457 			sc->sc_lastshortcal = ticks;
4458 	}
4459 	if (!isCalDone) {
4460 restart:
4461 		/*
4462 		 * Use a shorter interval to potentially collect multiple
4463 		 * data samples required to complete calibration.  Once
4464 		 * we're told the work is done we drop back to a longer
4465 		 * interval between requests.  We're more aggressive doing
4466 		 * work when operating as an AP to improve operation right
4467 		 * after startup.
4468 		 */
4469 		sc->sc_lastshortcal = ticks;
4470 		nextcal = ath_shortcalinterval*hz/1000;
4471 		if (sc->sc_opmode != HAL_M_HOSTAP)
4472 			nextcal *= 10;
4473 		sc->sc_doresetcal = AH_TRUE;
4474 	} else {
4475 		/* nextcal should be the shortest time for next event */
4476 		nextcal = ath_longcalinterval*hz;
4477 		if (sc->sc_lastcalreset == 0)
4478 			sc->sc_lastcalreset = sc->sc_lastlongcal;
4479 		else if (ticks - sc->sc_lastcalreset >= ath_resetcalinterval*hz)
4480 			sc->sc_resetcal = 1;	/* setup reset next trip */
4481 		sc->sc_doresetcal = AH_FALSE;
4482 	}
4483 	/* ANI calibration may occur more often than short/long/resetcal */
4484 	if (ath_anicalinterval > 0)
4485 		nextcal = MIN(nextcal, ath_anicalinterval*hz/1000);
4486 
4487 	if (nextcal != 0) {
4488 		DPRINTF(sc, ATH_DEBUG_CALIBRATE, "%s: next +%u (%sisCalDone)\n",
4489 		    __func__, nextcal, isCalDone ? "" : "!");
4490 		callout_reset(&sc->sc_cal_ch, nextcal, ath_calibrate, sc);
4491 	} else {
4492 		DPRINTF(sc, ATH_DEBUG_CALIBRATE, "%s: calibration disabled\n",
4493 		    __func__);
4494 		/* NB: don't rearm timer */
4495 	}
4496 }
4497 
4498 static void
4499 ath_scan_start(struct ieee80211com *ic)
4500 {
4501 	struct ifnet *ifp = ic->ic_ifp;
4502 	struct ath_softc *sc = ifp->if_softc;
4503 	struct ath_hal *ah = sc->sc_ah;
4504 	u_int32_t rfilt;
4505 
4506 	/* XXX calibration timer? */
4507 
4508 	sc->sc_scanning = 1;
4509 	sc->sc_syncbeacon = 0;
4510 	rfilt = ath_calcrxfilter(sc);
4511 	ath_hal_setrxfilter(ah, rfilt);
4512 	ath_hal_setassocid(ah, ifp->if_broadcastaddr, 0);
4513 
4514 	DPRINTF(sc, ATH_DEBUG_STATE, "%s: RX filter 0x%x bssid %s aid 0\n",
4515 		 __func__, rfilt, ether_sprintf(ifp->if_broadcastaddr));
4516 }
4517 
4518 static void
4519 ath_scan_end(struct ieee80211com *ic)
4520 {
4521 	struct ifnet *ifp = ic->ic_ifp;
4522 	struct ath_softc *sc = ifp->if_softc;
4523 	struct ath_hal *ah = sc->sc_ah;
4524 	u_int32_t rfilt;
4525 
4526 	sc->sc_scanning = 0;
4527 	rfilt = ath_calcrxfilter(sc);
4528 	ath_hal_setrxfilter(ah, rfilt);
4529 	ath_hal_setassocid(ah, sc->sc_curbssid, sc->sc_curaid);
4530 
4531 	ath_hal_process_noisefloor(ah);
4532 
4533 	DPRINTF(sc, ATH_DEBUG_STATE, "%s: RX filter 0x%x bssid %s aid 0x%x\n",
4534 		 __func__, rfilt, ether_sprintf(sc->sc_curbssid),
4535 		 sc->sc_curaid);
4536 }
4537 
4538 static void
4539 ath_set_channel(struct ieee80211com *ic)
4540 {
4541 	struct ifnet *ifp = ic->ic_ifp;
4542 	struct ath_softc *sc = ifp->if_softc;
4543 
4544 	(void) ath_chan_set(sc, ic->ic_curchan);
4545 	/*
4546 	 * If we are returning to our bss channel then mark state
4547 	 * so the next recv'd beacon's tsf will be used to sync the
4548 	 * beacon timers.  Note that since we only hear beacons in
4549 	 * sta/ibss mode this has no effect in other operating modes.
4550 	 */
4551 	if (!sc->sc_scanning && ic->ic_curchan == ic->ic_bsschan)
4552 		sc->sc_syncbeacon = 1;
4553 }
4554 
4555 /*
4556  * Walk the vap list and check if there any vap's in RUN state.
4557  */
4558 static int
4559 ath_isanyrunningvaps(struct ieee80211vap *this)
4560 {
4561 	struct ieee80211com *ic = this->iv_ic;
4562 	struct ieee80211vap *vap;
4563 
4564 	IEEE80211_LOCK_ASSERT(ic);
4565 
4566 	TAILQ_FOREACH(vap, &ic->ic_vaps, iv_next) {
4567 		if (vap != this && vap->iv_state >= IEEE80211_S_RUN)
4568 			return 1;
4569 	}
4570 	return 0;
4571 }
4572 
4573 static int
4574 ath_newstate(struct ieee80211vap *vap, enum ieee80211_state nstate, int arg)
4575 {
4576 	struct ieee80211com *ic = vap->iv_ic;
4577 	struct ath_softc *sc = ic->ic_ifp->if_softc;
4578 	struct ath_vap *avp = ATH_VAP(vap);
4579 	struct ath_hal *ah = sc->sc_ah;
4580 	struct ieee80211_node *ni = NULL;
4581 	int i, error, stamode;
4582 	u_int32_t rfilt;
4583 	static const HAL_LED_STATE leds[] = {
4584 	    HAL_LED_INIT,	/* IEEE80211_S_INIT */
4585 	    HAL_LED_SCAN,	/* IEEE80211_S_SCAN */
4586 	    HAL_LED_AUTH,	/* IEEE80211_S_AUTH */
4587 	    HAL_LED_ASSOC, 	/* IEEE80211_S_ASSOC */
4588 	    HAL_LED_RUN, 	/* IEEE80211_S_CAC */
4589 	    HAL_LED_RUN, 	/* IEEE80211_S_RUN */
4590 	    HAL_LED_RUN, 	/* IEEE80211_S_CSA */
4591 	    HAL_LED_RUN, 	/* IEEE80211_S_SLEEP */
4592 	};
4593 
4594 	DPRINTF(sc, ATH_DEBUG_STATE, "%s: %s -> %s\n", __func__,
4595 		ieee80211_state_name[vap->iv_state],
4596 		ieee80211_state_name[nstate]);
4597 
4598 	callout_drain(&sc->sc_cal_ch);
4599 	ath_hal_setledstate(ah, leds[nstate]);	/* set LED */
4600 
4601 	if (nstate == IEEE80211_S_SCAN) {
4602 		/*
4603 		 * Scanning: turn off beacon miss and don't beacon.
4604 		 * Mark beacon state so when we reach RUN state we'll
4605 		 * [re]setup beacons.  Unblock the task q thread so
4606 		 * deferred interrupt processing is done.
4607 		 */
4608 		ath_hal_intrset(ah,
4609 		    sc->sc_imask &~ (HAL_INT_SWBA | HAL_INT_BMISS));
4610 		sc->sc_imask &= ~(HAL_INT_SWBA | HAL_INT_BMISS);
4611 		sc->sc_beacons = 0;
4612 		taskqueue_unblock(sc->sc_tq);
4613 	}
4614 
4615 	ni = vap->iv_bss;
4616 	rfilt = ath_calcrxfilter(sc);
4617 	stamode = (vap->iv_opmode == IEEE80211_M_STA ||
4618 		   vap->iv_opmode == IEEE80211_M_AHDEMO ||
4619 		   vap->iv_opmode == IEEE80211_M_IBSS);
4620 	if (stamode && nstate == IEEE80211_S_RUN) {
4621 		sc->sc_curaid = ni->ni_associd;
4622 		IEEE80211_ADDR_COPY(sc->sc_curbssid, ni->ni_bssid);
4623 		ath_hal_setassocid(ah, sc->sc_curbssid, sc->sc_curaid);
4624 	}
4625 	DPRINTF(sc, ATH_DEBUG_STATE, "%s: RX filter 0x%x bssid %s aid 0x%x\n",
4626 	   __func__, rfilt, ether_sprintf(sc->sc_curbssid), sc->sc_curaid);
4627 	ath_hal_setrxfilter(ah, rfilt);
4628 
4629 	/* XXX is this to restore keycache on resume? */
4630 	if (vap->iv_opmode != IEEE80211_M_STA &&
4631 	    (vap->iv_flags & IEEE80211_F_PRIVACY)) {
4632 		for (i = 0; i < IEEE80211_WEP_NKID; i++)
4633 			if (ath_hal_keyisvalid(ah, i))
4634 				ath_hal_keysetmac(ah, i, ni->ni_bssid);
4635 	}
4636 
4637 	/*
4638 	 * Invoke the parent method to do net80211 work.
4639 	 */
4640 	error = avp->av_newstate(vap, nstate, arg);
4641 	if (error != 0)
4642 		goto bad;
4643 
4644 	if (nstate == IEEE80211_S_RUN) {
4645 		/* NB: collect bss node again, it may have changed */
4646 		ni = vap->iv_bss;
4647 
4648 		DPRINTF(sc, ATH_DEBUG_STATE,
4649 		    "%s(RUN): iv_flags 0x%08x bintvl %d bssid %s "
4650 		    "capinfo 0x%04x chan %d\n", __func__,
4651 		    vap->iv_flags, ni->ni_intval, ether_sprintf(ni->ni_bssid),
4652 		    ni->ni_capinfo, ieee80211_chan2ieee(ic, ic->ic_curchan));
4653 
4654 		switch (vap->iv_opmode) {
4655 #ifdef IEEE80211_SUPPORT_TDMA
4656 		case IEEE80211_M_AHDEMO:
4657 			if ((vap->iv_caps & IEEE80211_C_TDMA) == 0)
4658 				break;
4659 			/* fall thru... */
4660 #endif
4661 		case IEEE80211_M_HOSTAP:
4662 		case IEEE80211_M_IBSS:
4663 		case IEEE80211_M_MBSS:
4664 			/*
4665 			 * Allocate and setup the beacon frame.
4666 			 *
4667 			 * Stop any previous beacon DMA.  This may be
4668 			 * necessary, for example, when an ibss merge
4669 			 * causes reconfiguration; there will be a state
4670 			 * transition from RUN->RUN that means we may
4671 			 * be called with beacon transmission active.
4672 			 */
4673 			ath_hal_stoptxdma(ah, sc->sc_bhalq);
4674 
4675 			error = ath_beacon_alloc(sc, ni);
4676 			if (error != 0)
4677 				goto bad;
4678 			/*
4679 			 * If joining an adhoc network defer beacon timer
4680 			 * configuration to the next beacon frame so we
4681 			 * have a current TSF to use.  Otherwise we're
4682 			 * starting an ibss/bss so there's no need to delay;
4683 			 * if this is the first vap moving to RUN state, then
4684 			 * beacon state needs to be [re]configured.
4685 			 */
4686 			if (vap->iv_opmode == IEEE80211_M_IBSS &&
4687 			    ni->ni_tstamp.tsf != 0) {
4688 				sc->sc_syncbeacon = 1;
4689 			} else if (!sc->sc_beacons) {
4690 #ifdef IEEE80211_SUPPORT_TDMA
4691 				if (vap->iv_caps & IEEE80211_C_TDMA)
4692 					ath_tdma_config(sc, vap);
4693 				else
4694 #endif
4695 					ath_beacon_config(sc, vap);
4696 				sc->sc_beacons = 1;
4697 			}
4698 			break;
4699 		case IEEE80211_M_STA:
4700 			/*
4701 			 * Defer beacon timer configuration to the next
4702 			 * beacon frame so we have a current TSF to use
4703 			 * (any TSF collected when scanning is likely old).
4704 			 */
4705 			sc->sc_syncbeacon = 1;
4706 			break;
4707 		case IEEE80211_M_MONITOR:
4708 			/*
4709 			 * Monitor mode vaps have only INIT->RUN and RUN->RUN
4710 			 * transitions so we must re-enable interrupts here to
4711 			 * handle the case of a single monitor mode vap.
4712 			 */
4713 			ath_hal_intrset(ah, sc->sc_imask);
4714 			break;
4715 		case IEEE80211_M_WDS:
4716 			break;
4717 		default:
4718 			break;
4719 		}
4720 		/*
4721 		 * Let the hal process statistics collected during a
4722 		 * scan so it can provide calibrated noise floor data.
4723 		 */
4724 		ath_hal_process_noisefloor(ah);
4725 		/*
4726 		 * Reset rssi stats; maybe not the best place...
4727 		 */
4728 		sc->sc_halstats.ns_avgbrssi = ATH_RSSI_DUMMY_MARKER;
4729 		sc->sc_halstats.ns_avgrssi = ATH_RSSI_DUMMY_MARKER;
4730 		sc->sc_halstats.ns_avgtxrssi = ATH_RSSI_DUMMY_MARKER;
4731 		/*
4732 		 * Finally, start any timers and the task q thread
4733 		 * (in case we didn't go through SCAN state).
4734 		 */
4735 		if (ath_longcalinterval != 0) {
4736 			/* start periodic recalibration timer */
4737 			callout_reset(&sc->sc_cal_ch, 1, ath_calibrate, sc);
4738 		} else {
4739 			DPRINTF(sc, ATH_DEBUG_CALIBRATE,
4740 			    "%s: calibration disabled\n", __func__);
4741 		}
4742 		taskqueue_unblock(sc->sc_tq);
4743 	} else if (nstate == IEEE80211_S_INIT) {
4744 		/*
4745 		 * If there are no vaps left in RUN state then
4746 		 * shutdown host/driver operation:
4747 		 * o disable interrupts
4748 		 * o disable the task queue thread
4749 		 * o mark beacon processing as stopped
4750 		 */
4751 		if (!ath_isanyrunningvaps(vap)) {
4752 			sc->sc_imask &= ~(HAL_INT_SWBA | HAL_INT_BMISS);
4753 			/* disable interrupts  */
4754 			ath_hal_intrset(ah, sc->sc_imask &~ HAL_INT_GLOBAL);
4755 			taskqueue_block(sc->sc_tq);
4756 			sc->sc_beacons = 0;
4757 		}
4758 #ifdef IEEE80211_SUPPORT_TDMA
4759 		ath_hal_setcca(ah, AH_TRUE);
4760 #endif
4761 	}
4762 bad:
4763 	return error;
4764 }
4765 
4766 /*
4767  * Allocate a key cache slot to the station so we can
4768  * setup a mapping from key index to node. The key cache
4769  * slot is needed for managing antenna state and for
4770  * compression when stations do not use crypto.  We do
4771  * it uniliaterally here; if crypto is employed this slot
4772  * will be reassigned.
4773  */
4774 static void
4775 ath_setup_stationkey(struct ieee80211_node *ni)
4776 {
4777 	struct ieee80211vap *vap = ni->ni_vap;
4778 	struct ath_softc *sc = vap->iv_ic->ic_ifp->if_softc;
4779 	ieee80211_keyix keyix, rxkeyix;
4780 
4781 	if (!ath_key_alloc(vap, &ni->ni_ucastkey, &keyix, &rxkeyix)) {
4782 		/*
4783 		 * Key cache is full; we'll fall back to doing
4784 		 * the more expensive lookup in software.  Note
4785 		 * this also means no h/w compression.
4786 		 */
4787 		/* XXX msg+statistic */
4788 	} else {
4789 		/* XXX locking? */
4790 		ni->ni_ucastkey.wk_keyix = keyix;
4791 		ni->ni_ucastkey.wk_rxkeyix = rxkeyix;
4792 		/* NB: must mark device key to get called back on delete */
4793 		ni->ni_ucastkey.wk_flags |= IEEE80211_KEY_DEVKEY;
4794 		IEEE80211_ADDR_COPY(ni->ni_ucastkey.wk_macaddr, ni->ni_macaddr);
4795 		/* NB: this will create a pass-thru key entry */
4796 		ath_keyset(sc, &ni->ni_ucastkey, vap->iv_bss);
4797 	}
4798 }
4799 
4800 /*
4801  * Setup driver-specific state for a newly associated node.
4802  * Note that we're called also on a re-associate, the isnew
4803  * param tells us if this is the first time or not.
4804  */
4805 static void
4806 ath_newassoc(struct ieee80211_node *ni, int isnew)
4807 {
4808 	struct ath_node *an = ATH_NODE(ni);
4809 	struct ieee80211vap *vap = ni->ni_vap;
4810 	struct ath_softc *sc = vap->iv_ic->ic_ifp->if_softc;
4811 	const struct ieee80211_txparam *tp = ni->ni_txparms;
4812 
4813 	an->an_mcastrix = ath_tx_findrix(sc, tp->mcastrate);
4814 	an->an_mgmtrix = ath_tx_findrix(sc, tp->mgmtrate);
4815 
4816 	ath_rate_newassoc(sc, an, isnew);
4817 	if (isnew &&
4818 	    (vap->iv_flags & IEEE80211_F_PRIVACY) == 0 && sc->sc_hasclrkey &&
4819 	    ni->ni_ucastkey.wk_keyix == IEEE80211_KEYIX_NONE)
4820 		ath_setup_stationkey(ni);
4821 }
4822 
4823 static int
4824 ath_setregdomain(struct ieee80211com *ic, struct ieee80211_regdomain *reg,
4825 	int nchans, struct ieee80211_channel chans[])
4826 {
4827 	struct ath_softc *sc = ic->ic_ifp->if_softc;
4828 	struct ath_hal *ah = sc->sc_ah;
4829 	HAL_STATUS status;
4830 
4831 	DPRINTF(sc, ATH_DEBUG_REGDOMAIN,
4832 	    "%s: rd %u cc %u location %c%s\n",
4833 	    __func__, reg->regdomain, reg->country, reg->location,
4834 	    reg->ecm ? " ecm" : "");
4835 
4836 	status = ath_hal_set_channels(ah, chans, nchans,
4837 	    reg->country, reg->regdomain);
4838 	if (status != HAL_OK) {
4839 		DPRINTF(sc, ATH_DEBUG_REGDOMAIN, "%s: failed, status %u\n",
4840 		    __func__, status);
4841 		return EINVAL;		/* XXX */
4842 	}
4843 	return 0;
4844 }
4845 
4846 static void
4847 ath_getradiocaps(struct ieee80211com *ic,
4848 	int maxchans, int *nchans, struct ieee80211_channel chans[])
4849 {
4850 	struct ath_softc *sc = ic->ic_ifp->if_softc;
4851 	struct ath_hal *ah = sc->sc_ah;
4852 
4853 	DPRINTF(sc, ATH_DEBUG_REGDOMAIN, "%s: use rd %u cc %d\n",
4854 	    __func__, SKU_DEBUG, CTRY_DEFAULT);
4855 
4856 	/* XXX check return */
4857 	(void) ath_hal_getchannels(ah, chans, maxchans, nchans,
4858 	    HAL_MODE_ALL, CTRY_DEFAULT, SKU_DEBUG, AH_TRUE);
4859 
4860 }
4861 
4862 static int
4863 ath_getchannels(struct ath_softc *sc)
4864 {
4865 	struct ifnet *ifp = sc->sc_ifp;
4866 	struct ieee80211com *ic = ifp->if_l2com;
4867 	struct ath_hal *ah = sc->sc_ah;
4868 	HAL_STATUS status;
4869 
4870 	/*
4871 	 * Collect channel set based on EEPROM contents.
4872 	 */
4873 	status = ath_hal_init_channels(ah, ic->ic_channels, IEEE80211_CHAN_MAX,
4874 	    &ic->ic_nchans, HAL_MODE_ALL, CTRY_DEFAULT, SKU_NONE, AH_TRUE);
4875 	if (status != HAL_OK) {
4876 		if_printf(ifp, "%s: unable to collect channel list from hal, "
4877 		    "status %d\n", __func__, status);
4878 		return EINVAL;
4879 	}
4880 	(void) ath_hal_getregdomain(ah, &sc->sc_eerd);
4881 	ath_hal_getcountrycode(ah, &sc->sc_eecc);	/* NB: cannot fail */
4882 	/* XXX map Atheros sku's to net80211 SKU's */
4883 	/* XXX net80211 types too small */
4884 	ic->ic_regdomain.regdomain = (uint16_t) sc->sc_eerd;
4885 	ic->ic_regdomain.country = (uint16_t) sc->sc_eecc;
4886 	ic->ic_regdomain.isocc[0] = ' ';	/* XXX don't know */
4887 	ic->ic_regdomain.isocc[1] = ' ';
4888 
4889 	ic->ic_regdomain.ecm = 1;
4890 	ic->ic_regdomain.location = 'I';
4891 
4892 	DPRINTF(sc, ATH_DEBUG_REGDOMAIN,
4893 	    "%s: eeprom rd %u cc %u (mapped rd %u cc %u) location %c%s\n",
4894 	    __func__, sc->sc_eerd, sc->sc_eecc,
4895 	    ic->ic_regdomain.regdomain, ic->ic_regdomain.country,
4896 	    ic->ic_regdomain.location, ic->ic_regdomain.ecm ? " ecm" : "");
4897 	return 0;
4898 }
4899 
4900 static void
4901 ath_led_done(void *arg)
4902 {
4903 	struct ath_softc *sc = arg;
4904 
4905 	sc->sc_blinking = 0;
4906 }
4907 
4908 /*
4909  * Turn the LED off: flip the pin and then set a timer so no
4910  * update will happen for the specified duration.
4911  */
4912 static void
4913 ath_led_off(void *arg)
4914 {
4915 	struct ath_softc *sc = arg;
4916 
4917 	ath_hal_gpioset(sc->sc_ah, sc->sc_ledpin, !sc->sc_ledon);
4918 	callout_reset(&sc->sc_ledtimer, sc->sc_ledoff, ath_led_done, sc);
4919 }
4920 
4921 /*
4922  * Blink the LED according to the specified on/off times.
4923  */
4924 static void
4925 ath_led_blink(struct ath_softc *sc, int on, int off)
4926 {
4927 	DPRINTF(sc, ATH_DEBUG_LED, "%s: on %u off %u\n", __func__, on, off);
4928 	ath_hal_gpioset(sc->sc_ah, sc->sc_ledpin, sc->sc_ledon);
4929 	sc->sc_blinking = 1;
4930 	sc->sc_ledoff = off;
4931 	callout_reset(&sc->sc_ledtimer, on, ath_led_off, sc);
4932 }
4933 
4934 static void
4935 ath_led_event(struct ath_softc *sc, int rix)
4936 {
4937 	sc->sc_ledevent = ticks;	/* time of last event */
4938 	if (sc->sc_blinking)		/* don't interrupt active blink */
4939 		return;
4940 	ath_led_blink(sc, sc->sc_hwmap[rix].ledon, sc->sc_hwmap[rix].ledoff);
4941 }
4942 
4943 static int
4944 ath_rate_setup(struct ath_softc *sc, u_int mode)
4945 {
4946 	struct ath_hal *ah = sc->sc_ah;
4947 	const HAL_RATE_TABLE *rt;
4948 
4949 	switch (mode) {
4950 	case IEEE80211_MODE_11A:
4951 		rt = ath_hal_getratetable(ah, HAL_MODE_11A);
4952 		break;
4953 	case IEEE80211_MODE_HALF:
4954 		rt = ath_hal_getratetable(ah, HAL_MODE_11A_HALF_RATE);
4955 		break;
4956 	case IEEE80211_MODE_QUARTER:
4957 		rt = ath_hal_getratetable(ah, HAL_MODE_11A_QUARTER_RATE);
4958 		break;
4959 	case IEEE80211_MODE_11B:
4960 		rt = ath_hal_getratetable(ah, HAL_MODE_11B);
4961 		break;
4962 	case IEEE80211_MODE_11G:
4963 		rt = ath_hal_getratetable(ah, HAL_MODE_11G);
4964 		break;
4965 	case IEEE80211_MODE_TURBO_A:
4966 		rt = ath_hal_getratetable(ah, HAL_MODE_108A);
4967 		break;
4968 	case IEEE80211_MODE_TURBO_G:
4969 		rt = ath_hal_getratetable(ah, HAL_MODE_108G);
4970 		break;
4971 	case IEEE80211_MODE_STURBO_A:
4972 		rt = ath_hal_getratetable(ah, HAL_MODE_TURBO);
4973 		break;
4974 	case IEEE80211_MODE_11NA:
4975 		rt = ath_hal_getratetable(ah, HAL_MODE_11NA_HT20);
4976 		break;
4977 	case IEEE80211_MODE_11NG:
4978 		rt = ath_hal_getratetable(ah, HAL_MODE_11NG_HT20);
4979 		break;
4980 	default:
4981 		DPRINTF(sc, ATH_DEBUG_ANY, "%s: invalid mode %u\n",
4982 			__func__, mode);
4983 		return 0;
4984 	}
4985 	sc->sc_rates[mode] = rt;
4986 	return (rt != NULL);
4987 }
4988 
4989 static void
4990 ath_setcurmode(struct ath_softc *sc, enum ieee80211_phymode mode)
4991 {
4992 #define	N(a)	(sizeof(a)/sizeof(a[0]))
4993 	/* NB: on/off times from the Atheros NDIS driver, w/ permission */
4994 	static const struct {
4995 		u_int		rate;		/* tx/rx 802.11 rate */
4996 		u_int16_t	timeOn;		/* LED on time (ms) */
4997 		u_int16_t	timeOff;	/* LED off time (ms) */
4998 	} blinkrates[] = {
4999 		{ 108,  40,  10 },
5000 		{  96,  44,  11 },
5001 		{  72,  50,  13 },
5002 		{  48,  57,  14 },
5003 		{  36,  67,  16 },
5004 		{  24,  80,  20 },
5005 		{  22, 100,  25 },
5006 		{  18, 133,  34 },
5007 		{  12, 160,  40 },
5008 		{  10, 200,  50 },
5009 		{   6, 240,  58 },
5010 		{   4, 267,  66 },
5011 		{   2, 400, 100 },
5012 		{   0, 500, 130 },
5013 		/* XXX half/quarter rates */
5014 	};
5015 	const HAL_RATE_TABLE *rt;
5016 	int i, j;
5017 
5018 	memset(sc->sc_rixmap, 0xff, sizeof(sc->sc_rixmap));
5019 	rt = sc->sc_rates[mode];
5020 	KASSERT(rt != NULL, ("no h/w rate set for phy mode %u", mode));
5021 	for (i = 0; i < rt->rateCount; i++) {
5022 		uint8_t ieeerate = rt->info[i].dot11Rate & IEEE80211_RATE_VAL;
5023 		if (rt->info[i].phy != IEEE80211_T_HT)
5024 			sc->sc_rixmap[ieeerate] = i;
5025 		else
5026 			sc->sc_rixmap[ieeerate | IEEE80211_RATE_MCS] = i;
5027 	}
5028 	memset(sc->sc_hwmap, 0, sizeof(sc->sc_hwmap));
5029 	for (i = 0; i < N(sc->sc_hwmap); i++) {
5030 		if (i >= rt->rateCount) {
5031 			sc->sc_hwmap[i].ledon = (500 * hz) / 1000;
5032 			sc->sc_hwmap[i].ledoff = (130 * hz) / 1000;
5033 			continue;
5034 		}
5035 		sc->sc_hwmap[i].ieeerate =
5036 			rt->info[i].dot11Rate & IEEE80211_RATE_VAL;
5037 		if (rt->info[i].phy == IEEE80211_T_HT)
5038 			sc->sc_hwmap[i].ieeerate |= IEEE80211_RATE_MCS;
5039 		sc->sc_hwmap[i].txflags = IEEE80211_RADIOTAP_F_DATAPAD;
5040 		if (rt->info[i].shortPreamble ||
5041 		    rt->info[i].phy == IEEE80211_T_OFDM)
5042 			sc->sc_hwmap[i].txflags |= IEEE80211_RADIOTAP_F_SHORTPRE;
5043 		sc->sc_hwmap[i].rxflags = sc->sc_hwmap[i].txflags;
5044 		for (j = 0; j < N(blinkrates)-1; j++)
5045 			if (blinkrates[j].rate == sc->sc_hwmap[i].ieeerate)
5046 				break;
5047 		/* NB: this uses the last entry if the rate isn't found */
5048 		/* XXX beware of overlow */
5049 		sc->sc_hwmap[i].ledon = (blinkrates[j].timeOn * hz) / 1000;
5050 		sc->sc_hwmap[i].ledoff = (blinkrates[j].timeOff * hz) / 1000;
5051 	}
5052 	sc->sc_currates = rt;
5053 	sc->sc_curmode = mode;
5054 	/*
5055 	 * All protection frames are transmited at 2Mb/s for
5056 	 * 11g, otherwise at 1Mb/s.
5057 	 */
5058 	if (mode == IEEE80211_MODE_11G)
5059 		sc->sc_protrix = ath_tx_findrix(sc, 2*2);
5060 	else
5061 		sc->sc_protrix = ath_tx_findrix(sc, 2*1);
5062 	/* NB: caller is responsible for resetting rate control state */
5063 #undef N
5064 }
5065 
5066 static void
5067 ath_watchdog(void *arg)
5068 {
5069 	struct ath_softc *sc = arg;
5070 
5071 	if (sc->sc_wd_timer != 0 && --sc->sc_wd_timer == 0) {
5072 		struct ifnet *ifp = sc->sc_ifp;
5073 		uint32_t hangs;
5074 
5075 		if (ath_hal_gethangstate(sc->sc_ah, 0xffff, &hangs) &&
5076 		    hangs != 0) {
5077 			if_printf(ifp, "%s hang detected (0x%x)\n",
5078 			    hangs & 0xff ? "bb" : "mac", hangs);
5079 		} else
5080 			if_printf(ifp, "device timeout\n");
5081 		ath_reset(ifp);
5082 		ifp->if_oerrors++;
5083 		sc->sc_stats.ast_watchdog++;
5084 	}
5085 	callout_schedule(&sc->sc_wd_ch, hz);
5086 }
5087 
5088 #ifdef ATH_DIAGAPI
5089 /*
5090  * Diagnostic interface to the HAL.  This is used by various
5091  * tools to do things like retrieve register contents for
5092  * debugging.  The mechanism is intentionally opaque so that
5093  * it can change frequently w/o concern for compatiblity.
5094  */
5095 static int
5096 ath_ioctl_diag(struct ath_softc *sc, struct ath_diag *ad)
5097 {
5098 	struct ath_hal *ah = sc->sc_ah;
5099 	u_int id = ad->ad_id & ATH_DIAG_ID;
5100 	void *indata = NULL;
5101 	void *outdata = NULL;
5102 	u_int32_t insize = ad->ad_in_size;
5103 	u_int32_t outsize = ad->ad_out_size;
5104 	int error = 0;
5105 
5106 	if (ad->ad_id & ATH_DIAG_IN) {
5107 		/*
5108 		 * Copy in data.
5109 		 */
5110 		indata = malloc(insize, M_TEMP, M_NOWAIT);
5111 		if (indata == NULL) {
5112 			error = ENOMEM;
5113 			goto bad;
5114 		}
5115 		error = copyin(ad->ad_in_data, indata, insize);
5116 		if (error)
5117 			goto bad;
5118 	}
5119 	if (ad->ad_id & ATH_DIAG_DYN) {
5120 		/*
5121 		 * Allocate a buffer for the results (otherwise the HAL
5122 		 * returns a pointer to a buffer where we can read the
5123 		 * results).  Note that we depend on the HAL leaving this
5124 		 * pointer for us to use below in reclaiming the buffer;
5125 		 * may want to be more defensive.
5126 		 */
5127 		outdata = malloc(outsize, M_TEMP, M_NOWAIT);
5128 		if (outdata == NULL) {
5129 			error = ENOMEM;
5130 			goto bad;
5131 		}
5132 	}
5133 	if (ath_hal_getdiagstate(ah, id, indata, insize, &outdata, &outsize)) {
5134 		if (outsize < ad->ad_out_size)
5135 			ad->ad_out_size = outsize;
5136 		if (outdata != NULL)
5137 			error = copyout(outdata, ad->ad_out_data,
5138 					ad->ad_out_size);
5139 	} else {
5140 		error = EINVAL;
5141 	}
5142 bad:
5143 	if ((ad->ad_id & ATH_DIAG_IN) && indata != NULL)
5144 		free(indata, M_TEMP);
5145 	if ((ad->ad_id & ATH_DIAG_DYN) && outdata != NULL)
5146 		free(outdata, M_TEMP);
5147 	return error;
5148 }
5149 #endif /* ATH_DIAGAPI */
5150 
5151 static int
5152 ath_ioctl(struct ifnet *ifp, u_long cmd, caddr_t data)
5153 {
5154 #define	IS_RUNNING(ifp) \
5155 	((ifp->if_flags & IFF_UP) && (ifp->if_drv_flags & IFF_DRV_RUNNING))
5156 	struct ath_softc *sc = ifp->if_softc;
5157 	struct ieee80211com *ic = ifp->if_l2com;
5158 	struct ifreq *ifr = (struct ifreq *)data;
5159 	const HAL_RATE_TABLE *rt;
5160 	int error = 0;
5161 
5162 	switch (cmd) {
5163 	case SIOCSIFFLAGS:
5164 		ATH_LOCK(sc);
5165 		if (IS_RUNNING(ifp)) {
5166 			/*
5167 			 * To avoid rescanning another access point,
5168 			 * do not call ath_init() here.  Instead,
5169 			 * only reflect promisc mode settings.
5170 			 */
5171 			ath_mode_init(sc);
5172 		} else if (ifp->if_flags & IFF_UP) {
5173 			/*
5174 			 * Beware of being called during attach/detach
5175 			 * to reset promiscuous mode.  In that case we
5176 			 * will still be marked UP but not RUNNING.
5177 			 * However trying to re-init the interface
5178 			 * is the wrong thing to do as we've already
5179 			 * torn down much of our state.  There's
5180 			 * probably a better way to deal with this.
5181 			 */
5182 			if (!sc->sc_invalid)
5183 				ath_init(sc);	/* XXX lose error */
5184 		} else {
5185 			ath_stop_locked(ifp);
5186 #ifdef notyet
5187 			/* XXX must wakeup in places like ath_vap_delete */
5188 			if (!sc->sc_invalid)
5189 				ath_hal_setpower(sc->sc_ah, HAL_PM_FULL_SLEEP);
5190 #endif
5191 		}
5192 		ATH_UNLOCK(sc);
5193 		break;
5194 	case SIOCGIFMEDIA:
5195 	case SIOCSIFMEDIA:
5196 		error = ifmedia_ioctl(ifp, ifr, &ic->ic_media, cmd);
5197 		break;
5198 	case SIOCGATHSTATS:
5199 		/* NB: embed these numbers to get a consistent view */
5200 		sc->sc_stats.ast_tx_packets = ifp->if_opackets;
5201 		sc->sc_stats.ast_rx_packets = ifp->if_ipackets;
5202 		sc->sc_stats.ast_tx_rssi = ATH_RSSI(sc->sc_halstats.ns_avgtxrssi);
5203 		sc->sc_stats.ast_rx_rssi = ATH_RSSI(sc->sc_halstats.ns_avgrssi);
5204 #ifdef IEEE80211_SUPPORT_TDMA
5205 		sc->sc_stats.ast_tdma_tsfadjp = TDMA_AVG(sc->sc_avgtsfdeltap);
5206 		sc->sc_stats.ast_tdma_tsfadjm = TDMA_AVG(sc->sc_avgtsfdeltam);
5207 #endif
5208 		rt = sc->sc_currates;
5209 		sc->sc_stats.ast_tx_rate =
5210 		    rt->info[sc->sc_txrix].dot11Rate &~ IEEE80211_RATE_BASIC;
5211 		if (rt->info[sc->sc_txrix].phy & IEEE80211_T_HT)
5212 			sc->sc_stats.ast_tx_rate |= IEEE80211_RATE_MCS;
5213 		return copyout(&sc->sc_stats,
5214 		    ifr->ifr_data, sizeof (sc->sc_stats));
5215 	case SIOCZATHSTATS:
5216 		error = priv_check(curthread, PRIV_DRIVER);
5217 		if (error == 0)
5218 			memset(&sc->sc_stats, 0, sizeof(sc->sc_stats));
5219 		break;
5220 #ifdef ATH_DIAGAPI
5221 	case SIOCGATHDIAG:
5222 		error = ath_ioctl_diag(sc, (struct ath_diag *) ifr);
5223 		break;
5224 #endif
5225 	case SIOCGIFADDR:
5226 		error = ether_ioctl(ifp, cmd, data);
5227 		break;
5228 	default:
5229 		error = EINVAL;
5230 		break;
5231 	}
5232 	return error;
5233 #undef IS_RUNNING
5234 }
5235 
5236 /*
5237  * Announce various information on device/driver attach.
5238  */
5239 static void
5240 ath_announce(struct ath_softc *sc)
5241 {
5242 	struct ifnet *ifp = sc->sc_ifp;
5243 	struct ath_hal *ah = sc->sc_ah;
5244 
5245 	if_printf(ifp, "AR%s mac %d.%d RF%s phy %d.%d\n",
5246 		ath_hal_mac_name(ah), ah->ah_macVersion, ah->ah_macRev,
5247 		ath_hal_rf_name(ah), ah->ah_phyRev >> 4, ah->ah_phyRev & 0xf);
5248 	if (bootverbose) {
5249 		int i;
5250 		for (i = 0; i <= WME_AC_VO; i++) {
5251 			struct ath_txq *txq = sc->sc_ac2q[i];
5252 			if_printf(ifp, "Use hw queue %u for %s traffic\n",
5253 				txq->axq_qnum, ieee80211_wme_acnames[i]);
5254 		}
5255 		if_printf(ifp, "Use hw queue %u for CAB traffic\n",
5256 			sc->sc_cabq->axq_qnum);
5257 		if_printf(ifp, "Use hw queue %u for beacons\n", sc->sc_bhalq);
5258 	}
5259 	if (ath_rxbuf != ATH_RXBUF)
5260 		if_printf(ifp, "using %u rx buffers\n", ath_rxbuf);
5261 	if (ath_txbuf != ATH_TXBUF)
5262 		if_printf(ifp, "using %u tx buffers\n", ath_txbuf);
5263 	if (sc->sc_mcastkey && bootverbose)
5264 		if_printf(ifp, "using multicast key search\n");
5265 }
5266 
5267 #ifdef IEEE80211_SUPPORT_TDMA
5268 static __inline uint32_t
5269 ath_hal_getnexttbtt(struct ath_hal *ah)
5270 {
5271 #define	AR_TIMER0	0x8028
5272 	return OS_REG_READ(ah, AR_TIMER0);
5273 }
5274 
5275 static __inline void
5276 ath_hal_adjusttsf(struct ath_hal *ah, int32_t tsfdelta)
5277 {
5278 	/* XXX handle wrap/overflow */
5279 	OS_REG_WRITE(ah, AR_TSF_L32, OS_REG_READ(ah, AR_TSF_L32) + tsfdelta);
5280 }
5281 
5282 static void
5283 ath_tdma_settimers(struct ath_softc *sc, u_int32_t nexttbtt, u_int32_t bintval)
5284 {
5285 	struct ath_hal *ah = sc->sc_ah;
5286 	HAL_BEACON_TIMERS bt;
5287 
5288 	bt.bt_intval = bintval | HAL_BEACON_ENA;
5289 	bt.bt_nexttbtt = nexttbtt;
5290 	bt.bt_nextdba = (nexttbtt<<3) - sc->sc_tdmadbaprep;
5291 	bt.bt_nextswba = (nexttbtt<<3) - sc->sc_tdmaswbaprep;
5292 	bt.bt_nextatim = nexttbtt+1;
5293 	ath_hal_beaconsettimers(ah, &bt);
5294 }
5295 
5296 /*
5297  * Calculate the beacon interval.  This is periodic in the
5298  * superframe for the bss.  We assume each station is configured
5299  * identically wrt transmit rate so the guard time we calculate
5300  * above will be the same on all stations.  Note we need to
5301  * factor in the xmit time because the hardware will schedule
5302  * a frame for transmit if the start of the frame is within
5303  * the burst time.  When we get hardware that properly kills
5304  * frames in the PCU we can reduce/eliminate the guard time.
5305  *
5306  * Roundup to 1024 is so we have 1 TU buffer in the guard time
5307  * to deal with the granularity of the nexttbtt timer.  11n MAC's
5308  * with 1us timer granularity should allow us to reduce/eliminate
5309  * this.
5310  */
5311 static void
5312 ath_tdma_bintvalsetup(struct ath_softc *sc,
5313 	const struct ieee80211_tdma_state *tdma)
5314 {
5315 	/* copy from vap state (XXX check all vaps have same value?) */
5316 	sc->sc_tdmaslotlen = tdma->tdma_slotlen;
5317 
5318 	sc->sc_tdmabintval = roundup((sc->sc_tdmaslotlen+sc->sc_tdmaguard) *
5319 		tdma->tdma_slotcnt, 1024);
5320 	sc->sc_tdmabintval >>= 10;		/* TSF -> TU */
5321 	if (sc->sc_tdmabintval & 1)
5322 		sc->sc_tdmabintval++;
5323 
5324 	if (tdma->tdma_slot == 0) {
5325 		/*
5326 		 * Only slot 0 beacons; other slots respond.
5327 		 */
5328 		sc->sc_imask |= HAL_INT_SWBA;
5329 		sc->sc_tdmaswba = 0;		/* beacon immediately */
5330 	} else {
5331 		/* XXX all vaps must be slot 0 or slot !0 */
5332 		sc->sc_imask &= ~HAL_INT_SWBA;
5333 	}
5334 }
5335 
5336 /*
5337  * Max 802.11 overhead.  This assumes no 4-address frames and
5338  * the encapsulation done by ieee80211_encap (llc).  We also
5339  * include potential crypto overhead.
5340  */
5341 #define	IEEE80211_MAXOVERHEAD \
5342 	(sizeof(struct ieee80211_qosframe) \
5343 	 + sizeof(struct llc) \
5344 	 + IEEE80211_ADDR_LEN \
5345 	 + IEEE80211_WEP_IVLEN \
5346 	 + IEEE80211_WEP_KIDLEN \
5347 	 + IEEE80211_WEP_CRCLEN \
5348 	 + IEEE80211_WEP_MICLEN \
5349 	 + IEEE80211_CRC_LEN)
5350 
5351 /*
5352  * Setup initially for tdma operation.  Start the beacon
5353  * timers and enable SWBA if we are slot 0.  Otherwise
5354  * we wait for slot 0 to arrive so we can sync up before
5355  * starting to transmit.
5356  */
5357 static void
5358 ath_tdma_config(struct ath_softc *sc, struct ieee80211vap *vap)
5359 {
5360 	struct ath_hal *ah = sc->sc_ah;
5361 	struct ifnet *ifp = sc->sc_ifp;
5362 	struct ieee80211com *ic = ifp->if_l2com;
5363 	const struct ieee80211_txparam *tp;
5364 	const struct ieee80211_tdma_state *tdma = NULL;
5365 	int rix;
5366 
5367 	if (vap == NULL) {
5368 		vap = TAILQ_FIRST(&ic->ic_vaps);   /* XXX */
5369 		if (vap == NULL) {
5370 			if_printf(ifp, "%s: no vaps?\n", __func__);
5371 			return;
5372 		}
5373 	}
5374 	tp = vap->iv_bss->ni_txparms;
5375 	/*
5376 	 * Calculate the guard time for each slot.  This is the
5377 	 * time to send a maximal-size frame according to the
5378 	 * fixed/lowest transmit rate.  Note that the interface
5379 	 * mtu does not include the 802.11 overhead so we must
5380 	 * tack that on (ath_hal_computetxtime includes the
5381 	 * preamble and plcp in it's calculation).
5382 	 */
5383 	tdma = vap->iv_tdma;
5384 	if (tp->ucastrate != IEEE80211_FIXED_RATE_NONE)
5385 		rix = ath_tx_findrix(sc, tp->ucastrate);
5386 	else
5387 		rix = ath_tx_findrix(sc, tp->mcastrate);
5388 	/* XXX short preamble assumed */
5389 	sc->sc_tdmaguard = ath_hal_computetxtime(ah, sc->sc_currates,
5390 		ifp->if_mtu + IEEE80211_MAXOVERHEAD, rix, AH_TRUE);
5391 
5392 	ath_hal_intrset(ah, 0);
5393 
5394 	ath_beaconq_config(sc);			/* setup h/w beacon q */
5395 	if (sc->sc_setcca)
5396 		ath_hal_setcca(ah, AH_FALSE);	/* disable CCA */
5397 	ath_tdma_bintvalsetup(sc, tdma);	/* calculate beacon interval */
5398 	ath_tdma_settimers(sc, sc->sc_tdmabintval,
5399 		sc->sc_tdmabintval | HAL_BEACON_RESET_TSF);
5400 	sc->sc_syncbeacon = 0;
5401 
5402 	sc->sc_avgtsfdeltap = TDMA_DUMMY_MARKER;
5403 	sc->sc_avgtsfdeltam = TDMA_DUMMY_MARKER;
5404 
5405 	ath_hal_intrset(ah, sc->sc_imask);
5406 
5407 	DPRINTF(sc, ATH_DEBUG_TDMA, "%s: slot %u len %uus cnt %u "
5408 	    "bsched %u guard %uus bintval %u TU dba prep %u\n", __func__,
5409 	    tdma->tdma_slot, tdma->tdma_slotlen, tdma->tdma_slotcnt,
5410 	    tdma->tdma_bintval, sc->sc_tdmaguard, sc->sc_tdmabintval,
5411 	    sc->sc_tdmadbaprep);
5412 }
5413 
5414 /*
5415  * Update tdma operation.  Called from the 802.11 layer
5416  * when a beacon is received from the TDMA station operating
5417  * in the slot immediately preceding us in the bss.  Use
5418  * the rx timestamp for the beacon frame to update our
5419  * beacon timers so we follow their schedule.  Note that
5420  * by using the rx timestamp we implicitly include the
5421  * propagation delay in our schedule.
5422  */
5423 static void
5424 ath_tdma_update(struct ieee80211_node *ni,
5425 	const struct ieee80211_tdma_param *tdma, int changed)
5426 {
5427 #define	TSF_TO_TU(_h,_l) \
5428 	((((u_int32_t)(_h)) << 22) | (((u_int32_t)(_l)) >> 10))
5429 #define	TU_TO_TSF(_tu)	(((u_int64_t)(_tu)) << 10)
5430 	struct ieee80211vap *vap = ni->ni_vap;
5431 	struct ieee80211com *ic = ni->ni_ic;
5432 	struct ath_softc *sc = ic->ic_ifp->if_softc;
5433 	struct ath_hal *ah = sc->sc_ah;
5434 	const HAL_RATE_TABLE *rt = sc->sc_currates;
5435 	u_int64_t tsf, rstamp, nextslot;
5436 	u_int32_t txtime, nextslottu, timer0;
5437 	int32_t tudelta, tsfdelta;
5438 	const struct ath_rx_status *rs;
5439 	int rix;
5440 
5441 	sc->sc_stats.ast_tdma_update++;
5442 
5443 	/*
5444 	 * Check for and adopt configuration changes.
5445 	 */
5446 	if (changed != 0) {
5447 		const struct ieee80211_tdma_state *ts = vap->iv_tdma;
5448 
5449 		ath_tdma_bintvalsetup(sc, ts);
5450 		if (changed & TDMA_UPDATE_SLOTLEN)
5451 			ath_wme_update(ic);
5452 
5453 		DPRINTF(sc, ATH_DEBUG_TDMA,
5454 		    "%s: adopt slot %u slotcnt %u slotlen %u us "
5455 		    "bintval %u TU\n", __func__,
5456 		    ts->tdma_slot, ts->tdma_slotcnt, ts->tdma_slotlen,
5457 		    sc->sc_tdmabintval);
5458 
5459 		/* XXX right? */
5460 		ath_hal_intrset(ah, sc->sc_imask);
5461 		/* NB: beacon timers programmed below */
5462 	}
5463 
5464 	/* extend rx timestamp to 64 bits */
5465 	rs = sc->sc_lastrs;
5466 	tsf = ath_hal_gettsf64(ah);
5467 	rstamp = ath_extend_tsf(rs->rs_tstamp, tsf);
5468 	/*
5469 	 * The rx timestamp is set by the hardware on completing
5470 	 * reception (at the point where the rx descriptor is DMA'd
5471 	 * to the host).  To find the start of our next slot we
5472 	 * must adjust this time by the time required to send
5473 	 * the packet just received.
5474 	 */
5475 	rix = rt->rateCodeToIndex[rs->rs_rate];
5476 	txtime = ath_hal_computetxtime(ah, rt, rs->rs_datalen, rix,
5477 	    rt->info[rix].shortPreamble);
5478 	/* NB: << 9 is to cvt to TU and /2 */
5479 	nextslot = (rstamp - txtime) + (sc->sc_tdmabintval << 9);
5480 	nextslottu = TSF_TO_TU(nextslot>>32, nextslot) & HAL_BEACON_PERIOD;
5481 
5482 	/*
5483 	 * TIMER0 is the h/w's idea of NextTBTT (in TU's).  Convert
5484 	 * to usecs and calculate the difference between what the
5485 	 * other station thinks and what we have programmed.  This
5486 	 * lets us figure how to adjust our timers to match.  The
5487 	 * adjustments are done by pulling the TSF forward and possibly
5488 	 * rewriting the beacon timers.
5489 	 */
5490 	timer0 = ath_hal_getnexttbtt(ah);
5491 	tsfdelta = (int32_t)((nextslot % TU_TO_TSF(HAL_BEACON_PERIOD+1)) - TU_TO_TSF(timer0));
5492 
5493 	DPRINTF(sc, ATH_DEBUG_TDMA_TIMER,
5494 	    "tsfdelta %d avg +%d/-%d\n", tsfdelta,
5495 	    TDMA_AVG(sc->sc_avgtsfdeltap), TDMA_AVG(sc->sc_avgtsfdeltam));
5496 
5497 	if (tsfdelta < 0) {
5498 		TDMA_SAMPLE(sc->sc_avgtsfdeltap, 0);
5499 		TDMA_SAMPLE(sc->sc_avgtsfdeltam, -tsfdelta);
5500 		tsfdelta = -tsfdelta % 1024;
5501 		nextslottu++;
5502 	} else if (tsfdelta > 0) {
5503 		TDMA_SAMPLE(sc->sc_avgtsfdeltap, tsfdelta);
5504 		TDMA_SAMPLE(sc->sc_avgtsfdeltam, 0);
5505 		tsfdelta = 1024 - (tsfdelta % 1024);
5506 		nextslottu++;
5507 	} else {
5508 		TDMA_SAMPLE(sc->sc_avgtsfdeltap, 0);
5509 		TDMA_SAMPLE(sc->sc_avgtsfdeltam, 0);
5510 	}
5511 	tudelta = nextslottu - timer0;
5512 
5513 	/*
5514 	 * Copy sender's timetstamp into tdma ie so they can
5515 	 * calculate roundtrip time.  We submit a beacon frame
5516 	 * below after any timer adjustment.  The frame goes out
5517 	 * at the next TBTT so the sender can calculate the
5518 	 * roundtrip by inspecting the tdma ie in our beacon frame.
5519 	 *
5520 	 * NB: This tstamp is subtlely preserved when
5521 	 *     IEEE80211_BEACON_TDMA is marked (e.g. when the
5522 	 *     slot position changes) because ieee80211_add_tdma
5523 	 *     skips over the data.
5524 	 */
5525 	memcpy(ATH_VAP(vap)->av_boff.bo_tdma +
5526 		__offsetof(struct ieee80211_tdma_param, tdma_tstamp),
5527 		&ni->ni_tstamp.data, 8);
5528 #if 0
5529 	DPRINTF(sc, ATH_DEBUG_TDMA_TIMER,
5530 	    "tsf %llu nextslot %llu (%d, %d) nextslottu %u timer0 %u (%d)\n",
5531 	    (unsigned long long) tsf, (unsigned long long) nextslot,
5532 	    (int)(nextslot - tsf), tsfdelta,
5533 	    nextslottu, timer0, tudelta);
5534 #endif
5535 	/*
5536 	 * Adjust the beacon timers only when pulling them forward
5537 	 * or when going back by less than the beacon interval.
5538 	 * Negative jumps larger than the beacon interval seem to
5539 	 * cause the timers to stop and generally cause instability.
5540 	 * This basically filters out jumps due to missed beacons.
5541 	 */
5542 	if (tudelta != 0 && (tudelta > 0 || -tudelta < sc->sc_tdmabintval)) {
5543 		ath_tdma_settimers(sc, nextslottu, sc->sc_tdmabintval);
5544 		sc->sc_stats.ast_tdma_timers++;
5545 	}
5546 	if (tsfdelta > 0) {
5547 		ath_hal_adjusttsf(ah, tsfdelta);
5548 		sc->sc_stats.ast_tdma_tsf++;
5549 	}
5550 	ath_tdma_beacon_send(sc, vap);		/* prepare response */
5551 #undef TU_TO_TSF
5552 #undef TSF_TO_TU
5553 }
5554 
5555 /*
5556  * Transmit a beacon frame at SWBA.  Dynamic updates
5557  * to the frame contents are done as needed.
5558  */
5559 static void
5560 ath_tdma_beacon_send(struct ath_softc *sc, struct ieee80211vap *vap)
5561 {
5562 	struct ath_hal *ah = sc->sc_ah;
5563 	struct ath_buf *bf;
5564 	int otherant;
5565 
5566 	/*
5567 	 * Check if the previous beacon has gone out.  If
5568 	 * not don't try to post another, skip this period
5569 	 * and wait for the next.  Missed beacons indicate
5570 	 * a problem and should not occur.  If we miss too
5571 	 * many consecutive beacons reset the device.
5572 	 */
5573 	if (ath_hal_numtxpending(ah, sc->sc_bhalq) != 0) {
5574 		sc->sc_bmisscount++;
5575 		DPRINTF(sc, ATH_DEBUG_BEACON,
5576 			"%s: missed %u consecutive beacons\n",
5577 			__func__, sc->sc_bmisscount);
5578 		if (sc->sc_bmisscount >= ath_bstuck_threshold)
5579 			taskqueue_enqueue(sc->sc_tq, &sc->sc_bstucktask);
5580 		return;
5581 	}
5582 	if (sc->sc_bmisscount != 0) {
5583 		DPRINTF(sc, ATH_DEBUG_BEACON,
5584 			"%s: resume beacon xmit after %u misses\n",
5585 			__func__, sc->sc_bmisscount);
5586 		sc->sc_bmisscount = 0;
5587 	}
5588 
5589 	/*
5590 	 * Check recent per-antenna transmit statistics and flip
5591 	 * the default antenna if noticeably more frames went out
5592 	 * on the non-default antenna.
5593 	 * XXX assumes 2 anntenae
5594 	 */
5595 	if (!sc->sc_diversity) {
5596 		otherant = sc->sc_defant & 1 ? 2 : 1;
5597 		if (sc->sc_ant_tx[otherant] > sc->sc_ant_tx[sc->sc_defant] + 2)
5598 			ath_setdefantenna(sc, otherant);
5599 		sc->sc_ant_tx[1] = sc->sc_ant_tx[2] = 0;
5600 	}
5601 
5602 	bf = ath_beacon_generate(sc, vap);
5603 	if (bf != NULL) {
5604 		/*
5605 		 * Stop any current dma and put the new frame on the queue.
5606 		 * This should never fail since we check above that no frames
5607 		 * are still pending on the queue.
5608 		 */
5609 		if (!ath_hal_stoptxdma(ah, sc->sc_bhalq)) {
5610 			DPRINTF(sc, ATH_DEBUG_ANY,
5611 				"%s: beacon queue %u did not stop?\n",
5612 				__func__, sc->sc_bhalq);
5613 			/* NB: the HAL still stops DMA, so proceed */
5614 		}
5615 		ath_hal_puttxbuf(ah, sc->sc_bhalq, bf->bf_daddr);
5616 		ath_hal_txstart(ah, sc->sc_bhalq);
5617 
5618 		sc->sc_stats.ast_be_xmit++;		/* XXX per-vap? */
5619 
5620 		/*
5621 		 * Record local TSF for our last send for use
5622 		 * in arbitrating slot collisions.
5623 		 */
5624 		vap->iv_bss->ni_tstamp.tsf = ath_hal_gettsf64(ah);
5625 	}
5626 }
5627 #endif /* IEEE80211_SUPPORT_TDMA */
5628 
5629 MODULE_VERSION(if_ath, 1);
5630 MODULE_DEPEND(if_ath, wlan, 1, 1, 1);          /* 802.11 media layer */
5631