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