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