xref: /freebsd/sys/dev/ath/if_ath.c (revision 81966bce06dac45f42bda62b14dba0756ef28505)
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 	DPRINTF(sc, ATH_DEBUG_MODE, "%s: RX filter 0x%x, %s if_flags 0x%x\n",
2490 	    __func__, rfilt, ieee80211_opmode_name[ic->ic_opmode], ifp->if_flags);
2491 	return rfilt;
2492 }
2493 
2494 static void
2495 ath_update_promisc(struct ifnet *ifp)
2496 {
2497 	struct ath_softc *sc = ifp->if_softc;
2498 	u_int32_t rfilt;
2499 
2500 	/* configure rx filter */
2501 	rfilt = ath_calcrxfilter(sc);
2502 	ath_hal_setrxfilter(sc->sc_ah, rfilt);
2503 
2504 	DPRINTF(sc, ATH_DEBUG_MODE, "%s: RX filter 0x%x\n", __func__, rfilt);
2505 }
2506 
2507 static void
2508 ath_update_mcast(struct ifnet *ifp)
2509 {
2510 	struct ath_softc *sc = ifp->if_softc;
2511 	u_int32_t mfilt[2];
2512 
2513 	/* calculate and install multicast filter */
2514 	if ((ifp->if_flags & IFF_ALLMULTI) == 0) {
2515 		struct ifmultiaddr *ifma;
2516 		/*
2517 		 * Merge multicast addresses to form the hardware filter.
2518 		 */
2519 		mfilt[0] = mfilt[1] = 0;
2520 		if_maddr_rlock(ifp);	/* XXX need some fiddling to remove? */
2521 		TAILQ_FOREACH(ifma, &ifp->if_multiaddrs, ifma_link) {
2522 			caddr_t dl;
2523 			u_int32_t val;
2524 			u_int8_t pos;
2525 
2526 			/* calculate XOR of eight 6bit values */
2527 			dl = LLADDR((struct sockaddr_dl *) ifma->ifma_addr);
2528 			val = LE_READ_4(dl + 0);
2529 			pos = (val >> 18) ^ (val >> 12) ^ (val >> 6) ^ val;
2530 			val = LE_READ_4(dl + 3);
2531 			pos ^= (val >> 18) ^ (val >> 12) ^ (val >> 6) ^ val;
2532 			pos &= 0x3f;
2533 			mfilt[pos / 32] |= (1 << (pos % 32));
2534 		}
2535 		if_maddr_runlock(ifp);
2536 	} else
2537 		mfilt[0] = mfilt[1] = ~0;
2538 	ath_hal_setmcastfilter(sc->sc_ah, mfilt[0], mfilt[1]);
2539 	DPRINTF(sc, ATH_DEBUG_MODE, "%s: MC filter %08x:%08x\n",
2540 		__func__, mfilt[0], mfilt[1]);
2541 }
2542 
2543 static void
2544 ath_mode_init(struct ath_softc *sc)
2545 {
2546 	struct ifnet *ifp = sc->sc_ifp;
2547 	struct ath_hal *ah = sc->sc_ah;
2548 	u_int32_t rfilt;
2549 
2550 	/* configure rx filter */
2551 	rfilt = ath_calcrxfilter(sc);
2552 	ath_hal_setrxfilter(ah, rfilt);
2553 
2554 	/* configure operational mode */
2555 	ath_hal_setopmode(ah);
2556 
2557 	/* handle any link-level address change */
2558 	ath_hal_setmac(ah, IF_LLADDR(ifp));
2559 
2560 	/* calculate and install multicast filter */
2561 	ath_update_mcast(ifp);
2562 }
2563 
2564 /*
2565  * Set the slot time based on the current setting.
2566  */
2567 static void
2568 ath_setslottime(struct ath_softc *sc)
2569 {
2570 	struct ieee80211com *ic = sc->sc_ifp->if_l2com;
2571 	struct ath_hal *ah = sc->sc_ah;
2572 	u_int usec;
2573 
2574 	if (IEEE80211_IS_CHAN_HALF(ic->ic_curchan))
2575 		usec = 13;
2576 	else if (IEEE80211_IS_CHAN_QUARTER(ic->ic_curchan))
2577 		usec = 21;
2578 	else if (IEEE80211_IS_CHAN_ANYG(ic->ic_curchan)) {
2579 		/* honor short/long slot time only in 11g */
2580 		/* XXX shouldn't honor on pure g or turbo g channel */
2581 		if (ic->ic_flags & IEEE80211_F_SHSLOT)
2582 			usec = HAL_SLOT_TIME_9;
2583 		else
2584 			usec = HAL_SLOT_TIME_20;
2585 	} else
2586 		usec = HAL_SLOT_TIME_9;
2587 
2588 	DPRINTF(sc, ATH_DEBUG_RESET,
2589 	    "%s: chan %u MHz flags 0x%x %s slot, %u usec\n",
2590 	    __func__, ic->ic_curchan->ic_freq, ic->ic_curchan->ic_flags,
2591 	    ic->ic_flags & IEEE80211_F_SHSLOT ? "short" : "long", usec);
2592 
2593 	ath_hal_setslottime(ah, usec);
2594 	sc->sc_updateslot = OK;
2595 }
2596 
2597 /*
2598  * Callback from the 802.11 layer to update the
2599  * slot time based on the current setting.
2600  */
2601 static void
2602 ath_updateslot(struct ifnet *ifp)
2603 {
2604 	struct ath_softc *sc = ifp->if_softc;
2605 	struct ieee80211com *ic = ifp->if_l2com;
2606 
2607 	/*
2608 	 * When not coordinating the BSS, change the hardware
2609 	 * immediately.  For other operation we defer the change
2610 	 * until beacon updates have propagated to the stations.
2611 	 */
2612 	if (ic->ic_opmode == IEEE80211_M_HOSTAP ||
2613 	    ic->ic_opmode == IEEE80211_M_MBSS)
2614 		sc->sc_updateslot = UPDATE;
2615 	else
2616 		ath_setslottime(sc);
2617 }
2618 
2619 /*
2620  * Setup a h/w transmit queue for beacons.
2621  */
2622 static int
2623 ath_beaconq_setup(struct ath_hal *ah)
2624 {
2625 	HAL_TXQ_INFO qi;
2626 
2627 	memset(&qi, 0, sizeof(qi));
2628 	qi.tqi_aifs = HAL_TXQ_USEDEFAULT;
2629 	qi.tqi_cwmin = HAL_TXQ_USEDEFAULT;
2630 	qi.tqi_cwmax = HAL_TXQ_USEDEFAULT;
2631 	/* NB: for dynamic turbo, don't enable any other interrupts */
2632 	qi.tqi_qflags = HAL_TXQ_TXDESCINT_ENABLE;
2633 	return ath_hal_setuptxqueue(ah, HAL_TX_QUEUE_BEACON, &qi);
2634 }
2635 
2636 /*
2637  * Setup the transmit queue parameters for the beacon queue.
2638  */
2639 static int
2640 ath_beaconq_config(struct ath_softc *sc)
2641 {
2642 #define	ATH_EXPONENT_TO_VALUE(v)	((1<<(v))-1)
2643 	struct ieee80211com *ic = sc->sc_ifp->if_l2com;
2644 	struct ath_hal *ah = sc->sc_ah;
2645 	HAL_TXQ_INFO qi;
2646 
2647 	ath_hal_gettxqueueprops(ah, sc->sc_bhalq, &qi);
2648 	if (ic->ic_opmode == IEEE80211_M_HOSTAP ||
2649 	    ic->ic_opmode == IEEE80211_M_MBSS) {
2650 		/*
2651 		 * Always burst out beacon and CAB traffic.
2652 		 */
2653 		qi.tqi_aifs = ATH_BEACON_AIFS_DEFAULT;
2654 		qi.tqi_cwmin = ATH_BEACON_CWMIN_DEFAULT;
2655 		qi.tqi_cwmax = ATH_BEACON_CWMAX_DEFAULT;
2656 	} else {
2657 		struct wmeParams *wmep =
2658 			&ic->ic_wme.wme_chanParams.cap_wmeParams[WME_AC_BE];
2659 		/*
2660 		 * Adhoc mode; important thing is to use 2x cwmin.
2661 		 */
2662 		qi.tqi_aifs = wmep->wmep_aifsn;
2663 		qi.tqi_cwmin = 2*ATH_EXPONENT_TO_VALUE(wmep->wmep_logcwmin);
2664 		qi.tqi_cwmax = ATH_EXPONENT_TO_VALUE(wmep->wmep_logcwmax);
2665 	}
2666 
2667 	if (!ath_hal_settxqueueprops(ah, sc->sc_bhalq, &qi)) {
2668 		device_printf(sc->sc_dev, "unable to update parameters for "
2669 			"beacon hardware queue!\n");
2670 		return 0;
2671 	} else {
2672 		ath_hal_resettxqueue(ah, sc->sc_bhalq); /* push to h/w */
2673 		return 1;
2674 	}
2675 #undef ATH_EXPONENT_TO_VALUE
2676 }
2677 
2678 /*
2679  * Allocate and setup an initial beacon frame.
2680  */
2681 static int
2682 ath_beacon_alloc(struct ath_softc *sc, struct ieee80211_node *ni)
2683 {
2684 	struct ieee80211vap *vap = ni->ni_vap;
2685 	struct ath_vap *avp = ATH_VAP(vap);
2686 	struct ath_buf *bf;
2687 	struct mbuf *m;
2688 	int error;
2689 
2690 	bf = avp->av_bcbuf;
2691 	if (bf->bf_m != NULL) {
2692 		bus_dmamap_unload(sc->sc_dmat, bf->bf_dmamap);
2693 		m_freem(bf->bf_m);
2694 		bf->bf_m = NULL;
2695 	}
2696 	if (bf->bf_node != NULL) {
2697 		ieee80211_free_node(bf->bf_node);
2698 		bf->bf_node = NULL;
2699 	}
2700 
2701 	/*
2702 	 * NB: the beacon data buffer must be 32-bit aligned;
2703 	 * we assume the mbuf routines will return us something
2704 	 * with this alignment (perhaps should assert).
2705 	 */
2706 	m = ieee80211_beacon_alloc(ni, &avp->av_boff);
2707 	if (m == NULL) {
2708 		device_printf(sc->sc_dev, "%s: cannot get mbuf\n", __func__);
2709 		sc->sc_stats.ast_be_nombuf++;
2710 		return ENOMEM;
2711 	}
2712 	error = bus_dmamap_load_mbuf_sg(sc->sc_dmat, bf->bf_dmamap, m,
2713 				     bf->bf_segs, &bf->bf_nseg,
2714 				     BUS_DMA_NOWAIT);
2715 	if (error != 0) {
2716 		device_printf(sc->sc_dev,
2717 		    "%s: cannot map mbuf, bus_dmamap_load_mbuf_sg returns %d\n",
2718 		    __func__, error);
2719 		m_freem(m);
2720 		return error;
2721 	}
2722 
2723 	/*
2724 	 * Calculate a TSF adjustment factor required for staggered
2725 	 * beacons.  Note that we assume the format of the beacon
2726 	 * frame leaves the tstamp field immediately following the
2727 	 * header.
2728 	 */
2729 	if (sc->sc_stagbeacons && avp->av_bslot > 0) {
2730 		uint64_t tsfadjust;
2731 		struct ieee80211_frame *wh;
2732 
2733 		/*
2734 		 * The beacon interval is in TU's; the TSF is in usecs.
2735 		 * We figure out how many TU's to add to align the timestamp
2736 		 * then convert to TSF units and handle byte swapping before
2737 		 * inserting it in the frame.  The hardware will then add this
2738 		 * each time a beacon frame is sent.  Note that we align vap's
2739 		 * 1..N and leave vap 0 untouched.  This means vap 0 has a
2740 		 * timestamp in one beacon interval while the others get a
2741 		 * timstamp aligned to the next interval.
2742 		 */
2743 		tsfadjust = ni->ni_intval *
2744 		    (ATH_BCBUF - avp->av_bslot) / ATH_BCBUF;
2745 		tsfadjust = htole64(tsfadjust << 10);	/* TU -> TSF */
2746 
2747 		DPRINTF(sc, ATH_DEBUG_BEACON,
2748 		    "%s: %s beacons bslot %d intval %u tsfadjust %llu\n",
2749 		    __func__, sc->sc_stagbeacons ? "stagger" : "burst",
2750 		    avp->av_bslot, ni->ni_intval,
2751 		    (long long unsigned) le64toh(tsfadjust));
2752 
2753 		wh = mtod(m, struct ieee80211_frame *);
2754 		memcpy(&wh[1], &tsfadjust, sizeof(tsfadjust));
2755 	}
2756 	bf->bf_m = m;
2757 	bf->bf_node = ieee80211_ref_node(ni);
2758 
2759 	return 0;
2760 }
2761 
2762 /*
2763  * Setup the beacon frame for transmit.
2764  */
2765 static void
2766 ath_beacon_setup(struct ath_softc *sc, struct ath_buf *bf)
2767 {
2768 #define	USE_SHPREAMBLE(_ic) \
2769 	(((_ic)->ic_flags & (IEEE80211_F_SHPREAMBLE | IEEE80211_F_USEBARKER))\
2770 		== IEEE80211_F_SHPREAMBLE)
2771 	struct ieee80211_node *ni = bf->bf_node;
2772 	struct ieee80211com *ic = ni->ni_ic;
2773 	struct mbuf *m = bf->bf_m;
2774 	struct ath_hal *ah = sc->sc_ah;
2775 	struct ath_desc *ds;
2776 	int flags, antenna;
2777 	const HAL_RATE_TABLE *rt;
2778 	u_int8_t rix, rate;
2779 
2780 	DPRINTF(sc, ATH_DEBUG_BEACON_PROC, "%s: m %p len %u\n",
2781 		__func__, m, m->m_len);
2782 
2783 	/* setup descriptors */
2784 	ds = bf->bf_desc;
2785 	bf->bf_last = bf;
2786 	bf->bf_lastds = ds;
2787 
2788 	flags = HAL_TXDESC_NOACK;
2789 	if (ic->ic_opmode == IEEE80211_M_IBSS && sc->sc_hasveol) {
2790 		ds->ds_link = bf->bf_daddr;	/* self-linked */
2791 		flags |= HAL_TXDESC_VEOL;
2792 		/*
2793 		 * Let hardware handle antenna switching.
2794 		 */
2795 		antenna = sc->sc_txantenna;
2796 	} else {
2797 		ds->ds_link = 0;
2798 		/*
2799 		 * Switch antenna every 4 beacons.
2800 		 * XXX assumes two antenna
2801 		 */
2802 		if (sc->sc_txantenna != 0)
2803 			antenna = sc->sc_txantenna;
2804 		else if (sc->sc_stagbeacons && sc->sc_nbcnvaps != 0)
2805 			antenna = ((sc->sc_stats.ast_be_xmit / sc->sc_nbcnvaps) & 4 ? 2 : 1);
2806 		else
2807 			antenna = (sc->sc_stats.ast_be_xmit & 4 ? 2 : 1);
2808 	}
2809 
2810 	KASSERT(bf->bf_nseg == 1,
2811 		("multi-segment beacon frame; nseg %u", bf->bf_nseg));
2812 	ds->ds_data = bf->bf_segs[0].ds_addr;
2813 	/*
2814 	 * Calculate rate code.
2815 	 * XXX everything at min xmit rate
2816 	 */
2817 	rix = 0;
2818 	rt = sc->sc_currates;
2819 	rate = rt->info[rix].rateCode;
2820 	if (USE_SHPREAMBLE(ic))
2821 		rate |= rt->info[rix].shortPreamble;
2822 	ath_hal_setuptxdesc(ah, ds
2823 		, m->m_len + IEEE80211_CRC_LEN	/* frame length */
2824 		, sizeof(struct ieee80211_frame)/* header length */
2825 		, HAL_PKT_TYPE_BEACON		/* Atheros packet type */
2826 		, ni->ni_txpower		/* txpower XXX */
2827 		, rate, 1			/* series 0 rate/tries */
2828 		, HAL_TXKEYIX_INVALID		/* no encryption */
2829 		, antenna			/* antenna mode */
2830 		, flags				/* no ack, veol for beacons */
2831 		, 0				/* rts/cts rate */
2832 		, 0				/* rts/cts duration */
2833 	);
2834 	/* NB: beacon's BufLen must be a multiple of 4 bytes */
2835 	ath_hal_filltxdesc(ah, ds
2836 		, roundup(m->m_len, 4)		/* buffer length */
2837 		, AH_TRUE			/* first segment */
2838 		, AH_TRUE			/* last segment */
2839 		, ds				/* first descriptor */
2840 	);
2841 #if 0
2842 	ath_desc_swap(ds);
2843 #endif
2844 #undef USE_SHPREAMBLE
2845 }
2846 
2847 static void
2848 ath_beacon_update(struct ieee80211vap *vap, int item)
2849 {
2850 	struct ieee80211_beacon_offsets *bo = &ATH_VAP(vap)->av_boff;
2851 
2852 	setbit(bo->bo_flags, item);
2853 }
2854 
2855 /*
2856  * Append the contents of src to dst; both queues
2857  * are assumed to be locked.
2858  */
2859 static void
2860 ath_txqmove(struct ath_txq *dst, struct ath_txq *src)
2861 {
2862 	TAILQ_CONCAT(&dst->axq_q, &src->axq_q, bf_list);
2863 	dst->axq_link = src->axq_link;
2864 	src->axq_link = NULL;
2865 	dst->axq_depth += src->axq_depth;
2866 	dst->axq_aggr_depth += src->axq_aggr_depth;
2867 	src->axq_depth = 0;
2868 	src->axq_aggr_depth = 0;
2869 }
2870 
2871 /*
2872  * Transmit a beacon frame at SWBA.  Dynamic updates to the
2873  * frame contents are done as needed and the slot time is
2874  * also adjusted based on current state.
2875  */
2876 static void
2877 ath_beacon_proc(void *arg, int pending)
2878 {
2879 	struct ath_softc *sc = arg;
2880 	struct ath_hal *ah = sc->sc_ah;
2881 	struct ieee80211vap *vap;
2882 	struct ath_buf *bf;
2883 	int slot, otherant;
2884 	uint32_t bfaddr;
2885 
2886 	DPRINTF(sc, ATH_DEBUG_BEACON_PROC, "%s: pending %u\n",
2887 		__func__, pending);
2888 	/*
2889 	 * Check if the previous beacon has gone out.  If
2890 	 * not don't try to post another, skip this period
2891 	 * and wait for the next.  Missed beacons indicate
2892 	 * a problem and should not occur.  If we miss too
2893 	 * many consecutive beacons reset the device.
2894 	 */
2895 	if (ath_hal_numtxpending(ah, sc->sc_bhalq) != 0) {
2896 		sc->sc_bmisscount++;
2897 		sc->sc_stats.ast_be_missed++;
2898 		DPRINTF(sc, ATH_DEBUG_BEACON,
2899 			"%s: missed %u consecutive beacons\n",
2900 			__func__, sc->sc_bmisscount);
2901 		if (sc->sc_bmisscount >= ath_bstuck_threshold)
2902 			taskqueue_enqueue(sc->sc_tq, &sc->sc_bstucktask);
2903 		return;
2904 	}
2905 	if (sc->sc_bmisscount != 0) {
2906 		DPRINTF(sc, ATH_DEBUG_BEACON,
2907 			"%s: resume beacon xmit after %u misses\n",
2908 			__func__, sc->sc_bmisscount);
2909 		sc->sc_bmisscount = 0;
2910 	}
2911 
2912 	if (sc->sc_stagbeacons) {			/* staggered beacons */
2913 		struct ieee80211com *ic = sc->sc_ifp->if_l2com;
2914 		uint32_t tsftu;
2915 
2916 		tsftu = ath_hal_gettsf32(ah) >> 10;
2917 		/* XXX lintval */
2918 		slot = ((tsftu % ic->ic_lintval) * ATH_BCBUF) / ic->ic_lintval;
2919 		vap = sc->sc_bslot[(slot+1) % ATH_BCBUF];
2920 		bfaddr = 0;
2921 		if (vap != NULL && vap->iv_state >= IEEE80211_S_RUN) {
2922 			bf = ath_beacon_generate(sc, vap);
2923 			if (bf != NULL)
2924 				bfaddr = bf->bf_daddr;
2925 		}
2926 	} else {					/* burst'd beacons */
2927 		uint32_t *bflink = &bfaddr;
2928 
2929 		for (slot = 0; slot < ATH_BCBUF; slot++) {
2930 			vap = sc->sc_bslot[slot];
2931 			if (vap != NULL && vap->iv_state >= IEEE80211_S_RUN) {
2932 				bf = ath_beacon_generate(sc, vap);
2933 				if (bf != NULL) {
2934 					*bflink = bf->bf_daddr;
2935 					bflink = &bf->bf_desc->ds_link;
2936 				}
2937 			}
2938 		}
2939 		*bflink = 0;				/* terminate list */
2940 	}
2941 
2942 	/*
2943 	 * Handle slot time change when a non-ERP station joins/leaves
2944 	 * an 11g network.  The 802.11 layer notifies us via callback,
2945 	 * we mark updateslot, then wait one beacon before effecting
2946 	 * the change.  This gives associated stations at least one
2947 	 * beacon interval to note the state change.
2948 	 */
2949 	/* XXX locking */
2950 	if (sc->sc_updateslot == UPDATE) {
2951 		sc->sc_updateslot = COMMIT;	/* commit next beacon */
2952 		sc->sc_slotupdate = slot;
2953 	} else if (sc->sc_updateslot == COMMIT && sc->sc_slotupdate == slot)
2954 		ath_setslottime(sc);		/* commit change to h/w */
2955 
2956 	/*
2957 	 * Check recent per-antenna transmit statistics and flip
2958 	 * the default antenna if noticeably more frames went out
2959 	 * on the non-default antenna.
2960 	 * XXX assumes 2 anntenae
2961 	 */
2962 	if (!sc->sc_diversity && (!sc->sc_stagbeacons || slot == 0)) {
2963 		otherant = sc->sc_defant & 1 ? 2 : 1;
2964 		if (sc->sc_ant_tx[otherant] > sc->sc_ant_tx[sc->sc_defant] + 2)
2965 			ath_setdefantenna(sc, otherant);
2966 		sc->sc_ant_tx[1] = sc->sc_ant_tx[2] = 0;
2967 	}
2968 
2969 	if (bfaddr != 0) {
2970 		/*
2971 		 * Stop any current dma and put the new frame on the queue.
2972 		 * This should never fail since we check above that no frames
2973 		 * are still pending on the queue.
2974 		 */
2975 		if (!ath_hal_stoptxdma(ah, sc->sc_bhalq)) {
2976 			DPRINTF(sc, ATH_DEBUG_ANY,
2977 				"%s: beacon queue %u did not stop?\n",
2978 				__func__, sc->sc_bhalq);
2979 		}
2980 		/* NB: cabq traffic should already be queued and primed */
2981 		ath_hal_puttxbuf(ah, sc->sc_bhalq, bfaddr);
2982 		ath_hal_txstart(ah, sc->sc_bhalq);
2983 
2984 		sc->sc_stats.ast_be_xmit++;
2985 	}
2986 }
2987 
2988 static struct ath_buf *
2989 ath_beacon_generate(struct ath_softc *sc, struct ieee80211vap *vap)
2990 {
2991 	struct ath_vap *avp = ATH_VAP(vap);
2992 	struct ath_txq *cabq = sc->sc_cabq;
2993 	struct ath_buf *bf;
2994 	struct mbuf *m;
2995 	int nmcastq, error;
2996 
2997 	KASSERT(vap->iv_state >= IEEE80211_S_RUN,
2998 	    ("not running, state %d", vap->iv_state));
2999 	KASSERT(avp->av_bcbuf != NULL, ("no beacon buffer"));
3000 
3001 	/*
3002 	 * Update dynamic beacon contents.  If this returns
3003 	 * non-zero then we need to remap the memory because
3004 	 * the beacon frame changed size (probably because
3005 	 * of the TIM bitmap).
3006 	 */
3007 	bf = avp->av_bcbuf;
3008 	m = bf->bf_m;
3009 	nmcastq = avp->av_mcastq.axq_depth;
3010 	if (ieee80211_beacon_update(bf->bf_node, &avp->av_boff, m, nmcastq)) {
3011 		/* XXX too conservative? */
3012 		bus_dmamap_unload(sc->sc_dmat, bf->bf_dmamap);
3013 		error = bus_dmamap_load_mbuf_sg(sc->sc_dmat, bf->bf_dmamap, m,
3014 					     bf->bf_segs, &bf->bf_nseg,
3015 					     BUS_DMA_NOWAIT);
3016 		if (error != 0) {
3017 			if_printf(vap->iv_ifp,
3018 			    "%s: bus_dmamap_load_mbuf_sg failed, error %u\n",
3019 			    __func__, error);
3020 			return NULL;
3021 		}
3022 	}
3023 	if ((avp->av_boff.bo_tim[4] & 1) && cabq->axq_depth) {
3024 		DPRINTF(sc, ATH_DEBUG_BEACON,
3025 		    "%s: cabq did not drain, mcastq %u cabq %u\n",
3026 		    __func__, nmcastq, cabq->axq_depth);
3027 		sc->sc_stats.ast_cabq_busy++;
3028 		if (sc->sc_nvaps > 1 && sc->sc_stagbeacons) {
3029 			/*
3030 			 * CABQ traffic from a previous vap is still pending.
3031 			 * We must drain the q before this beacon frame goes
3032 			 * out as otherwise this vap's stations will get cab
3033 			 * frames from a different vap.
3034 			 * XXX could be slow causing us to miss DBA
3035 			 */
3036 			ath_tx_draintxq(sc, cabq);
3037 		}
3038 	}
3039 	ath_beacon_setup(sc, bf);
3040 	bus_dmamap_sync(sc->sc_dmat, bf->bf_dmamap, BUS_DMASYNC_PREWRITE);
3041 
3042 	/*
3043 	 * Enable the CAB queue before the beacon queue to
3044 	 * insure cab frames are triggered by this beacon.
3045 	 */
3046 	if (avp->av_boff.bo_tim[4] & 1) {
3047 		struct ath_hal *ah = sc->sc_ah;
3048 
3049 		/* NB: only at DTIM */
3050 		ATH_TXQ_LOCK(cabq);
3051 		ATH_TXQ_LOCK(&avp->av_mcastq);
3052 		if (nmcastq) {
3053 			struct ath_buf *bfm;
3054 
3055 			/*
3056 			 * Move frames from the s/w mcast q to the h/w cab q.
3057 			 * XXX MORE_DATA bit
3058 			 */
3059 			bfm = TAILQ_FIRST(&avp->av_mcastq.axq_q);
3060 			if (cabq->axq_link != NULL) {
3061 				*cabq->axq_link = bfm->bf_daddr;
3062 			} else
3063 				ath_hal_puttxbuf(ah, cabq->axq_qnum,
3064 					bfm->bf_daddr);
3065 			ath_txqmove(cabq, &avp->av_mcastq);
3066 
3067 			sc->sc_stats.ast_cabq_xmit += nmcastq;
3068 		}
3069 		/* NB: gated by beacon so safe to start here */
3070 		if (! TAILQ_EMPTY(&(cabq->axq_q)))
3071 			ath_hal_txstart(ah, cabq->axq_qnum);
3072 		ATH_TXQ_UNLOCK(&avp->av_mcastq);
3073 		ATH_TXQ_UNLOCK(cabq);
3074 	}
3075 	return bf;
3076 }
3077 
3078 static void
3079 ath_beacon_start_adhoc(struct ath_softc *sc, struct ieee80211vap *vap)
3080 {
3081 	struct ath_vap *avp = ATH_VAP(vap);
3082 	struct ath_hal *ah = sc->sc_ah;
3083 	struct ath_buf *bf;
3084 	struct mbuf *m;
3085 	int error;
3086 
3087 	KASSERT(avp->av_bcbuf != NULL, ("no beacon buffer"));
3088 
3089 	/*
3090 	 * Update dynamic beacon contents.  If this returns
3091 	 * non-zero then we need to remap the memory because
3092 	 * the beacon frame changed size (probably because
3093 	 * of the TIM bitmap).
3094 	 */
3095 	bf = avp->av_bcbuf;
3096 	m = bf->bf_m;
3097 	if (ieee80211_beacon_update(bf->bf_node, &avp->av_boff, m, 0)) {
3098 		/* XXX too conservative? */
3099 		bus_dmamap_unload(sc->sc_dmat, bf->bf_dmamap);
3100 		error = bus_dmamap_load_mbuf_sg(sc->sc_dmat, bf->bf_dmamap, m,
3101 					     bf->bf_segs, &bf->bf_nseg,
3102 					     BUS_DMA_NOWAIT);
3103 		if (error != 0) {
3104 			if_printf(vap->iv_ifp,
3105 			    "%s: bus_dmamap_load_mbuf_sg failed, error %u\n",
3106 			    __func__, error);
3107 			return;
3108 		}
3109 	}
3110 	ath_beacon_setup(sc, bf);
3111 	bus_dmamap_sync(sc->sc_dmat, bf->bf_dmamap, BUS_DMASYNC_PREWRITE);
3112 
3113 	/* NB: caller is known to have already stopped tx dma */
3114 	ath_hal_puttxbuf(ah, sc->sc_bhalq, bf->bf_daddr);
3115 	ath_hal_txstart(ah, sc->sc_bhalq);
3116 }
3117 
3118 /*
3119  * Reset the hardware after detecting beacons have stopped.
3120  */
3121 static void
3122 ath_bstuck_proc(void *arg, int pending)
3123 {
3124 	struct ath_softc *sc = arg;
3125 	struct ifnet *ifp = sc->sc_ifp;
3126 	uint32_t hangs = 0;
3127 
3128 	if (ath_hal_gethangstate(sc->sc_ah, 0xff, &hangs) && hangs != 0)
3129 		if_printf(ifp, "bb hang detected (0x%x)\n", hangs);
3130 
3131 	if_printf(ifp, "stuck beacon; resetting (bmiss count %u)\n",
3132 		sc->sc_bmisscount);
3133 	sc->sc_stats.ast_bstuck++;
3134 	/*
3135 	 * This assumes that there's no simultaneous channel mode change
3136 	 * occuring.
3137 	 */
3138 	ath_reset(ifp, ATH_RESET_NOLOSS);
3139 }
3140 
3141 /*
3142  * Reclaim beacon resources and return buffer to the pool.
3143  */
3144 static void
3145 ath_beacon_return(struct ath_softc *sc, struct ath_buf *bf)
3146 {
3147 
3148 	if (bf->bf_m != NULL) {
3149 		bus_dmamap_unload(sc->sc_dmat, bf->bf_dmamap);
3150 		m_freem(bf->bf_m);
3151 		bf->bf_m = NULL;
3152 	}
3153 	if (bf->bf_node != NULL) {
3154 		ieee80211_free_node(bf->bf_node);
3155 		bf->bf_node = NULL;
3156 	}
3157 	TAILQ_INSERT_TAIL(&sc->sc_bbuf, bf, bf_list);
3158 }
3159 
3160 /*
3161  * Reclaim beacon resources.
3162  */
3163 static void
3164 ath_beacon_free(struct ath_softc *sc)
3165 {
3166 	struct ath_buf *bf;
3167 
3168 	TAILQ_FOREACH(bf, &sc->sc_bbuf, bf_list) {
3169 		if (bf->bf_m != NULL) {
3170 			bus_dmamap_unload(sc->sc_dmat, bf->bf_dmamap);
3171 			m_freem(bf->bf_m);
3172 			bf->bf_m = NULL;
3173 		}
3174 		if (bf->bf_node != NULL) {
3175 			ieee80211_free_node(bf->bf_node);
3176 			bf->bf_node = NULL;
3177 		}
3178 	}
3179 }
3180 
3181 /*
3182  * Configure the beacon and sleep timers.
3183  *
3184  * When operating as an AP this resets the TSF and sets
3185  * up the hardware to notify us when we need to issue beacons.
3186  *
3187  * When operating in station mode this sets up the beacon
3188  * timers according to the timestamp of the last received
3189  * beacon and the current TSF, configures PCF and DTIM
3190  * handling, programs the sleep registers so the hardware
3191  * will wakeup in time to receive beacons, and configures
3192  * the beacon miss handling so we'll receive a BMISS
3193  * interrupt when we stop seeing beacons from the AP
3194  * we've associated with.
3195  */
3196 static void
3197 ath_beacon_config(struct ath_softc *sc, struct ieee80211vap *vap)
3198 {
3199 #define	TSF_TO_TU(_h,_l) \
3200 	((((u_int32_t)(_h)) << 22) | (((u_int32_t)(_l)) >> 10))
3201 #define	FUDGE	2
3202 	struct ath_hal *ah = sc->sc_ah;
3203 	struct ieee80211com *ic = sc->sc_ifp->if_l2com;
3204 	struct ieee80211_node *ni;
3205 	u_int32_t nexttbtt, intval, tsftu;
3206 	u_int64_t tsf;
3207 
3208 	if (vap == NULL)
3209 		vap = TAILQ_FIRST(&ic->ic_vaps);	/* XXX */
3210 	ni = vap->iv_bss;
3211 
3212 	/* extract tstamp from last beacon and convert to TU */
3213 	nexttbtt = TSF_TO_TU(LE_READ_4(ni->ni_tstamp.data + 4),
3214 			     LE_READ_4(ni->ni_tstamp.data));
3215 	if (ic->ic_opmode == IEEE80211_M_HOSTAP ||
3216 	    ic->ic_opmode == IEEE80211_M_MBSS) {
3217 		/*
3218 		 * For multi-bss ap/mesh support beacons are either staggered
3219 		 * evenly over N slots or burst together.  For the former
3220 		 * arrange for the SWBA to be delivered for each slot.
3221 		 * Slots that are not occupied will generate nothing.
3222 		 */
3223 		/* NB: the beacon interval is kept internally in TU's */
3224 		intval = ni->ni_intval & HAL_BEACON_PERIOD;
3225 		if (sc->sc_stagbeacons)
3226 			intval /= ATH_BCBUF;
3227 	} else {
3228 		/* NB: the beacon interval is kept internally in TU's */
3229 		intval = ni->ni_intval & HAL_BEACON_PERIOD;
3230 	}
3231 	if (nexttbtt == 0)		/* e.g. for ap mode */
3232 		nexttbtt = intval;
3233 	else if (intval)		/* NB: can be 0 for monitor mode */
3234 		nexttbtt = roundup(nexttbtt, intval);
3235 	DPRINTF(sc, ATH_DEBUG_BEACON, "%s: nexttbtt %u intval %u (%u)\n",
3236 		__func__, nexttbtt, intval, ni->ni_intval);
3237 	if (ic->ic_opmode == IEEE80211_M_STA && !sc->sc_swbmiss) {
3238 		HAL_BEACON_STATE bs;
3239 		int dtimperiod, dtimcount;
3240 		int cfpperiod, cfpcount;
3241 
3242 		/*
3243 		 * Setup dtim and cfp parameters according to
3244 		 * last beacon we received (which may be none).
3245 		 */
3246 		dtimperiod = ni->ni_dtim_period;
3247 		if (dtimperiod <= 0)		/* NB: 0 if not known */
3248 			dtimperiod = 1;
3249 		dtimcount = ni->ni_dtim_count;
3250 		if (dtimcount >= dtimperiod)	/* NB: sanity check */
3251 			dtimcount = 0;		/* XXX? */
3252 		cfpperiod = 1;			/* NB: no PCF support yet */
3253 		cfpcount = 0;
3254 		/*
3255 		 * Pull nexttbtt forward to reflect the current
3256 		 * TSF and calculate dtim+cfp state for the result.
3257 		 */
3258 		tsf = ath_hal_gettsf64(ah);
3259 		tsftu = TSF_TO_TU(tsf>>32, tsf) + FUDGE;
3260 		do {
3261 			nexttbtt += intval;
3262 			if (--dtimcount < 0) {
3263 				dtimcount = dtimperiod - 1;
3264 				if (--cfpcount < 0)
3265 					cfpcount = cfpperiod - 1;
3266 			}
3267 		} while (nexttbtt < tsftu);
3268 		memset(&bs, 0, sizeof(bs));
3269 		bs.bs_intval = intval;
3270 		bs.bs_nexttbtt = nexttbtt;
3271 		bs.bs_dtimperiod = dtimperiod*intval;
3272 		bs.bs_nextdtim = bs.bs_nexttbtt + dtimcount*intval;
3273 		bs.bs_cfpperiod = cfpperiod*bs.bs_dtimperiod;
3274 		bs.bs_cfpnext = bs.bs_nextdtim + cfpcount*bs.bs_dtimperiod;
3275 		bs.bs_cfpmaxduration = 0;
3276 #if 0
3277 		/*
3278 		 * The 802.11 layer records the offset to the DTIM
3279 		 * bitmap while receiving beacons; use it here to
3280 		 * enable h/w detection of our AID being marked in
3281 		 * the bitmap vector (to indicate frames for us are
3282 		 * pending at the AP).
3283 		 * XXX do DTIM handling in s/w to WAR old h/w bugs
3284 		 * XXX enable based on h/w rev for newer chips
3285 		 */
3286 		bs.bs_timoffset = ni->ni_timoff;
3287 #endif
3288 		/*
3289 		 * Calculate the number of consecutive beacons to miss
3290 		 * before taking a BMISS interrupt.
3291 		 * Note that we clamp the result to at most 10 beacons.
3292 		 */
3293 		bs.bs_bmissthreshold = vap->iv_bmissthreshold;
3294 		if (bs.bs_bmissthreshold > 10)
3295 			bs.bs_bmissthreshold = 10;
3296 		else if (bs.bs_bmissthreshold <= 0)
3297 			bs.bs_bmissthreshold = 1;
3298 
3299 		/*
3300 		 * Calculate sleep duration.  The configuration is
3301 		 * given in ms.  We insure a multiple of the beacon
3302 		 * period is used.  Also, if the sleep duration is
3303 		 * greater than the DTIM period then it makes senses
3304 		 * to make it a multiple of that.
3305 		 *
3306 		 * XXX fixed at 100ms
3307 		 */
3308 		bs.bs_sleepduration =
3309 			roundup(IEEE80211_MS_TO_TU(100), bs.bs_intval);
3310 		if (bs.bs_sleepduration > bs.bs_dtimperiod)
3311 			bs.bs_sleepduration = roundup(bs.bs_sleepduration, bs.bs_dtimperiod);
3312 
3313 		DPRINTF(sc, ATH_DEBUG_BEACON,
3314 			"%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"
3315 			, __func__
3316 			, tsf, tsftu
3317 			, bs.bs_intval
3318 			, bs.bs_nexttbtt
3319 			, bs.bs_dtimperiod
3320 			, bs.bs_nextdtim
3321 			, bs.bs_bmissthreshold
3322 			, bs.bs_sleepduration
3323 			, bs.bs_cfpperiod
3324 			, bs.bs_cfpmaxduration
3325 			, bs.bs_cfpnext
3326 			, bs.bs_timoffset
3327 		);
3328 		ath_hal_intrset(ah, 0);
3329 		ath_hal_beacontimers(ah, &bs);
3330 		sc->sc_imask |= HAL_INT_BMISS;
3331 		ath_hal_intrset(ah, sc->sc_imask);
3332 	} else {
3333 		ath_hal_intrset(ah, 0);
3334 		if (nexttbtt == intval)
3335 			intval |= HAL_BEACON_RESET_TSF;
3336 		if (ic->ic_opmode == IEEE80211_M_IBSS) {
3337 			/*
3338 			 * In IBSS mode enable the beacon timers but only
3339 			 * enable SWBA interrupts if we need to manually
3340 			 * prepare beacon frames.  Otherwise we use a
3341 			 * self-linked tx descriptor and let the hardware
3342 			 * deal with things.
3343 			 */
3344 			intval |= HAL_BEACON_ENA;
3345 			if (!sc->sc_hasveol)
3346 				sc->sc_imask |= HAL_INT_SWBA;
3347 			if ((intval & HAL_BEACON_RESET_TSF) == 0) {
3348 				/*
3349 				 * Pull nexttbtt forward to reflect
3350 				 * the current TSF.
3351 				 */
3352 				tsf = ath_hal_gettsf64(ah);
3353 				tsftu = TSF_TO_TU(tsf>>32, tsf) + FUDGE;
3354 				do {
3355 					nexttbtt += intval;
3356 				} while (nexttbtt < tsftu);
3357 			}
3358 			ath_beaconq_config(sc);
3359 		} else if (ic->ic_opmode == IEEE80211_M_HOSTAP ||
3360 		    ic->ic_opmode == IEEE80211_M_MBSS) {
3361 			/*
3362 			 * In AP/mesh mode we enable the beacon timers
3363 			 * and SWBA interrupts to prepare beacon frames.
3364 			 */
3365 			intval |= HAL_BEACON_ENA;
3366 			sc->sc_imask |= HAL_INT_SWBA;	/* beacon prepare */
3367 			ath_beaconq_config(sc);
3368 		}
3369 		ath_hal_beaconinit(ah, nexttbtt, intval);
3370 		sc->sc_bmisscount = 0;
3371 		ath_hal_intrset(ah, sc->sc_imask);
3372 		/*
3373 		 * When using a self-linked beacon descriptor in
3374 		 * ibss mode load it once here.
3375 		 */
3376 		if (ic->ic_opmode == IEEE80211_M_IBSS && sc->sc_hasveol)
3377 			ath_beacon_start_adhoc(sc, vap);
3378 	}
3379 	sc->sc_syncbeacon = 0;
3380 #undef FUDGE
3381 #undef TSF_TO_TU
3382 }
3383 
3384 static void
3385 ath_load_cb(void *arg, bus_dma_segment_t *segs, int nsegs, int error)
3386 {
3387 	bus_addr_t *paddr = (bus_addr_t*) arg;
3388 	KASSERT(error == 0, ("error %u on bus_dma callback", error));
3389 	*paddr = segs->ds_addr;
3390 }
3391 
3392 static int
3393 ath_descdma_setup(struct ath_softc *sc,
3394 	struct ath_descdma *dd, ath_bufhead *head,
3395 	const char *name, int nbuf, int ndesc)
3396 {
3397 #define	DS2PHYS(_dd, _ds) \
3398 	((_dd)->dd_desc_paddr + ((caddr_t)(_ds) - (caddr_t)(_dd)->dd_desc))
3399 #define	ATH_DESC_4KB_BOUND_CHECK(_daddr, _len) \
3400 	((((u_int32_t)(_daddr) & 0xFFF) > (0x1000 - (_len))) ? 1 : 0)
3401 	struct ifnet *ifp = sc->sc_ifp;
3402 	uint8_t *ds;
3403 	struct ath_buf *bf;
3404 	int i, bsize, error;
3405 	int desc_len;
3406 
3407 	desc_len = sizeof(struct ath_desc);
3408 
3409 	DPRINTF(sc, ATH_DEBUG_RESET, "%s: %s DMA: %u buffers %u desc/buf\n",
3410 	    __func__, name, nbuf, ndesc);
3411 
3412 	dd->dd_name = name;
3413 	dd->dd_desc_len = desc_len * nbuf * ndesc;
3414 
3415 	/*
3416 	 * Merlin work-around:
3417 	 * Descriptors that cross the 4KB boundary can't be used.
3418 	 * Assume one skipped descriptor per 4KB page.
3419 	 */
3420 	if (! ath_hal_split4ktrans(sc->sc_ah)) {
3421 		int numdescpage = 4096 / (desc_len * ndesc);
3422 		dd->dd_desc_len = (nbuf / numdescpage + 1) * 4096;
3423 	}
3424 
3425 	/*
3426 	 * Setup DMA descriptor area.
3427 	 */
3428 	error = bus_dma_tag_create(bus_get_dma_tag(sc->sc_dev),	/* parent */
3429 		       PAGE_SIZE, 0,		/* alignment, bounds */
3430 		       BUS_SPACE_MAXADDR_32BIT,	/* lowaddr */
3431 		       BUS_SPACE_MAXADDR,	/* highaddr */
3432 		       NULL, NULL,		/* filter, filterarg */
3433 		       dd->dd_desc_len,		/* maxsize */
3434 		       1,			/* nsegments */
3435 		       dd->dd_desc_len,		/* maxsegsize */
3436 		       BUS_DMA_ALLOCNOW,	/* flags */
3437 		       NULL,			/* lockfunc */
3438 		       NULL,			/* lockarg */
3439 		       &dd->dd_dmat);
3440 	if (error != 0) {
3441 		if_printf(ifp, "cannot allocate %s DMA tag\n", dd->dd_name);
3442 		return error;
3443 	}
3444 
3445 	/* allocate descriptors */
3446 	error = bus_dmamap_create(dd->dd_dmat, BUS_DMA_NOWAIT, &dd->dd_dmamap);
3447 	if (error != 0) {
3448 		if_printf(ifp, "unable to create dmamap for %s descriptors, "
3449 			"error %u\n", dd->dd_name, error);
3450 		goto fail0;
3451 	}
3452 
3453 	error = bus_dmamem_alloc(dd->dd_dmat, (void**) &dd->dd_desc,
3454 				 BUS_DMA_NOWAIT | BUS_DMA_COHERENT,
3455 				 &dd->dd_dmamap);
3456 	if (error != 0) {
3457 		if_printf(ifp, "unable to alloc memory for %u %s descriptors, "
3458 			"error %u\n", nbuf * ndesc, dd->dd_name, error);
3459 		goto fail1;
3460 	}
3461 
3462 	error = bus_dmamap_load(dd->dd_dmat, dd->dd_dmamap,
3463 				dd->dd_desc, dd->dd_desc_len,
3464 				ath_load_cb, &dd->dd_desc_paddr,
3465 				BUS_DMA_NOWAIT);
3466 	if (error != 0) {
3467 		if_printf(ifp, "unable to map %s descriptors, error %u\n",
3468 			dd->dd_name, error);
3469 		goto fail2;
3470 	}
3471 
3472 	ds = (uint8_t *) dd->dd_desc;
3473 	DPRINTF(sc, ATH_DEBUG_RESET, "%s: %s DMA map: %p (%lu) -> %p (%lu)\n",
3474 	    __func__, dd->dd_name, ds, (u_long) dd->dd_desc_len,
3475 	    (caddr_t) dd->dd_desc_paddr, /*XXX*/ (u_long) dd->dd_desc_len);
3476 
3477 	/* allocate rx buffers */
3478 	bsize = sizeof(struct ath_buf) * nbuf;
3479 	bf = malloc(bsize, M_ATHDEV, M_NOWAIT | M_ZERO);
3480 	if (bf == NULL) {
3481 		if_printf(ifp, "malloc of %s buffers failed, size %u\n",
3482 			dd->dd_name, bsize);
3483 		goto fail3;
3484 	}
3485 	dd->dd_bufptr = bf;
3486 
3487 	TAILQ_INIT(head);
3488 	for (i = 0; i < nbuf; i++, bf++, ds += (ndesc * desc_len)) {
3489 		bf->bf_desc = (struct ath_desc *) ds;
3490 		bf->bf_daddr = DS2PHYS(dd, ds);
3491 		if (! ath_hal_split4ktrans(sc->sc_ah)) {
3492 			/*
3493 			 * Merlin WAR: Skip descriptor addresses which
3494 			 * cause 4KB boundary crossing along any point
3495 			 * in the descriptor.
3496 			 */
3497 			 if (ATH_DESC_4KB_BOUND_CHECK(bf->bf_daddr,
3498 			     desc_len * ndesc)) {
3499 				/* Start at the next page */
3500 				ds += 0x1000 - (bf->bf_daddr & 0xFFF);
3501 				bf->bf_desc = (struct ath_desc *) ds;
3502 				bf->bf_daddr = DS2PHYS(dd, ds);
3503 			}
3504 		}
3505 		error = bus_dmamap_create(sc->sc_dmat, BUS_DMA_NOWAIT,
3506 				&bf->bf_dmamap);
3507 		if (error != 0) {
3508 			if_printf(ifp, "unable to create dmamap for %s "
3509 				"buffer %u, error %u\n", dd->dd_name, i, error);
3510 			ath_descdma_cleanup(sc, dd, head);
3511 			return error;
3512 		}
3513 		bf->bf_lastds = bf->bf_desc;	/* Just an initial value */
3514 		TAILQ_INSERT_TAIL(head, bf, bf_list);
3515 	}
3516 	return 0;
3517 fail3:
3518 	bus_dmamap_unload(dd->dd_dmat, dd->dd_dmamap);
3519 fail2:
3520 	bus_dmamem_free(dd->dd_dmat, dd->dd_desc, dd->dd_dmamap);
3521 fail1:
3522 	bus_dmamap_destroy(dd->dd_dmat, dd->dd_dmamap);
3523 fail0:
3524 	bus_dma_tag_destroy(dd->dd_dmat);
3525 	memset(dd, 0, sizeof(*dd));
3526 	return error;
3527 #undef DS2PHYS
3528 #undef ATH_DESC_4KB_BOUND_CHECK
3529 }
3530 
3531 static void
3532 ath_descdma_cleanup(struct ath_softc *sc,
3533 	struct ath_descdma *dd, ath_bufhead *head)
3534 {
3535 	struct ath_buf *bf;
3536 	struct ieee80211_node *ni;
3537 
3538 	bus_dmamap_unload(dd->dd_dmat, dd->dd_dmamap);
3539 	bus_dmamem_free(dd->dd_dmat, dd->dd_desc, dd->dd_dmamap);
3540 	bus_dmamap_destroy(dd->dd_dmat, dd->dd_dmamap);
3541 	bus_dma_tag_destroy(dd->dd_dmat);
3542 
3543 	TAILQ_FOREACH(bf, head, bf_list) {
3544 		if (bf->bf_m) {
3545 			m_freem(bf->bf_m);
3546 			bf->bf_m = NULL;
3547 		}
3548 		if (bf->bf_dmamap != NULL) {
3549 			bus_dmamap_destroy(sc->sc_dmat, bf->bf_dmamap);
3550 			bf->bf_dmamap = NULL;
3551 		}
3552 		ni = bf->bf_node;
3553 		bf->bf_node = NULL;
3554 		if (ni != NULL) {
3555 			/*
3556 			 * Reclaim node reference.
3557 			 */
3558 			ieee80211_free_node(ni);
3559 		}
3560 	}
3561 
3562 	TAILQ_INIT(head);
3563 	free(dd->dd_bufptr, M_ATHDEV);
3564 	memset(dd, 0, sizeof(*dd));
3565 }
3566 
3567 static int
3568 ath_desc_alloc(struct ath_softc *sc)
3569 {
3570 	int error;
3571 
3572 	error = ath_descdma_setup(sc, &sc->sc_rxdma, &sc->sc_rxbuf,
3573 			"rx", ath_rxbuf, 1);
3574 	if (error != 0)
3575 		return error;
3576 
3577 	error = ath_descdma_setup(sc, &sc->sc_txdma, &sc->sc_txbuf,
3578 			"tx", ath_txbuf, ATH_TXDESC);
3579 	if (error != 0) {
3580 		ath_descdma_cleanup(sc, &sc->sc_rxdma, &sc->sc_rxbuf);
3581 		return error;
3582 	}
3583 
3584 	error = ath_descdma_setup(sc, &sc->sc_bdma, &sc->sc_bbuf,
3585 			"beacon", ATH_BCBUF, 1);
3586 	if (error != 0) {
3587 		ath_descdma_cleanup(sc, &sc->sc_txdma, &sc->sc_txbuf);
3588 		ath_descdma_cleanup(sc, &sc->sc_rxdma, &sc->sc_rxbuf);
3589 		return error;
3590 	}
3591 	return 0;
3592 }
3593 
3594 static void
3595 ath_desc_free(struct ath_softc *sc)
3596 {
3597 
3598 	if (sc->sc_bdma.dd_desc_len != 0)
3599 		ath_descdma_cleanup(sc, &sc->sc_bdma, &sc->sc_bbuf);
3600 	if (sc->sc_txdma.dd_desc_len != 0)
3601 		ath_descdma_cleanup(sc, &sc->sc_txdma, &sc->sc_txbuf);
3602 	if (sc->sc_rxdma.dd_desc_len != 0)
3603 		ath_descdma_cleanup(sc, &sc->sc_rxdma, &sc->sc_rxbuf);
3604 }
3605 
3606 static struct ieee80211_node *
3607 ath_node_alloc(struct ieee80211vap *vap, const uint8_t mac[IEEE80211_ADDR_LEN])
3608 {
3609 	struct ieee80211com *ic = vap->iv_ic;
3610 	struct ath_softc *sc = ic->ic_ifp->if_softc;
3611 	const size_t space = sizeof(struct ath_node) + sc->sc_rc->arc_space;
3612 	struct ath_node *an;
3613 
3614 	an = malloc(space, M_80211_NODE, M_NOWAIT|M_ZERO);
3615 	if (an == NULL) {
3616 		/* XXX stat+msg */
3617 		return NULL;
3618 	}
3619 	ath_rate_node_init(sc, an);
3620 
3621 	/* Setup the mutex - there's no associd yet so set the name to NULL */
3622 	snprintf(an->an_name, sizeof(an->an_name), "%s: node %p",
3623 	    device_get_nameunit(sc->sc_dev), an);
3624 	mtx_init(&an->an_mtx, an->an_name, NULL, MTX_DEF);
3625 
3626 	/* XXX setup ath_tid */
3627 	ath_tx_tid_init(sc, an);
3628 
3629 	DPRINTF(sc, ATH_DEBUG_NODE, "%s: an %p\n", __func__, an);
3630 	return &an->an_node;
3631 }
3632 
3633 static void
3634 ath_node_cleanup(struct ieee80211_node *ni)
3635 {
3636 	struct ieee80211com *ic = ni->ni_ic;
3637 	struct ath_softc *sc = ic->ic_ifp->if_softc;
3638 
3639 	/* Cleanup ath_tid, free unused bufs, unlink bufs in TXQ */
3640 	ath_tx_node_flush(sc, ATH_NODE(ni));
3641 	ath_rate_node_cleanup(sc, ATH_NODE(ni));
3642 	sc->sc_node_cleanup(ni);
3643 }
3644 
3645 static void
3646 ath_node_free(struct ieee80211_node *ni)
3647 {
3648 	struct ieee80211com *ic = ni->ni_ic;
3649 	struct ath_softc *sc = ic->ic_ifp->if_softc;
3650 
3651 	DPRINTF(sc, ATH_DEBUG_NODE, "%s: ni %p\n", __func__, ni);
3652 	mtx_destroy(&ATH_NODE(ni)->an_mtx);
3653 	sc->sc_node_free(ni);
3654 }
3655 
3656 static void
3657 ath_node_getsignal(const struct ieee80211_node *ni, int8_t *rssi, int8_t *noise)
3658 {
3659 	struct ieee80211com *ic = ni->ni_ic;
3660 	struct ath_softc *sc = ic->ic_ifp->if_softc;
3661 	struct ath_hal *ah = sc->sc_ah;
3662 
3663 	*rssi = ic->ic_node_getrssi(ni);
3664 	if (ni->ni_chan != IEEE80211_CHAN_ANYC)
3665 		*noise = ath_hal_getchannoise(ah, ni->ni_chan);
3666 	else
3667 		*noise = -95;		/* nominally correct */
3668 }
3669 
3670 static int
3671 ath_rxbuf_init(struct ath_softc *sc, struct ath_buf *bf)
3672 {
3673 	struct ath_hal *ah = sc->sc_ah;
3674 	int error;
3675 	struct mbuf *m;
3676 	struct ath_desc *ds;
3677 
3678 	m = bf->bf_m;
3679 	if (m == NULL) {
3680 		/*
3681 		 * NB: by assigning a page to the rx dma buffer we
3682 		 * implicitly satisfy the Atheros requirement that
3683 		 * this buffer be cache-line-aligned and sized to be
3684 		 * multiple of the cache line size.  Not doing this
3685 		 * causes weird stuff to happen (for the 5210 at least).
3686 		 */
3687 		m = m_getcl(M_DONTWAIT, MT_DATA, M_PKTHDR);
3688 		if (m == NULL) {
3689 			DPRINTF(sc, ATH_DEBUG_ANY,
3690 				"%s: no mbuf/cluster\n", __func__);
3691 			sc->sc_stats.ast_rx_nombuf++;
3692 			return ENOMEM;
3693 		}
3694 		m->m_pkthdr.len = m->m_len = m->m_ext.ext_size;
3695 
3696 		error = bus_dmamap_load_mbuf_sg(sc->sc_dmat,
3697 					     bf->bf_dmamap, m,
3698 					     bf->bf_segs, &bf->bf_nseg,
3699 					     BUS_DMA_NOWAIT);
3700 		if (error != 0) {
3701 			DPRINTF(sc, ATH_DEBUG_ANY,
3702 			    "%s: bus_dmamap_load_mbuf_sg failed; error %d\n",
3703 			    __func__, error);
3704 			sc->sc_stats.ast_rx_busdma++;
3705 			m_freem(m);
3706 			return error;
3707 		}
3708 		KASSERT(bf->bf_nseg == 1,
3709 			("multi-segment packet; nseg %u", bf->bf_nseg));
3710 		bf->bf_m = m;
3711 	}
3712 	bus_dmamap_sync(sc->sc_dmat, bf->bf_dmamap, BUS_DMASYNC_PREREAD);
3713 
3714 	/*
3715 	 * Setup descriptors.  For receive we always terminate
3716 	 * the descriptor list with a self-linked entry so we'll
3717 	 * not get overrun under high load (as can happen with a
3718 	 * 5212 when ANI processing enables PHY error frames).
3719 	 *
3720 	 * To insure the last descriptor is self-linked we create
3721 	 * each descriptor as self-linked and add it to the end.  As
3722 	 * each additional descriptor is added the previous self-linked
3723 	 * entry is ``fixed'' naturally.  This should be safe even
3724 	 * if DMA is happening.  When processing RX interrupts we
3725 	 * never remove/process the last, self-linked, entry on the
3726 	 * descriptor list.  This insures the hardware always has
3727 	 * someplace to write a new frame.
3728 	 */
3729 	/*
3730 	 * 11N: we can no longer afford to self link the last descriptor.
3731 	 * MAC acknowledges BA status as long as it copies frames to host
3732 	 * buffer (or rx fifo). This can incorrectly acknowledge packets
3733 	 * to a sender if last desc is self-linked.
3734 	 */
3735 	ds = bf->bf_desc;
3736 	if (sc->sc_rxslink)
3737 		ds->ds_link = bf->bf_daddr;	/* link to self */
3738 	else
3739 		ds->ds_link = 0;		/* terminate the list */
3740 	ds->ds_data = bf->bf_segs[0].ds_addr;
3741 	ath_hal_setuprxdesc(ah, ds
3742 		, m->m_len		/* buffer size */
3743 		, 0
3744 	);
3745 
3746 	if (sc->sc_rxlink != NULL)
3747 		*sc->sc_rxlink = bf->bf_daddr;
3748 	sc->sc_rxlink = &ds->ds_link;
3749 	return 0;
3750 }
3751 
3752 /*
3753  * Extend 15-bit time stamp from rx descriptor to
3754  * a full 64-bit TSF using the specified TSF.
3755  */
3756 static __inline u_int64_t
3757 ath_extend_tsf15(u_int32_t rstamp, u_int64_t tsf)
3758 {
3759 	if ((tsf & 0x7fff) < rstamp)
3760 		tsf -= 0x8000;
3761 
3762 	return ((tsf &~ 0x7fff) | rstamp);
3763 }
3764 
3765 /*
3766  * Extend 32-bit time stamp from rx descriptor to
3767  * a full 64-bit TSF using the specified TSF.
3768  */
3769 static __inline u_int64_t
3770 ath_extend_tsf32(u_int32_t rstamp, u_int64_t tsf)
3771 {
3772 	u_int32_t tsf_low = tsf & 0xffffffff;
3773 	u_int64_t tsf64 = (tsf & ~0xffffffffULL) | rstamp;
3774 
3775 	if (rstamp > tsf_low && (rstamp - tsf_low > 0x10000000))
3776 		tsf64 -= 0x100000000ULL;
3777 
3778 	if (rstamp < tsf_low && (tsf_low - rstamp > 0x10000000))
3779 		tsf64 += 0x100000000ULL;
3780 
3781 	return tsf64;
3782 }
3783 
3784 /*
3785  * Extend the TSF from the RX descriptor to a full 64 bit TSF.
3786  * Earlier hardware versions only wrote the low 15 bits of the
3787  * TSF into the RX descriptor; later versions (AR5416 and up)
3788  * include the 32 bit TSF value.
3789  */
3790 static __inline u_int64_t
3791 ath_extend_tsf(struct ath_softc *sc, u_int32_t rstamp, u_int64_t tsf)
3792 {
3793 	if (sc->sc_rxtsf32)
3794 		return ath_extend_tsf32(rstamp, tsf);
3795 	else
3796 		return ath_extend_tsf15(rstamp, tsf);
3797 }
3798 
3799 /*
3800  * Intercept management frames to collect beacon rssi data
3801  * and to do ibss merges.
3802  */
3803 static void
3804 ath_recv_mgmt(struct ieee80211_node *ni, struct mbuf *m,
3805 	int subtype, int rssi, int nf)
3806 {
3807 	struct ieee80211vap *vap = ni->ni_vap;
3808 	struct ath_softc *sc = vap->iv_ic->ic_ifp->if_softc;
3809 
3810 	/*
3811 	 * Call up first so subsequent work can use information
3812 	 * potentially stored in the node (e.g. for ibss merge).
3813 	 */
3814 	ATH_VAP(vap)->av_recv_mgmt(ni, m, subtype, rssi, nf);
3815 	switch (subtype) {
3816 	case IEEE80211_FC0_SUBTYPE_BEACON:
3817 		/* update rssi statistics for use by the hal */
3818 		ATH_RSSI_LPF(sc->sc_halstats.ns_avgbrssi, rssi);
3819 		if (sc->sc_syncbeacon &&
3820 		    ni == vap->iv_bss && vap->iv_state == IEEE80211_S_RUN) {
3821 			/*
3822 			 * Resync beacon timers using the tsf of the beacon
3823 			 * frame we just received.
3824 			 */
3825 			ath_beacon_config(sc, vap);
3826 		}
3827 		/* fall thru... */
3828 	case IEEE80211_FC0_SUBTYPE_PROBE_RESP:
3829 		if (vap->iv_opmode == IEEE80211_M_IBSS &&
3830 		    vap->iv_state == IEEE80211_S_RUN) {
3831 			uint32_t rstamp = sc->sc_lastrs->rs_tstamp;
3832 			uint64_t tsf = ath_extend_tsf(sc, rstamp,
3833 				ath_hal_gettsf64(sc->sc_ah));
3834 			/*
3835 			 * Handle ibss merge as needed; check the tsf on the
3836 			 * frame before attempting the merge.  The 802.11 spec
3837 			 * says the station should change it's bssid to match
3838 			 * the oldest station with the same ssid, where oldest
3839 			 * is determined by the tsf.  Note that hardware
3840 			 * reconfiguration happens through callback to
3841 			 * ath_newstate as the state machine will go from
3842 			 * RUN -> RUN when this happens.
3843 			 */
3844 			if (le64toh(ni->ni_tstamp.tsf) >= tsf) {
3845 				DPRINTF(sc, ATH_DEBUG_STATE,
3846 				    "ibss merge, rstamp %u tsf %ju "
3847 				    "tstamp %ju\n", rstamp, (uintmax_t)tsf,
3848 				    (uintmax_t)ni->ni_tstamp.tsf);
3849 				(void) ieee80211_ibss_merge(ni);
3850 			}
3851 		}
3852 		break;
3853 	}
3854 }
3855 
3856 /*
3857  * Set the default antenna.
3858  */
3859 static void
3860 ath_setdefantenna(struct ath_softc *sc, u_int antenna)
3861 {
3862 	struct ath_hal *ah = sc->sc_ah;
3863 
3864 	/* XXX block beacon interrupts */
3865 	ath_hal_setdefantenna(ah, antenna);
3866 	if (sc->sc_defant != antenna)
3867 		sc->sc_stats.ast_ant_defswitch++;
3868 	sc->sc_defant = antenna;
3869 	sc->sc_rxotherant = 0;
3870 }
3871 
3872 static void
3873 ath_rx_tap(struct ifnet *ifp, struct mbuf *m,
3874 	const struct ath_rx_status *rs, u_int64_t tsf, int16_t nf)
3875 {
3876 #define	CHAN_HT20	htole32(IEEE80211_CHAN_HT20)
3877 #define	CHAN_HT40U	htole32(IEEE80211_CHAN_HT40U)
3878 #define	CHAN_HT40D	htole32(IEEE80211_CHAN_HT40D)
3879 #define	CHAN_HT		(CHAN_HT20|CHAN_HT40U|CHAN_HT40D)
3880 	struct ath_softc *sc = ifp->if_softc;
3881 	const HAL_RATE_TABLE *rt;
3882 	uint8_t rix;
3883 
3884 	rt = sc->sc_currates;
3885 	KASSERT(rt != NULL, ("no rate table, mode %u", sc->sc_curmode));
3886 	rix = rt->rateCodeToIndex[rs->rs_rate];
3887 	sc->sc_rx_th.wr_rate = sc->sc_hwmap[rix].ieeerate;
3888 	sc->sc_rx_th.wr_flags = sc->sc_hwmap[rix].rxflags;
3889 #ifdef AH_SUPPORT_AR5416
3890 	sc->sc_rx_th.wr_chan_flags &= ~CHAN_HT;
3891 	if (sc->sc_rx_th.wr_rate & IEEE80211_RATE_MCS) {	/* HT rate */
3892 		struct ieee80211com *ic = ifp->if_l2com;
3893 
3894 		if ((rs->rs_flags & HAL_RX_2040) == 0)
3895 			sc->sc_rx_th.wr_chan_flags |= CHAN_HT20;
3896 		else if (IEEE80211_IS_CHAN_HT40U(ic->ic_curchan))
3897 			sc->sc_rx_th.wr_chan_flags |= CHAN_HT40U;
3898 		else
3899 			sc->sc_rx_th.wr_chan_flags |= CHAN_HT40D;
3900 		if ((rs->rs_flags & HAL_RX_GI) == 0)
3901 			sc->sc_rx_th.wr_flags |= IEEE80211_RADIOTAP_F_SHORTGI;
3902 	}
3903 #endif
3904 	sc->sc_rx_th.wr_tsf = htole64(ath_extend_tsf(sc, rs->rs_tstamp, tsf));
3905 	if (rs->rs_status & HAL_RXERR_CRC)
3906 		sc->sc_rx_th.wr_flags |= IEEE80211_RADIOTAP_F_BADFCS;
3907 	/* XXX propagate other error flags from descriptor */
3908 	sc->sc_rx_th.wr_antnoise = nf;
3909 	sc->sc_rx_th.wr_antsignal = nf + rs->rs_rssi;
3910 	sc->sc_rx_th.wr_antenna = rs->rs_antenna;
3911 #undef CHAN_HT
3912 #undef CHAN_HT20
3913 #undef CHAN_HT40U
3914 #undef CHAN_HT40D
3915 }
3916 
3917 static void
3918 ath_handle_micerror(struct ieee80211com *ic,
3919 	struct ieee80211_frame *wh, int keyix)
3920 {
3921 	struct ieee80211_node *ni;
3922 
3923 	/* XXX recheck MIC to deal w/ chips that lie */
3924 	/* XXX discard MIC errors on !data frames */
3925 	ni = ieee80211_find_rxnode(ic, (const struct ieee80211_frame_min *) wh);
3926 	if (ni != NULL) {
3927 		ieee80211_notify_michael_failure(ni->ni_vap, wh, keyix);
3928 		ieee80211_free_node(ni);
3929 	}
3930 }
3931 
3932 /*
3933  * Only run the RX proc if it's not already running.
3934  * Since this may get run as part of the reset/flush path,
3935  * the task can't clash with an existing, running tasklet.
3936  */
3937 static void
3938 ath_rx_tasklet(void *arg, int npending)
3939 {
3940 	struct ath_softc *sc = arg;
3941 
3942 	CTR1(ATH_KTR_INTR, "ath_rx_proc: pending=%d", npending);
3943 	DPRINTF(sc, ATH_DEBUG_RX_PROC, "%s: pending %u\n", __func__, npending);
3944 	ATH_PCU_LOCK(sc);
3945 	if (sc->sc_inreset_cnt > 0) {
3946 		device_printf(sc->sc_dev,
3947 		    "%s: sc_inreset_cnt > 0; skipping\n", __func__);
3948 		ATH_PCU_UNLOCK(sc);
3949 		return;
3950 	}
3951 	ATH_PCU_UNLOCK(sc);
3952 	ath_rx_proc(sc, 1);
3953 }
3954 
3955 static void
3956 ath_rx_proc(struct ath_softc *sc, int resched)
3957 {
3958 #define	PA2DESC(_sc, _pa) \
3959 	((struct ath_desc *)((caddr_t)(_sc)->sc_rxdma.dd_desc + \
3960 		((_pa) - (_sc)->sc_rxdma.dd_desc_paddr)))
3961 	struct ath_buf *bf;
3962 	struct ifnet *ifp = sc->sc_ifp;
3963 	struct ieee80211com *ic = ifp->if_l2com;
3964 	struct ath_hal *ah = sc->sc_ah;
3965 	struct ath_desc *ds;
3966 	struct ath_rx_status *rs;
3967 	struct mbuf *m;
3968 	struct ieee80211_node *ni;
3969 	int len, type, ngood;
3970 	HAL_STATUS status;
3971 	int16_t nf;
3972 	u_int64_t tsf;
3973 	int npkts = 0;
3974 
3975 	/* XXX we must not hold the ATH_LOCK here */
3976 	ATH_UNLOCK_ASSERT(sc);
3977 	ATH_PCU_UNLOCK_ASSERT(sc);
3978 
3979 	ATH_PCU_LOCK(sc);
3980 	sc->sc_rxproc_cnt++;
3981 	ATH_PCU_UNLOCK(sc);
3982 
3983 	DPRINTF(sc, ATH_DEBUG_RX_PROC, "%s: called\n", __func__);
3984 	ngood = 0;
3985 	nf = ath_hal_getchannoise(ah, sc->sc_curchan);
3986 	sc->sc_stats.ast_rx_noise = nf;
3987 	tsf = ath_hal_gettsf64(ah);
3988 	do {
3989 		bf = TAILQ_FIRST(&sc->sc_rxbuf);
3990 		if (sc->sc_rxslink && bf == NULL) {	/* NB: shouldn't happen */
3991 			if_printf(ifp, "%s: no buffer!\n", __func__);
3992 			break;
3993 		} else if (bf == NULL) {
3994 			/*
3995 			 * End of List:
3996 			 * this can happen for non-self-linked RX chains
3997 			 */
3998 			sc->sc_stats.ast_rx_hitqueueend++;
3999 			break;
4000 		}
4001 		m = bf->bf_m;
4002 		if (m == NULL) {		/* NB: shouldn't happen */
4003 			/*
4004 			 * If mbuf allocation failed previously there
4005 			 * will be no mbuf; try again to re-populate it.
4006 			 */
4007 			/* XXX make debug msg */
4008 			if_printf(ifp, "%s: no mbuf!\n", __func__);
4009 			TAILQ_REMOVE(&sc->sc_rxbuf, bf, bf_list);
4010 			goto rx_next;
4011 		}
4012 		ds = bf->bf_desc;
4013 		if (ds->ds_link == bf->bf_daddr) {
4014 			/* NB: never process the self-linked entry at the end */
4015 			sc->sc_stats.ast_rx_hitqueueend++;
4016 			break;
4017 		}
4018 		/* XXX sync descriptor memory */
4019 		/*
4020 		 * Must provide the virtual address of the current
4021 		 * descriptor, the physical address, and the virtual
4022 		 * address of the next descriptor in the h/w chain.
4023 		 * This allows the HAL to look ahead to see if the
4024 		 * hardware is done with a descriptor by checking the
4025 		 * done bit in the following descriptor and the address
4026 		 * of the current descriptor the DMA engine is working
4027 		 * on.  All this is necessary because of our use of
4028 		 * a self-linked list to avoid rx overruns.
4029 		 */
4030 		rs = &bf->bf_status.ds_rxstat;
4031 		status = ath_hal_rxprocdesc(ah, ds,
4032 				bf->bf_daddr, PA2DESC(sc, ds->ds_link), rs);
4033 #ifdef ATH_DEBUG
4034 		if (sc->sc_debug & ATH_DEBUG_RECV_DESC)
4035 			ath_printrxbuf(sc, bf, 0, status == HAL_OK);
4036 #endif
4037 		if (status == HAL_EINPROGRESS)
4038 			break;
4039 
4040 		TAILQ_REMOVE(&sc->sc_rxbuf, bf, bf_list);
4041 		npkts++;
4042 
4043 		/* These aren't specifically errors */
4044 #ifdef	AH_SUPPORT_AR5416
4045 		if (rs->rs_flags & HAL_RX_GI)
4046 			sc->sc_stats.ast_rx_halfgi++;
4047 		if (rs->rs_flags & HAL_RX_2040)
4048 			sc->sc_stats.ast_rx_2040++;
4049 		if (rs->rs_flags & HAL_RX_DELIM_CRC_PRE)
4050 			sc->sc_stats.ast_rx_pre_crc_err++;
4051 		if (rs->rs_flags & HAL_RX_DELIM_CRC_POST)
4052 			sc->sc_stats.ast_rx_post_crc_err++;
4053 		if (rs->rs_flags & HAL_RX_DECRYPT_BUSY)
4054 			sc->sc_stats.ast_rx_decrypt_busy_err++;
4055 		if (rs->rs_flags & HAL_RX_HI_RX_CHAIN)
4056 			sc->sc_stats.ast_rx_hi_rx_chain++;
4057 #endif /* AH_SUPPORT_AR5416 */
4058 
4059 		if (rs->rs_status != 0) {
4060 			if (rs->rs_status & HAL_RXERR_CRC)
4061 				sc->sc_stats.ast_rx_crcerr++;
4062 			if (rs->rs_status & HAL_RXERR_FIFO)
4063 				sc->sc_stats.ast_rx_fifoerr++;
4064 			if (rs->rs_status & HAL_RXERR_PHY) {
4065 				sc->sc_stats.ast_rx_phyerr++;
4066 				/* Process DFS radar events */
4067 				if ((rs->rs_phyerr == HAL_PHYERR_RADAR) ||
4068 				    (rs->rs_phyerr == HAL_PHYERR_FALSE_RADAR_EXT)) {
4069 					/* Since we're touching the frame data, sync it */
4070 					bus_dmamap_sync(sc->sc_dmat,
4071 					    bf->bf_dmamap,
4072 					    BUS_DMASYNC_POSTREAD);
4073 					/* Now pass it to the radar processing code */
4074 					ath_dfs_process_phy_err(sc, mtod(m, char *), tsf, rs);
4075 				}
4076 
4077 				/* Be suitably paranoid about receiving phy errors out of the stats array bounds */
4078 				if (rs->rs_phyerr < 64)
4079 					sc->sc_stats.ast_rx_phy[rs->rs_phyerr]++;
4080 				goto rx_error;	/* NB: don't count in ierrors */
4081 			}
4082 			if (rs->rs_status & HAL_RXERR_DECRYPT) {
4083 				/*
4084 				 * Decrypt error.  If the error occurred
4085 				 * because there was no hardware key, then
4086 				 * let the frame through so the upper layers
4087 				 * can process it.  This is necessary for 5210
4088 				 * parts which have no way to setup a ``clear''
4089 				 * key cache entry.
4090 				 *
4091 				 * XXX do key cache faulting
4092 				 */
4093 				if (rs->rs_keyix == HAL_RXKEYIX_INVALID)
4094 					goto rx_accept;
4095 				sc->sc_stats.ast_rx_badcrypt++;
4096 			}
4097 			if (rs->rs_status & HAL_RXERR_MIC) {
4098 				sc->sc_stats.ast_rx_badmic++;
4099 				/*
4100 				 * Do minimal work required to hand off
4101 				 * the 802.11 header for notification.
4102 				 */
4103 				/* XXX frag's and qos frames */
4104 				len = rs->rs_datalen;
4105 				if (len >= sizeof (struct ieee80211_frame)) {
4106 					bus_dmamap_sync(sc->sc_dmat,
4107 					    bf->bf_dmamap,
4108 					    BUS_DMASYNC_POSTREAD);
4109 					ath_handle_micerror(ic,
4110 					    mtod(m, struct ieee80211_frame *),
4111 					    sc->sc_splitmic ?
4112 						rs->rs_keyix-32 : rs->rs_keyix);
4113 				}
4114 			}
4115 			ifp->if_ierrors++;
4116 rx_error:
4117 			/*
4118 			 * Cleanup any pending partial frame.
4119 			 */
4120 			if (sc->sc_rxpending != NULL) {
4121 				m_freem(sc->sc_rxpending);
4122 				sc->sc_rxpending = NULL;
4123 			}
4124 			/*
4125 			 * When a tap is present pass error frames
4126 			 * that have been requested.  By default we
4127 			 * pass decrypt+mic errors but others may be
4128 			 * interesting (e.g. crc).
4129 			 */
4130 			if (ieee80211_radiotap_active(ic) &&
4131 			    (rs->rs_status & sc->sc_monpass)) {
4132 				bus_dmamap_sync(sc->sc_dmat, bf->bf_dmamap,
4133 				    BUS_DMASYNC_POSTREAD);
4134 				/* NB: bpf needs the mbuf length setup */
4135 				len = rs->rs_datalen;
4136 				m->m_pkthdr.len = m->m_len = len;
4137 				bf->bf_m = NULL;
4138 				ath_rx_tap(ifp, m, rs, tsf, nf);
4139 				ieee80211_radiotap_rx_all(ic, m);
4140 				m_freem(m);
4141 			}
4142 			/* XXX pass MIC errors up for s/w reclaculation */
4143 			goto rx_next;
4144 		}
4145 rx_accept:
4146 		/*
4147 		 * Sync and unmap the frame.  At this point we're
4148 		 * committed to passing the mbuf somewhere so clear
4149 		 * bf_m; this means a new mbuf must be allocated
4150 		 * when the rx descriptor is setup again to receive
4151 		 * another frame.
4152 		 */
4153 		bus_dmamap_sync(sc->sc_dmat, bf->bf_dmamap,
4154 		    BUS_DMASYNC_POSTREAD);
4155 		bus_dmamap_unload(sc->sc_dmat, bf->bf_dmamap);
4156 		bf->bf_m = NULL;
4157 
4158 		len = rs->rs_datalen;
4159 		m->m_len = len;
4160 
4161 		if (rs->rs_more) {
4162 			/*
4163 			 * Frame spans multiple descriptors; save
4164 			 * it for the next completed descriptor, it
4165 			 * will be used to construct a jumbogram.
4166 			 */
4167 			if (sc->sc_rxpending != NULL) {
4168 				/* NB: max frame size is currently 2 clusters */
4169 				sc->sc_stats.ast_rx_toobig++;
4170 				m_freem(sc->sc_rxpending);
4171 			}
4172 			m->m_pkthdr.rcvif = ifp;
4173 			m->m_pkthdr.len = len;
4174 			sc->sc_rxpending = m;
4175 			goto rx_next;
4176 		} else if (sc->sc_rxpending != NULL) {
4177 			/*
4178 			 * This is the second part of a jumbogram,
4179 			 * chain it to the first mbuf, adjust the
4180 			 * frame length, and clear the rxpending state.
4181 			 */
4182 			sc->sc_rxpending->m_next = m;
4183 			sc->sc_rxpending->m_pkthdr.len += len;
4184 			m = sc->sc_rxpending;
4185 			sc->sc_rxpending = NULL;
4186 		} else {
4187 			/*
4188 			 * Normal single-descriptor receive; setup
4189 			 * the rcvif and packet length.
4190 			 */
4191 			m->m_pkthdr.rcvif = ifp;
4192 			m->m_pkthdr.len = len;
4193 		}
4194 
4195 		/*
4196 		 * Validate rs->rs_antenna.
4197 		 *
4198 		 * Some users w/ AR9285 NICs have reported crashes
4199 		 * here because rs_antenna field is bogusly large.
4200 		 * Let's enforce the maximum antenna limit of 8
4201 		 * (and it shouldn't be hard coded, but that's a
4202 		 * separate problem) and if there's an issue, print
4203 		 * out an error and adjust rs_antenna to something
4204 		 * sensible.
4205 		 *
4206 		 * This code should be removed once the actual
4207 		 * root cause of the issue has been identified.
4208 		 * For example, it may be that the rs_antenna
4209 		 * field is only valid for the lsat frame of
4210 		 * an aggregate and it just happens that it is
4211 		 * "mostly" right. (This is a general statement -
4212 		 * the majority of the statistics are only valid
4213 		 * for the last frame in an aggregate.
4214 		 */
4215 		if (rs->rs_antenna > 7) {
4216 			device_printf(sc->sc_dev, "%s: rs_antenna > 7 (%d)\n",
4217 			    __func__, rs->rs_antenna);
4218 #ifdef	ATH_DEBUG
4219 			ath_printrxbuf(sc, bf, 0, status == HAL_OK);
4220 #endif /* ATH_DEBUG */
4221 			rs->rs_antenna = 0;	/* XXX better than nothing */
4222 		}
4223 
4224 		ifp->if_ipackets++;
4225 		sc->sc_stats.ast_ant_rx[rs->rs_antenna]++;
4226 
4227 		/*
4228 		 * Populate the rx status block.  When there are bpf
4229 		 * listeners we do the additional work to provide
4230 		 * complete status.  Otherwise we fill in only the
4231 		 * material required by ieee80211_input.  Note that
4232 		 * noise setting is filled in above.
4233 		 */
4234 		if (ieee80211_radiotap_active(ic))
4235 			ath_rx_tap(ifp, m, rs, tsf, nf);
4236 
4237 		/*
4238 		 * From this point on we assume the frame is at least
4239 		 * as large as ieee80211_frame_min; verify that.
4240 		 */
4241 		if (len < IEEE80211_MIN_LEN) {
4242 			if (!ieee80211_radiotap_active(ic)) {
4243 				DPRINTF(sc, ATH_DEBUG_RECV,
4244 				    "%s: short packet %d\n", __func__, len);
4245 				sc->sc_stats.ast_rx_tooshort++;
4246 			} else {
4247 				/* NB: in particular this captures ack's */
4248 				ieee80211_radiotap_rx_all(ic, m);
4249 			}
4250 			m_freem(m);
4251 			goto rx_next;
4252 		}
4253 
4254 		if (IFF_DUMPPKTS(sc, ATH_DEBUG_RECV)) {
4255 			const HAL_RATE_TABLE *rt = sc->sc_currates;
4256 			uint8_t rix = rt->rateCodeToIndex[rs->rs_rate];
4257 
4258 			ieee80211_dump_pkt(ic, mtod(m, caddr_t), len,
4259 			    sc->sc_hwmap[rix].ieeerate, rs->rs_rssi);
4260 		}
4261 
4262 		m_adj(m, -IEEE80211_CRC_LEN);
4263 
4264 		/*
4265 		 * Locate the node for sender, track state, and then
4266 		 * pass the (referenced) node up to the 802.11 layer
4267 		 * for its use.
4268 		 */
4269 		ni = ieee80211_find_rxnode_withkey(ic,
4270 			mtod(m, const struct ieee80211_frame_min *),
4271 			rs->rs_keyix == HAL_RXKEYIX_INVALID ?
4272 				IEEE80211_KEYIX_NONE : rs->rs_keyix);
4273 		sc->sc_lastrs = rs;
4274 
4275 #ifdef	AH_SUPPORT_AR5416
4276 		if (rs->rs_isaggr)
4277 			sc->sc_stats.ast_rx_agg++;
4278 #endif /* AH_SUPPORT_AR5416 */
4279 
4280 		if (ni != NULL) {
4281 			/*
4282  			 * Only punt packets for ampdu reorder processing for
4283 			 * 11n nodes; net80211 enforces that M_AMPDU is only
4284 			 * set for 11n nodes.
4285  			 */
4286 			if (ni->ni_flags & IEEE80211_NODE_HT)
4287 				m->m_flags |= M_AMPDU;
4288 
4289 			/*
4290 			 * Sending station is known, dispatch directly.
4291 			 */
4292 			type = ieee80211_input(ni, m, rs->rs_rssi, nf);
4293 			ieee80211_free_node(ni);
4294 			/*
4295 			 * Arrange to update the last rx timestamp only for
4296 			 * frames from our ap when operating in station mode.
4297 			 * This assumes the rx key is always setup when
4298 			 * associated.
4299 			 */
4300 			if (ic->ic_opmode == IEEE80211_M_STA &&
4301 			    rs->rs_keyix != HAL_RXKEYIX_INVALID)
4302 				ngood++;
4303 		} else {
4304 			type = ieee80211_input_all(ic, m, rs->rs_rssi, nf);
4305 		}
4306 		/*
4307 		 * Track rx rssi and do any rx antenna management.
4308 		 */
4309 		ATH_RSSI_LPF(sc->sc_halstats.ns_avgrssi, rs->rs_rssi);
4310 		if (sc->sc_diversity) {
4311 			/*
4312 			 * When using fast diversity, change the default rx
4313 			 * antenna if diversity chooses the other antenna 3
4314 			 * times in a row.
4315 			 */
4316 			if (sc->sc_defant != rs->rs_antenna) {
4317 				if (++sc->sc_rxotherant >= 3)
4318 					ath_setdefantenna(sc, rs->rs_antenna);
4319 			} else
4320 				sc->sc_rxotherant = 0;
4321 		}
4322 
4323 		/* Newer school diversity - kite specific for now */
4324 		/* XXX perhaps migrate the normal diversity code to this? */
4325 		if ((ah)->ah_rxAntCombDiversity)
4326 			(*(ah)->ah_rxAntCombDiversity)(ah, rs, ticks, hz);
4327 
4328 		if (sc->sc_softled) {
4329 			/*
4330 			 * Blink for any data frame.  Otherwise do a
4331 			 * heartbeat-style blink when idle.  The latter
4332 			 * is mainly for station mode where we depend on
4333 			 * periodic beacon frames to trigger the poll event.
4334 			 */
4335 			if (type == IEEE80211_FC0_TYPE_DATA) {
4336 				const HAL_RATE_TABLE *rt = sc->sc_currates;
4337 				ath_led_event(sc,
4338 				    rt->rateCodeToIndex[rs->rs_rate]);
4339 			} else if (ticks - sc->sc_ledevent >= sc->sc_ledidle)
4340 				ath_led_event(sc, 0);
4341 		}
4342 rx_next:
4343 		TAILQ_INSERT_TAIL(&sc->sc_rxbuf, bf, bf_list);
4344 	} while (ath_rxbuf_init(sc, bf) == 0);
4345 
4346 	/* rx signal state monitoring */
4347 	ath_hal_rxmonitor(ah, &sc->sc_halstats, sc->sc_curchan);
4348 	if (ngood)
4349 		sc->sc_lastrx = tsf;
4350 
4351 	CTR2(ATH_KTR_INTR, "ath_rx_proc: npkts=%d, ngood=%d", npkts, ngood);
4352 	/* Queue DFS tasklet if needed */
4353 	if (resched && ath_dfs_tasklet_needed(sc, sc->sc_curchan))
4354 		taskqueue_enqueue(sc->sc_tq, &sc->sc_dfstask);
4355 
4356 	/*
4357 	 * Now that all the RX frames were handled that
4358 	 * need to be handled, kick the PCU if there's
4359 	 * been an RXEOL condition.
4360 	 */
4361 	ATH_PCU_LOCK(sc);
4362 	if (resched && sc->sc_kickpcu) {
4363 		CTR0(ATH_KTR_ERR, "ath_rx_proc: kickpcu");
4364 		device_printf(sc->sc_dev, "%s: kickpcu; handled %d packets\n",
4365 		    __func__, npkts);
4366 
4367 		/* XXX rxslink? */
4368 		/*
4369 		 * XXX can we hold the PCU lock here?
4370 		 * Are there any net80211 buffer calls involved?
4371 		 */
4372 		bf = TAILQ_FIRST(&sc->sc_rxbuf);
4373 		ath_hal_putrxbuf(ah, bf->bf_daddr);
4374 		ath_hal_rxena(ah);		/* enable recv descriptors */
4375 		ath_mode_init(sc);		/* set filters, etc. */
4376 		ath_hal_startpcurecv(ah);	/* re-enable PCU/DMA engine */
4377 
4378 		ath_hal_intrset(ah, sc->sc_imask);
4379 		sc->sc_kickpcu = 0;
4380 	}
4381 	ATH_PCU_UNLOCK(sc);
4382 
4383 	/* XXX check this inside of IF_LOCK? */
4384 	if (resched && (ifp->if_drv_flags & IFF_DRV_OACTIVE) == 0) {
4385 #ifdef IEEE80211_SUPPORT_SUPERG
4386 		ieee80211_ff_age_all(ic, 100);
4387 #endif
4388 		if (!IFQ_IS_EMPTY(&ifp->if_snd))
4389 			ath_start(ifp);
4390 	}
4391 #undef PA2DESC
4392 
4393 	ATH_PCU_LOCK(sc);
4394 	sc->sc_rxproc_cnt--;
4395 	ATH_PCU_UNLOCK(sc);
4396 }
4397 
4398 static void
4399 ath_txq_init(struct ath_softc *sc, struct ath_txq *txq, int qnum)
4400 {
4401 	txq->axq_qnum = qnum;
4402 	txq->axq_ac = 0;
4403 	txq->axq_depth = 0;
4404 	txq->axq_aggr_depth = 0;
4405 	txq->axq_intrcnt = 0;
4406 	txq->axq_link = NULL;
4407 	txq->axq_softc = sc;
4408 	TAILQ_INIT(&txq->axq_q);
4409 	TAILQ_INIT(&txq->axq_tidq);
4410 	ATH_TXQ_LOCK_INIT(sc, txq);
4411 }
4412 
4413 /*
4414  * Setup a h/w transmit queue.
4415  */
4416 static struct ath_txq *
4417 ath_txq_setup(struct ath_softc *sc, int qtype, int subtype)
4418 {
4419 #define	N(a)	(sizeof(a)/sizeof(a[0]))
4420 	struct ath_hal *ah = sc->sc_ah;
4421 	HAL_TXQ_INFO qi;
4422 	int qnum;
4423 
4424 	memset(&qi, 0, sizeof(qi));
4425 	qi.tqi_subtype = subtype;
4426 	qi.tqi_aifs = HAL_TXQ_USEDEFAULT;
4427 	qi.tqi_cwmin = HAL_TXQ_USEDEFAULT;
4428 	qi.tqi_cwmax = HAL_TXQ_USEDEFAULT;
4429 	/*
4430 	 * Enable interrupts only for EOL and DESC conditions.
4431 	 * We mark tx descriptors to receive a DESC interrupt
4432 	 * when a tx queue gets deep; otherwise waiting for the
4433 	 * EOL to reap descriptors.  Note that this is done to
4434 	 * reduce interrupt load and this only defers reaping
4435 	 * descriptors, never transmitting frames.  Aside from
4436 	 * reducing interrupts this also permits more concurrency.
4437 	 * The only potential downside is if the tx queue backs
4438 	 * up in which case the top half of the kernel may backup
4439 	 * due to a lack of tx descriptors.
4440 	 */
4441 	qi.tqi_qflags = HAL_TXQ_TXEOLINT_ENABLE | HAL_TXQ_TXDESCINT_ENABLE;
4442 	qnum = ath_hal_setuptxqueue(ah, qtype, &qi);
4443 	if (qnum == -1) {
4444 		/*
4445 		 * NB: don't print a message, this happens
4446 		 * normally on parts with too few tx queues
4447 		 */
4448 		return NULL;
4449 	}
4450 	if (qnum >= N(sc->sc_txq)) {
4451 		device_printf(sc->sc_dev,
4452 			"hal qnum %u out of range, max %zu!\n",
4453 			qnum, N(sc->sc_txq));
4454 		ath_hal_releasetxqueue(ah, qnum);
4455 		return NULL;
4456 	}
4457 	if (!ATH_TXQ_SETUP(sc, qnum)) {
4458 		ath_txq_init(sc, &sc->sc_txq[qnum], qnum);
4459 		sc->sc_txqsetup |= 1<<qnum;
4460 	}
4461 	return &sc->sc_txq[qnum];
4462 #undef N
4463 }
4464 
4465 /*
4466  * Setup a hardware data transmit queue for the specified
4467  * access control.  The hal may not support all requested
4468  * queues in which case it will return a reference to a
4469  * previously setup queue.  We record the mapping from ac's
4470  * to h/w queues for use by ath_tx_start and also track
4471  * the set of h/w queues being used to optimize work in the
4472  * transmit interrupt handler and related routines.
4473  */
4474 static int
4475 ath_tx_setup(struct ath_softc *sc, int ac, int haltype)
4476 {
4477 #define	N(a)	(sizeof(a)/sizeof(a[0]))
4478 	struct ath_txq *txq;
4479 
4480 	if (ac >= N(sc->sc_ac2q)) {
4481 		device_printf(sc->sc_dev, "AC %u out of range, max %zu!\n",
4482 			ac, N(sc->sc_ac2q));
4483 		return 0;
4484 	}
4485 	txq = ath_txq_setup(sc, HAL_TX_QUEUE_DATA, haltype);
4486 	if (txq != NULL) {
4487 		txq->axq_ac = ac;
4488 		sc->sc_ac2q[ac] = txq;
4489 		return 1;
4490 	} else
4491 		return 0;
4492 #undef N
4493 }
4494 
4495 /*
4496  * Update WME parameters for a transmit queue.
4497  */
4498 static int
4499 ath_txq_update(struct ath_softc *sc, int ac)
4500 {
4501 #define	ATH_EXPONENT_TO_VALUE(v)	((1<<v)-1)
4502 #define	ATH_TXOP_TO_US(v)		(v<<5)
4503 	struct ifnet *ifp = sc->sc_ifp;
4504 	struct ieee80211com *ic = ifp->if_l2com;
4505 	struct ath_txq *txq = sc->sc_ac2q[ac];
4506 	struct wmeParams *wmep = &ic->ic_wme.wme_chanParams.cap_wmeParams[ac];
4507 	struct ath_hal *ah = sc->sc_ah;
4508 	HAL_TXQ_INFO qi;
4509 
4510 	ath_hal_gettxqueueprops(ah, txq->axq_qnum, &qi);
4511 #ifdef IEEE80211_SUPPORT_TDMA
4512 	if (sc->sc_tdma) {
4513 		/*
4514 		 * AIFS is zero so there's no pre-transmit wait.  The
4515 		 * burst time defines the slot duration and is configured
4516 		 * through net80211.  The QCU is setup to not do post-xmit
4517 		 * back off, lockout all lower-priority QCU's, and fire
4518 		 * off the DMA beacon alert timer which is setup based
4519 		 * on the slot configuration.
4520 		 */
4521 		qi.tqi_qflags = HAL_TXQ_TXOKINT_ENABLE
4522 			      | HAL_TXQ_TXERRINT_ENABLE
4523 			      | HAL_TXQ_TXURNINT_ENABLE
4524 			      | HAL_TXQ_TXEOLINT_ENABLE
4525 			      | HAL_TXQ_DBA_GATED
4526 			      | HAL_TXQ_BACKOFF_DISABLE
4527 			      | HAL_TXQ_ARB_LOCKOUT_GLOBAL
4528 			      ;
4529 		qi.tqi_aifs = 0;
4530 		/* XXX +dbaprep? */
4531 		qi.tqi_readyTime = sc->sc_tdmaslotlen;
4532 		qi.tqi_burstTime = qi.tqi_readyTime;
4533 	} else {
4534 #endif
4535 		/*
4536 		 * XXX shouldn't this just use the default flags
4537 		 * used in the previous queue setup?
4538 		 */
4539 		qi.tqi_qflags = HAL_TXQ_TXOKINT_ENABLE
4540 			      | HAL_TXQ_TXERRINT_ENABLE
4541 			      | HAL_TXQ_TXDESCINT_ENABLE
4542 			      | HAL_TXQ_TXURNINT_ENABLE
4543 			      | HAL_TXQ_TXEOLINT_ENABLE
4544 			      ;
4545 		qi.tqi_aifs = wmep->wmep_aifsn;
4546 		qi.tqi_cwmin = ATH_EXPONENT_TO_VALUE(wmep->wmep_logcwmin);
4547 		qi.tqi_cwmax = ATH_EXPONENT_TO_VALUE(wmep->wmep_logcwmax);
4548 		qi.tqi_readyTime = 0;
4549 		qi.tqi_burstTime = ATH_TXOP_TO_US(wmep->wmep_txopLimit);
4550 #ifdef IEEE80211_SUPPORT_TDMA
4551 	}
4552 #endif
4553 
4554 	DPRINTF(sc, ATH_DEBUG_RESET,
4555 	    "%s: Q%u qflags 0x%x aifs %u cwmin %u cwmax %u burstTime %u\n",
4556 	    __func__, txq->axq_qnum, qi.tqi_qflags,
4557 	    qi.tqi_aifs, qi.tqi_cwmin, qi.tqi_cwmax, qi.tqi_burstTime);
4558 
4559 	if (!ath_hal_settxqueueprops(ah, txq->axq_qnum, &qi)) {
4560 		if_printf(ifp, "unable to update hardware queue "
4561 			"parameters for %s traffic!\n",
4562 			ieee80211_wme_acnames[ac]);
4563 		return 0;
4564 	} else {
4565 		ath_hal_resettxqueue(ah, txq->axq_qnum); /* push to h/w */
4566 		return 1;
4567 	}
4568 #undef ATH_TXOP_TO_US
4569 #undef ATH_EXPONENT_TO_VALUE
4570 }
4571 
4572 /*
4573  * Callback from the 802.11 layer to update WME parameters.
4574  */
4575 static int
4576 ath_wme_update(struct ieee80211com *ic)
4577 {
4578 	struct ath_softc *sc = ic->ic_ifp->if_softc;
4579 
4580 	return !ath_txq_update(sc, WME_AC_BE) ||
4581 	    !ath_txq_update(sc, WME_AC_BK) ||
4582 	    !ath_txq_update(sc, WME_AC_VI) ||
4583 	    !ath_txq_update(sc, WME_AC_VO) ? EIO : 0;
4584 }
4585 
4586 /*
4587  * Reclaim resources for a setup queue.
4588  */
4589 static void
4590 ath_tx_cleanupq(struct ath_softc *sc, struct ath_txq *txq)
4591 {
4592 
4593 	ath_hal_releasetxqueue(sc->sc_ah, txq->axq_qnum);
4594 	ATH_TXQ_LOCK_DESTROY(txq);
4595 	sc->sc_txqsetup &= ~(1<<txq->axq_qnum);
4596 }
4597 
4598 /*
4599  * Reclaim all tx queue resources.
4600  */
4601 static void
4602 ath_tx_cleanup(struct ath_softc *sc)
4603 {
4604 	int i;
4605 
4606 	ATH_TXBUF_LOCK_DESTROY(sc);
4607 	for (i = 0; i < HAL_NUM_TX_QUEUES; i++)
4608 		if (ATH_TXQ_SETUP(sc, i))
4609 			ath_tx_cleanupq(sc, &sc->sc_txq[i]);
4610 }
4611 
4612 /*
4613  * Return h/w rate index for an IEEE rate (w/o basic rate bit)
4614  * using the current rates in sc_rixmap.
4615  */
4616 int
4617 ath_tx_findrix(const struct ath_softc *sc, uint8_t rate)
4618 {
4619 	int rix = sc->sc_rixmap[rate];
4620 	/* NB: return lowest rix for invalid rate */
4621 	return (rix == 0xff ? 0 : rix);
4622 }
4623 
4624 static void
4625 ath_tx_update_stats(struct ath_softc *sc, struct ath_tx_status *ts,
4626     struct ath_buf *bf)
4627 {
4628 	struct ieee80211_node *ni = bf->bf_node;
4629 	struct ifnet *ifp = sc->sc_ifp;
4630 	struct ieee80211com *ic = ifp->if_l2com;
4631 	int sr, lr, pri;
4632 
4633 	if (ts->ts_status == 0) {
4634 		u_int8_t txant = ts->ts_antenna;
4635 		sc->sc_stats.ast_ant_tx[txant]++;
4636 		sc->sc_ant_tx[txant]++;
4637 		if (ts->ts_finaltsi != 0)
4638 			sc->sc_stats.ast_tx_altrate++;
4639 		pri = M_WME_GETAC(bf->bf_m);
4640 		if (pri >= WME_AC_VO)
4641 			ic->ic_wme.wme_hipri_traffic++;
4642 		if ((bf->bf_txflags & HAL_TXDESC_NOACK) == 0)
4643 			ni->ni_inact = ni->ni_inact_reload;
4644 	} else {
4645 		if (ts->ts_status & HAL_TXERR_XRETRY)
4646 			sc->sc_stats.ast_tx_xretries++;
4647 		if (ts->ts_status & HAL_TXERR_FIFO)
4648 			sc->sc_stats.ast_tx_fifoerr++;
4649 		if (ts->ts_status & HAL_TXERR_FILT)
4650 			sc->sc_stats.ast_tx_filtered++;
4651 		if (ts->ts_status & HAL_TXERR_XTXOP)
4652 			sc->sc_stats.ast_tx_xtxop++;
4653 		if (ts->ts_status & HAL_TXERR_TIMER_EXPIRED)
4654 			sc->sc_stats.ast_tx_timerexpired++;
4655 
4656 		if (ts->ts_status & HAL_TX_DATA_UNDERRUN)
4657 			sc->sc_stats.ast_tx_data_underrun++;
4658 		if (ts->ts_status & HAL_TX_DELIM_UNDERRUN)
4659 			sc->sc_stats.ast_tx_delim_underrun++;
4660 
4661 		if (bf->bf_m->m_flags & M_FF)
4662 			sc->sc_stats.ast_ff_txerr++;
4663 	}
4664 	/* XXX when is this valid? */
4665 	if (ts->ts_status & HAL_TX_DESC_CFG_ERR)
4666 		sc->sc_stats.ast_tx_desccfgerr++;
4667 
4668 	sr = ts->ts_shortretry;
4669 	lr = ts->ts_longretry;
4670 	sc->sc_stats.ast_tx_shortretry += sr;
4671 	sc->sc_stats.ast_tx_longretry += lr;
4672 
4673 }
4674 
4675 /*
4676  * The default completion. If fail is 1, this means
4677  * "please don't retry the frame, and just return -1 status
4678  * to the net80211 stack.
4679  */
4680 void
4681 ath_tx_default_comp(struct ath_softc *sc, struct ath_buf *bf, int fail)
4682 {
4683 	struct ath_tx_status *ts = &bf->bf_status.ds_txstat;
4684 	int st;
4685 
4686 	if (fail == 1)
4687 		st = -1;
4688 	else
4689 		st = ((bf->bf_txflags & HAL_TXDESC_NOACK) == 0) ?
4690 		    ts->ts_status : HAL_TXERR_XRETRY;
4691 
4692 	if (bf->bf_state.bfs_dobaw)
4693 		device_printf(sc->sc_dev,
4694 		    "%s: dobaw should've been cleared!\n", __func__);
4695 	if (bf->bf_next != NULL)
4696 		device_printf(sc->sc_dev,
4697 		    "%s: bf_next not NULL!\n", __func__);
4698 
4699 	/*
4700 	 * Do any tx complete callback.  Note this must
4701 	 * be done before releasing the node reference.
4702 	 * This will free the mbuf, release the net80211
4703 	 * node and recycle the ath_buf.
4704 	 */
4705 	ath_tx_freebuf(sc, bf, st);
4706 }
4707 
4708 /*
4709  * Update rate control with the given completion status.
4710  */
4711 void
4712 ath_tx_update_ratectrl(struct ath_softc *sc, struct ieee80211_node *ni,
4713     struct ath_rc_series *rc, struct ath_tx_status *ts, int frmlen,
4714     int nframes, int nbad)
4715 {
4716 	struct ath_node *an;
4717 
4718 	/* Only for unicast frames */
4719 	if (ni == NULL)
4720 		return;
4721 
4722 	an = ATH_NODE(ni);
4723 
4724 	if ((ts->ts_status & HAL_TXERR_FILT) == 0) {
4725 		ATH_NODE_LOCK(an);
4726 		ath_rate_tx_complete(sc, an, rc, ts, frmlen, nframes, nbad);
4727 		ATH_NODE_UNLOCK(an);
4728 	}
4729 }
4730 
4731 /*
4732  * Update the busy status of the last frame on the free list.
4733  * When doing TDMA, the busy flag tracks whether the hardware
4734  * currently points to this buffer or not, and thus gated DMA
4735  * may restart by re-reading the last descriptor in this
4736  * buffer.
4737  *
4738  * This should be called in the completion function once one
4739  * of the buffers has been used.
4740  */
4741 static void
4742 ath_tx_update_busy(struct ath_softc *sc)
4743 {
4744 	struct ath_buf *last;
4745 
4746 	/*
4747 	 * Since the last frame may still be marked
4748 	 * as ATH_BUF_BUSY, unmark it here before
4749 	 * finishing the frame processing.
4750 	 * Since we've completed a frame (aggregate
4751 	 * or otherwise), the hardware has moved on
4752 	 * and is no longer referencing the previous
4753 	 * descriptor.
4754 	 */
4755 	ATH_TXBUF_LOCK_ASSERT(sc);
4756 	last = TAILQ_LAST(&sc->sc_txbuf, ath_bufhead_s);
4757 	if (last != NULL)
4758 		last->bf_flags &= ~ATH_BUF_BUSY;
4759 }
4760 
4761 
4762 /*
4763  * Process completed xmit descriptors from the specified queue.
4764  * Kick the packet scheduler if needed. This can occur from this
4765  * particular task.
4766  */
4767 static int
4768 ath_tx_processq(struct ath_softc *sc, struct ath_txq *txq, int dosched)
4769 {
4770 	struct ath_hal *ah = sc->sc_ah;
4771 	struct ath_buf *bf;
4772 	struct ath_desc *ds;
4773 	struct ath_tx_status *ts;
4774 	struct ieee80211_node *ni;
4775 	struct ath_node *an;
4776 	int nacked;
4777 	HAL_STATUS status;
4778 
4779 	DPRINTF(sc, ATH_DEBUG_TX_PROC, "%s: tx queue %u head %p link %p\n",
4780 		__func__, txq->axq_qnum,
4781 		(caddr_t)(uintptr_t) ath_hal_gettxbuf(sc->sc_ah, txq->axq_qnum),
4782 		txq->axq_link);
4783 	nacked = 0;
4784 	for (;;) {
4785 		ATH_TXQ_LOCK(txq);
4786 		txq->axq_intrcnt = 0;	/* reset periodic desc intr count */
4787 		bf = TAILQ_FIRST(&txq->axq_q);
4788 		if (bf == NULL) {
4789 			ATH_TXQ_UNLOCK(txq);
4790 			break;
4791 		}
4792 		ds = bf->bf_lastds;	/* XXX must be setup correctly! */
4793 		ts = &bf->bf_status.ds_txstat;
4794 		status = ath_hal_txprocdesc(ah, ds, ts);
4795 #ifdef ATH_DEBUG
4796 		if (sc->sc_debug & ATH_DEBUG_XMIT_DESC)
4797 			ath_printtxbuf(sc, bf, txq->axq_qnum, 0,
4798 			    status == HAL_OK);
4799 #endif
4800 		if (status == HAL_EINPROGRESS) {
4801 			ATH_TXQ_UNLOCK(txq);
4802 			break;
4803 		}
4804 		ATH_TXQ_REMOVE(txq, bf, bf_list);
4805 #ifdef IEEE80211_SUPPORT_TDMA
4806 		if (txq->axq_depth > 0) {
4807 			/*
4808 			 * More frames follow.  Mark the buffer busy
4809 			 * so it's not re-used while the hardware may
4810 			 * still re-read the link field in the descriptor.
4811 			 *
4812 			 * Use the last buffer in an aggregate as that
4813 			 * is where the hardware may be - intermediate
4814 			 * descriptors won't be "busy".
4815 			 */
4816 			bf->bf_last->bf_flags |= ATH_BUF_BUSY;
4817 		} else
4818 #else
4819 		if (txq->axq_depth == 0)
4820 #endif
4821 			txq->axq_link = NULL;
4822 		if (bf->bf_state.bfs_aggr)
4823 			txq->axq_aggr_depth--;
4824 
4825 		ni = bf->bf_node;
4826 		/*
4827 		 * If unicast frame was ack'd update RSSI,
4828 		 * including the last rx time used to
4829 		 * workaround phantom bmiss interrupts.
4830 		 */
4831 		if (ni != NULL && ts->ts_status == 0 &&
4832 		    ((bf->bf_txflags & HAL_TXDESC_NOACK) == 0)) {
4833 			nacked++;
4834 			sc->sc_stats.ast_tx_rssi = ts->ts_rssi;
4835 			ATH_RSSI_LPF(sc->sc_halstats.ns_avgtxrssi,
4836 				ts->ts_rssi);
4837 		}
4838 		ATH_TXQ_UNLOCK(txq);
4839 
4840 		/* If unicast frame, update general statistics */
4841 		if (ni != NULL) {
4842 			an = ATH_NODE(ni);
4843 			/* update statistics */
4844 			ath_tx_update_stats(sc, ts, bf);
4845 		}
4846 
4847 		/*
4848 		 * Call the completion handler.
4849 		 * The completion handler is responsible for
4850 		 * calling the rate control code.
4851 		 *
4852 		 * Frames with no completion handler get the
4853 		 * rate control code called here.
4854 		 */
4855 		if (bf->bf_comp == NULL) {
4856 			if ((ts->ts_status & HAL_TXERR_FILT) == 0 &&
4857 			    (bf->bf_txflags & HAL_TXDESC_NOACK) == 0) {
4858 				/*
4859 				 * XXX assume this isn't an aggregate
4860 				 * frame.
4861 				 */
4862 				ath_tx_update_ratectrl(sc, ni,
4863 				     bf->bf_state.bfs_rc, ts,
4864 				    bf->bf_state.bfs_pktlen, 1,
4865 				    (ts->ts_status == 0 ? 0 : 1));
4866 			}
4867 			ath_tx_default_comp(sc, bf, 0);
4868 		} else
4869 			bf->bf_comp(sc, bf, 0);
4870 	}
4871 #ifdef IEEE80211_SUPPORT_SUPERG
4872 	/*
4873 	 * Flush fast-frame staging queue when traffic slows.
4874 	 */
4875 	if (txq->axq_depth <= 1)
4876 		ieee80211_ff_flush(ic, txq->axq_ac);
4877 #endif
4878 
4879 	/* Kick the TXQ scheduler */
4880 	if (dosched) {
4881 		ATH_TXQ_LOCK(txq);
4882 		ath_txq_sched(sc, txq);
4883 		ATH_TXQ_UNLOCK(txq);
4884 	}
4885 
4886 	return nacked;
4887 }
4888 
4889 #define	TXQACTIVE(t, q)		( (t) & (1 << (q)))
4890 
4891 /*
4892  * Deferred processing of transmit interrupt; special-cased
4893  * for a single hardware transmit queue (e.g. 5210 and 5211).
4894  */
4895 static void
4896 ath_tx_proc_q0(void *arg, int npending)
4897 {
4898 	struct ath_softc *sc = arg;
4899 	struct ifnet *ifp = sc->sc_ifp;
4900 	uint32_t txqs;
4901 
4902 	ATH_PCU_LOCK(sc);
4903 	sc->sc_txproc_cnt++;
4904 	txqs = sc->sc_txq_active;
4905 	sc->sc_txq_active &= ~txqs;
4906 	ATH_PCU_UNLOCK(sc);
4907 
4908 	if (TXQACTIVE(txqs, 0) && ath_tx_processq(sc, &sc->sc_txq[0], 1))
4909 		/* XXX why is lastrx updated in tx code? */
4910 		sc->sc_lastrx = ath_hal_gettsf64(sc->sc_ah);
4911 	if (TXQACTIVE(txqs, sc->sc_cabq->axq_qnum))
4912 		ath_tx_processq(sc, sc->sc_cabq, 1);
4913 	/* XXX check this inside of IF_LOCK? */
4914 	ifp->if_drv_flags &= ~IFF_DRV_OACTIVE;
4915 	sc->sc_wd_timer = 0;
4916 
4917 	if (sc->sc_softled)
4918 		ath_led_event(sc, sc->sc_txrix);
4919 
4920 	ATH_PCU_LOCK(sc);
4921 	sc->sc_txproc_cnt--;
4922 	ATH_PCU_UNLOCK(sc);
4923 
4924 	ath_start(ifp);
4925 }
4926 
4927 /*
4928  * Deferred processing of transmit interrupt; special-cased
4929  * for four hardware queues, 0-3 (e.g. 5212 w/ WME support).
4930  */
4931 static void
4932 ath_tx_proc_q0123(void *arg, int npending)
4933 {
4934 	struct ath_softc *sc = arg;
4935 	struct ifnet *ifp = sc->sc_ifp;
4936 	int nacked;
4937 	uint32_t txqs;
4938 
4939 	ATH_PCU_LOCK(sc);
4940 	sc->sc_txproc_cnt++;
4941 	txqs = sc->sc_txq_active;
4942 	sc->sc_txq_active &= ~txqs;
4943 	ATH_PCU_UNLOCK(sc);
4944 
4945 	/*
4946 	 * Process each active queue.
4947 	 */
4948 	nacked = 0;
4949 	if (TXQACTIVE(txqs, 0))
4950 		nacked += ath_tx_processq(sc, &sc->sc_txq[0], 1);
4951 	if (TXQACTIVE(txqs, 1))
4952 		nacked += ath_tx_processq(sc, &sc->sc_txq[1], 1);
4953 	if (TXQACTIVE(txqs, 2))
4954 		nacked += ath_tx_processq(sc, &sc->sc_txq[2], 1);
4955 	if (TXQACTIVE(txqs, 3))
4956 		nacked += ath_tx_processq(sc, &sc->sc_txq[3], 1);
4957 	if (TXQACTIVE(txqs, sc->sc_cabq->axq_qnum))
4958 		ath_tx_processq(sc, sc->sc_cabq, 1);
4959 	if (nacked)
4960 		sc->sc_lastrx = ath_hal_gettsf64(sc->sc_ah);
4961 
4962 	/* XXX check this inside of IF_LOCK? */
4963 	ifp->if_drv_flags &= ~IFF_DRV_OACTIVE;
4964 	sc->sc_wd_timer = 0;
4965 
4966 	if (sc->sc_softled)
4967 		ath_led_event(sc, sc->sc_txrix);
4968 
4969 	ATH_PCU_LOCK(sc);
4970 	sc->sc_txproc_cnt--;
4971 	ATH_PCU_UNLOCK(sc);
4972 
4973 	ath_start(ifp);
4974 }
4975 
4976 /*
4977  * Deferred processing of transmit interrupt.
4978  */
4979 static void
4980 ath_tx_proc(void *arg, int npending)
4981 {
4982 	struct ath_softc *sc = arg;
4983 	struct ifnet *ifp = sc->sc_ifp;
4984 	int i, nacked;
4985 	uint32_t txqs;
4986 
4987 	ATH_PCU_LOCK(sc);
4988 	sc->sc_txproc_cnt++;
4989 	txqs = sc->sc_txq_active;
4990 	sc->sc_txq_active &= ~txqs;
4991 	ATH_PCU_UNLOCK(sc);
4992 
4993 	/*
4994 	 * Process each active queue.
4995 	 */
4996 	nacked = 0;
4997 	for (i = 0; i < HAL_NUM_TX_QUEUES; i++)
4998 		if (ATH_TXQ_SETUP(sc, i) && TXQACTIVE(txqs, i))
4999 			nacked += ath_tx_processq(sc, &sc->sc_txq[i], 1);
5000 	if (nacked)
5001 		sc->sc_lastrx = ath_hal_gettsf64(sc->sc_ah);
5002 
5003 	/* XXX check this inside of IF_LOCK? */
5004 	ifp->if_drv_flags &= ~IFF_DRV_OACTIVE;
5005 	sc->sc_wd_timer = 0;
5006 
5007 	if (sc->sc_softled)
5008 		ath_led_event(sc, sc->sc_txrix);
5009 
5010 	ATH_PCU_LOCK(sc);
5011 	sc->sc_txproc_cnt--;
5012 	ATH_PCU_UNLOCK(sc);
5013 
5014 	ath_start(ifp);
5015 }
5016 #undef	TXQACTIVE
5017 
5018 /*
5019  * Return a buffer to the pool and update the 'busy' flag on the
5020  * previous 'tail' entry.
5021  *
5022  * This _must_ only be called when the buffer is involved in a completed
5023  * TX. The logic is that if it was part of an active TX, the previous
5024  * buffer on the list is now not involved in a halted TX DMA queue, waiting
5025  * for restart (eg for TDMA.)
5026  *
5027  * The caller must free the mbuf and recycle the node reference.
5028  */
5029 void
5030 ath_freebuf(struct ath_softc *sc, struct ath_buf *bf)
5031 {
5032 	bus_dmamap_unload(sc->sc_dmat, bf->bf_dmamap);
5033 	bus_dmamap_sync(sc->sc_dmat, bf->bf_dmamap, BUS_DMASYNC_POSTWRITE);
5034 
5035 	KASSERT((bf->bf_node == NULL), ("%s: bf->bf_node != NULL\n", __func__));
5036 	KASSERT((bf->bf_m == NULL), ("%s: bf->bf_m != NULL\n", __func__));
5037 
5038 	ATH_TXBUF_LOCK(sc);
5039 	ath_tx_update_busy(sc);
5040 	TAILQ_INSERT_TAIL(&sc->sc_txbuf, bf, bf_list);
5041 	ATH_TXBUF_UNLOCK(sc);
5042 }
5043 
5044 /*
5045  * This is currently used by ath_tx_draintxq() and
5046  * ath_tx_tid_free_pkts().
5047  *
5048  * It recycles a single ath_buf.
5049  */
5050 void
5051 ath_tx_freebuf(struct ath_softc *sc, struct ath_buf *bf, int status)
5052 {
5053 	struct ieee80211_node *ni = bf->bf_node;
5054 	struct mbuf *m0 = bf->bf_m;
5055 
5056 	bf->bf_node = NULL;
5057 	bf->bf_m = NULL;
5058 
5059 	/* Free the buffer, it's not needed any longer */
5060 	ath_freebuf(sc, bf);
5061 
5062 	if (ni != NULL) {
5063 		/*
5064 		 * Do any callback and reclaim the node reference.
5065 		 */
5066 		if (m0->m_flags & M_TXCB)
5067 			ieee80211_process_callback(ni, m0, status);
5068 		ieee80211_free_node(ni);
5069 	}
5070 	m_freem(m0);
5071 
5072 	/*
5073 	 * XXX the buffer used to be freed -after-, but the DMA map was
5074 	 * freed where ath_freebuf() now is. I've no idea what this
5075 	 * will do.
5076 	 */
5077 }
5078 
5079 void
5080 ath_tx_draintxq(struct ath_softc *sc, struct ath_txq *txq)
5081 {
5082 #ifdef ATH_DEBUG
5083 	struct ath_hal *ah = sc->sc_ah;
5084 #endif
5085 	struct ath_buf *bf;
5086 	u_int ix;
5087 
5088 	/*
5089 	 * NB: this assumes output has been stopped and
5090 	 *     we do not need to block ath_tx_proc
5091 	 */
5092 	ATH_TXBUF_LOCK(sc);
5093 	bf = TAILQ_LAST(&sc->sc_txbuf, ath_bufhead_s);
5094 	if (bf != NULL)
5095 		bf->bf_flags &= ~ATH_BUF_BUSY;
5096 	ATH_TXBUF_UNLOCK(sc);
5097 
5098 	for (ix = 0;; ix++) {
5099 		ATH_TXQ_LOCK(txq);
5100 		bf = TAILQ_FIRST(&txq->axq_q);
5101 		if (bf == NULL) {
5102 			txq->axq_link = NULL;
5103 			ATH_TXQ_UNLOCK(txq);
5104 			break;
5105 		}
5106 		ATH_TXQ_REMOVE(txq, bf, bf_list);
5107 		if (bf->bf_state.bfs_aggr)
5108 			txq->axq_aggr_depth--;
5109 #ifdef ATH_DEBUG
5110 		if (sc->sc_debug & ATH_DEBUG_RESET) {
5111 			struct ieee80211com *ic = sc->sc_ifp->if_l2com;
5112 
5113 			ath_printtxbuf(sc, bf, txq->axq_qnum, ix,
5114 				ath_hal_txprocdesc(ah, bf->bf_lastds,
5115 				    &bf->bf_status.ds_txstat) == HAL_OK);
5116 			ieee80211_dump_pkt(ic, mtod(bf->bf_m, const uint8_t *),
5117 			    bf->bf_m->m_len, 0, -1);
5118 		}
5119 #endif /* ATH_DEBUG */
5120 		/*
5121 		 * Since we're now doing magic in the completion
5122 		 * functions, we -must- call it for aggregation
5123 		 * destinations or BAW tracking will get upset.
5124 		 */
5125 		/*
5126 		 * Clear ATH_BUF_BUSY; the completion handler
5127 		 * will free the buffer.
5128 		 */
5129 		ATH_TXQ_UNLOCK(txq);
5130 		bf->bf_flags &= ~ATH_BUF_BUSY;
5131 		if (bf->bf_comp)
5132 			bf->bf_comp(sc, bf, 1);
5133 		else
5134 			ath_tx_default_comp(sc, bf, 1);
5135 	}
5136 
5137 	/*
5138 	 * Drain software queued frames which are on
5139 	 * active TIDs.
5140 	 */
5141 	ath_tx_txq_drain(sc, txq);
5142 }
5143 
5144 static void
5145 ath_tx_stopdma(struct ath_softc *sc, struct ath_txq *txq)
5146 {
5147 	struct ath_hal *ah = sc->sc_ah;
5148 
5149 	DPRINTF(sc, ATH_DEBUG_RESET, "%s: tx queue [%u] %p, link %p\n",
5150 	    __func__, txq->axq_qnum,
5151 	    (caddr_t)(uintptr_t) ath_hal_gettxbuf(ah, txq->axq_qnum),
5152 	    txq->axq_link);
5153 	(void) ath_hal_stoptxdma(ah, txq->axq_qnum);
5154 }
5155 
5156 static int
5157 ath_stoptxdma(struct ath_softc *sc)
5158 {
5159 	struct ath_hal *ah = sc->sc_ah;
5160 	int i;
5161 
5162 	/* XXX return value */
5163 	if (sc->sc_invalid)
5164 		return 0;
5165 
5166 	if (!sc->sc_invalid) {
5167 		/* don't touch the hardware if marked invalid */
5168 		DPRINTF(sc, ATH_DEBUG_RESET, "%s: tx queue [%u] %p, link %p\n",
5169 		    __func__, sc->sc_bhalq,
5170 		    (caddr_t)(uintptr_t) ath_hal_gettxbuf(ah, sc->sc_bhalq),
5171 		    NULL);
5172 		(void) ath_hal_stoptxdma(ah, sc->sc_bhalq);
5173 		for (i = 0; i < HAL_NUM_TX_QUEUES; i++)
5174 			if (ATH_TXQ_SETUP(sc, i))
5175 				ath_tx_stopdma(sc, &sc->sc_txq[i]);
5176 	}
5177 
5178 	return 1;
5179 }
5180 
5181 /*
5182  * Drain the transmit queues and reclaim resources.
5183  */
5184 static void
5185 ath_draintxq(struct ath_softc *sc, ATH_RESET_TYPE reset_type)
5186 {
5187 #ifdef	ATH_DEBUG
5188 	struct ath_hal *ah = sc->sc_ah;
5189 #endif
5190 	struct ifnet *ifp = sc->sc_ifp;
5191 	int i;
5192 
5193 	(void) ath_stoptxdma(sc);
5194 
5195 	for (i = 0; i < HAL_NUM_TX_QUEUES; i++) {
5196 		/*
5197 		 * XXX TODO: should we just handle the completed TX frames
5198 		 * here, whether or not the reset is a full one or not?
5199 		 */
5200 		if (ATH_TXQ_SETUP(sc, i)) {
5201 			if (reset_type == ATH_RESET_NOLOSS)
5202 				ath_tx_processq(sc, &sc->sc_txq[i], 0);
5203 			else
5204 				ath_tx_draintxq(sc, &sc->sc_txq[i]);
5205 		}
5206 	}
5207 #ifdef ATH_DEBUG
5208 	if (sc->sc_debug & ATH_DEBUG_RESET) {
5209 		struct ath_buf *bf = TAILQ_FIRST(&sc->sc_bbuf);
5210 		if (bf != NULL && bf->bf_m != NULL) {
5211 			ath_printtxbuf(sc, bf, sc->sc_bhalq, 0,
5212 				ath_hal_txprocdesc(ah, bf->bf_lastds,
5213 				    &bf->bf_status.ds_txstat) == HAL_OK);
5214 			ieee80211_dump_pkt(ifp->if_l2com,
5215 			    mtod(bf->bf_m, const uint8_t *), bf->bf_m->m_len,
5216 			    0, -1);
5217 		}
5218 	}
5219 #endif /* ATH_DEBUG */
5220 	/* XXX check this inside of IF_LOCK? */
5221 	ifp->if_drv_flags &= ~IFF_DRV_OACTIVE;
5222 	sc->sc_wd_timer = 0;
5223 }
5224 
5225 /*
5226  * Disable the receive h/w in preparation for a reset.
5227  */
5228 static void
5229 ath_stoprecv(struct ath_softc *sc, int dodelay)
5230 {
5231 #define	PA2DESC(_sc, _pa) \
5232 	((struct ath_desc *)((caddr_t)(_sc)->sc_rxdma.dd_desc + \
5233 		((_pa) - (_sc)->sc_rxdma.dd_desc_paddr)))
5234 	struct ath_hal *ah = sc->sc_ah;
5235 
5236 	ath_hal_stoppcurecv(ah);	/* disable PCU */
5237 	ath_hal_setrxfilter(ah, 0);	/* clear recv filter */
5238 	ath_hal_stopdmarecv(ah);	/* disable DMA engine */
5239 	if (dodelay)
5240 		DELAY(3000);		/* 3ms is long enough for 1 frame */
5241 #ifdef ATH_DEBUG
5242 	if (sc->sc_debug & (ATH_DEBUG_RESET | ATH_DEBUG_FATAL)) {
5243 		struct ath_buf *bf;
5244 		u_int ix;
5245 
5246 		printf("%s: rx queue %p, link %p\n", __func__,
5247 			(caddr_t)(uintptr_t) ath_hal_getrxbuf(ah), sc->sc_rxlink);
5248 		ix = 0;
5249 		TAILQ_FOREACH(bf, &sc->sc_rxbuf, bf_list) {
5250 			struct ath_desc *ds = bf->bf_desc;
5251 			struct ath_rx_status *rs = &bf->bf_status.ds_rxstat;
5252 			HAL_STATUS status = ath_hal_rxprocdesc(ah, ds,
5253 				bf->bf_daddr, PA2DESC(sc, ds->ds_link), rs);
5254 			if (status == HAL_OK || (sc->sc_debug & ATH_DEBUG_FATAL))
5255 				ath_printrxbuf(sc, bf, ix, status == HAL_OK);
5256 			ix++;
5257 		}
5258 	}
5259 #endif
5260 	if (sc->sc_rxpending != NULL) {
5261 		m_freem(sc->sc_rxpending);
5262 		sc->sc_rxpending = NULL;
5263 	}
5264 	sc->sc_rxlink = NULL;		/* just in case */
5265 #undef PA2DESC
5266 }
5267 
5268 /*
5269  * Enable the receive h/w following a reset.
5270  */
5271 static int
5272 ath_startrecv(struct ath_softc *sc)
5273 {
5274 	struct ath_hal *ah = sc->sc_ah;
5275 	struct ath_buf *bf;
5276 
5277 	sc->sc_rxlink = NULL;
5278 	sc->sc_rxpending = NULL;
5279 	TAILQ_FOREACH(bf, &sc->sc_rxbuf, bf_list) {
5280 		int error = ath_rxbuf_init(sc, bf);
5281 		if (error != 0) {
5282 			DPRINTF(sc, ATH_DEBUG_RECV,
5283 				"%s: ath_rxbuf_init failed %d\n",
5284 				__func__, error);
5285 			return error;
5286 		}
5287 	}
5288 
5289 	bf = TAILQ_FIRST(&sc->sc_rxbuf);
5290 	ath_hal_putrxbuf(ah, bf->bf_daddr);
5291 	ath_hal_rxena(ah);		/* enable recv descriptors */
5292 	ath_mode_init(sc);		/* set filters, etc. */
5293 	ath_hal_startpcurecv(ah);	/* re-enable PCU/DMA engine */
5294 	return 0;
5295 }
5296 
5297 /*
5298  * Update internal state after a channel change.
5299  */
5300 static void
5301 ath_chan_change(struct ath_softc *sc, struct ieee80211_channel *chan)
5302 {
5303 	enum ieee80211_phymode mode;
5304 
5305 	/*
5306 	 * Change channels and update the h/w rate map
5307 	 * if we're switching; e.g. 11a to 11b/g.
5308 	 */
5309 	mode = ieee80211_chan2mode(chan);
5310 	if (mode != sc->sc_curmode)
5311 		ath_setcurmode(sc, mode);
5312 	sc->sc_curchan = chan;
5313 }
5314 
5315 /*
5316  * Set/change channels.  If the channel is really being changed,
5317  * it's done by resetting the chip.  To accomplish this we must
5318  * first cleanup any pending DMA, then restart stuff after a la
5319  * ath_init.
5320  */
5321 static int
5322 ath_chan_set(struct ath_softc *sc, struct ieee80211_channel *chan)
5323 {
5324 	struct ifnet *ifp = sc->sc_ifp;
5325 	struct ieee80211com *ic = ifp->if_l2com;
5326 	struct ath_hal *ah = sc->sc_ah;
5327 	int ret = 0;
5328 	int dointr = 0;
5329 
5330 	/* Treat this as an interface reset */
5331 	ATH_PCU_LOCK(sc);
5332 	if (ath_reset_grablock(sc, 1) == 0) {
5333 		device_printf(sc->sc_dev, "%s: concurrent reset! Danger!\n",
5334 		    __func__);
5335 	}
5336 	if (chan != sc->sc_curchan) {
5337 		dointr = 1;
5338 		/* XXX only do this if inreset_cnt is 1? */
5339 		ath_hal_intrset(ah, 0);
5340 	}
5341 	ATH_PCU_UNLOCK(sc);
5342 	ath_txrx_stop(sc);
5343 
5344 	DPRINTF(sc, ATH_DEBUG_RESET, "%s: %u (%u MHz, flags 0x%x)\n",
5345 	    __func__, ieee80211_chan2ieee(ic, chan),
5346 	    chan->ic_freq, chan->ic_flags);
5347 	if (chan != sc->sc_curchan) {
5348 		HAL_STATUS status;
5349 		/*
5350 		 * To switch channels clear any pending DMA operations;
5351 		 * wait long enough for the RX fifo to drain, reset the
5352 		 * hardware at the new frequency, and then re-enable
5353 		 * the relevant bits of the h/w.
5354 		 */
5355 #if 0
5356 		ath_hal_intrset(ah, 0);		/* disable interrupts */
5357 #endif
5358 		ath_stoprecv(sc, 1);		/* turn off frame recv */
5359 		/*
5360 		 * First, handle completed TX/RX frames.
5361 		 */
5362 		ath_rx_proc(sc, 0);
5363 		ath_draintxq(sc, ATH_RESET_NOLOSS);
5364 		/*
5365 		 * Next, flush the non-scheduled frames.
5366 		 */
5367 		ath_draintxq(sc, ATH_RESET_FULL);	/* clear pending tx frames */
5368 
5369 		if (!ath_hal_reset(ah, sc->sc_opmode, chan, AH_TRUE, &status)) {
5370 			if_printf(ifp, "%s: unable to reset "
5371 			    "channel %u (%u MHz, flags 0x%x), hal status %u\n",
5372 			    __func__, ieee80211_chan2ieee(ic, chan),
5373 			    chan->ic_freq, chan->ic_flags, status);
5374 			ret = EIO;
5375 			goto finish;
5376 		}
5377 		sc->sc_diversity = ath_hal_getdiversity(ah);
5378 
5379 		/* Let DFS at it in case it's a DFS channel */
5380 		ath_dfs_radar_enable(sc, ic->ic_curchan);
5381 
5382 		/*
5383 		 * Re-enable rx framework.
5384 		 */
5385 		if (ath_startrecv(sc) != 0) {
5386 			if_printf(ifp, "%s: unable to restart recv logic\n",
5387 			    __func__);
5388 			ret = EIO;
5389 			goto finish;
5390 		}
5391 
5392 		/*
5393 		 * Change channels and update the h/w rate map
5394 		 * if we're switching; e.g. 11a to 11b/g.
5395 		 */
5396 		ath_chan_change(sc, chan);
5397 
5398 		/*
5399 		 * Reset clears the beacon timers; reset them
5400 		 * here if needed.
5401 		 */
5402 		if (sc->sc_beacons) {		/* restart beacons */
5403 #ifdef IEEE80211_SUPPORT_TDMA
5404 			if (sc->sc_tdma)
5405 				ath_tdma_config(sc, NULL);
5406 			else
5407 #endif
5408 			ath_beacon_config(sc, NULL);
5409 		}
5410 
5411 #if 0
5412 		/*
5413 		 * Re-enable interrupts.
5414 		 */
5415 		ath_hal_intrset(ah, sc->sc_imask);
5416 #endif
5417 	}
5418 
5419 finish:
5420 	ATH_PCU_LOCK(sc);
5421 	sc->sc_inreset_cnt--;
5422 	/* XXX only do this if sc_inreset_cnt == 0? */
5423 	if (dointr)
5424 		ath_hal_intrset(ah, sc->sc_imask);
5425 	ATH_PCU_UNLOCK(sc);
5426 
5427 	/* XXX do this inside of IF_LOCK? */
5428 	ifp->if_drv_flags &= ~IFF_DRV_OACTIVE;
5429 	ath_txrx_start(sc);
5430 	/* XXX ath_start? */
5431 
5432 	return ret;
5433 }
5434 
5435 /*
5436  * Periodically recalibrate the PHY to account
5437  * for temperature/environment changes.
5438  */
5439 static void
5440 ath_calibrate(void *arg)
5441 {
5442 	struct ath_softc *sc = arg;
5443 	struct ath_hal *ah = sc->sc_ah;
5444 	struct ifnet *ifp = sc->sc_ifp;
5445 	struct ieee80211com *ic = ifp->if_l2com;
5446 	HAL_BOOL longCal, isCalDone;
5447 	HAL_BOOL aniCal, shortCal = AH_FALSE;
5448 	int nextcal;
5449 
5450 	if (ic->ic_flags & IEEE80211_F_SCAN)	/* defer, off channel */
5451 		goto restart;
5452 	longCal = (ticks - sc->sc_lastlongcal >= ath_longcalinterval*hz);
5453 	aniCal = (ticks - sc->sc_lastani >= ath_anicalinterval*hz/1000);
5454 	if (sc->sc_doresetcal)
5455 		shortCal = (ticks - sc->sc_lastshortcal >= ath_shortcalinterval*hz/1000);
5456 
5457 	DPRINTF(sc, ATH_DEBUG_CALIBRATE, "%s: shortCal=%d; longCal=%d; aniCal=%d\n", __func__, shortCal, longCal, aniCal);
5458 	if (aniCal) {
5459 		sc->sc_stats.ast_ani_cal++;
5460 		sc->sc_lastani = ticks;
5461 		ath_hal_ani_poll(ah, sc->sc_curchan);
5462 	}
5463 
5464 	if (longCal) {
5465 		sc->sc_stats.ast_per_cal++;
5466 		sc->sc_lastlongcal = ticks;
5467 		if (ath_hal_getrfgain(ah) == HAL_RFGAIN_NEED_CHANGE) {
5468 			/*
5469 			 * Rfgain is out of bounds, reset the chip
5470 			 * to load new gain values.
5471 			 */
5472 			DPRINTF(sc, ATH_DEBUG_CALIBRATE,
5473 				"%s: rfgain change\n", __func__);
5474 			sc->sc_stats.ast_per_rfgain++;
5475 			/*
5476 			 * Drop lock - we can't hold it across the
5477 			 * ath_reset() call. Instead, we'll drop
5478 			 * out here, do a reset, then reschedule
5479 			 * the callout.
5480 			 */
5481 			callout_reset(&sc->sc_cal_ch, 1, ath_calibrate, sc);
5482 			sc->sc_resetcal = 0;
5483 			sc->sc_doresetcal = AH_TRUE;
5484 			ATH_UNLOCK(sc);
5485 			ath_reset(ifp, ATH_RESET_NOLOSS);
5486 			ATH_LOCK(sc);
5487 			return;
5488 		}
5489 		/*
5490 		 * If this long cal is after an idle period, then
5491 		 * reset the data collection state so we start fresh.
5492 		 */
5493 		if (sc->sc_resetcal) {
5494 			(void) ath_hal_calreset(ah, sc->sc_curchan);
5495 			sc->sc_lastcalreset = ticks;
5496 			sc->sc_lastshortcal = ticks;
5497 			sc->sc_resetcal = 0;
5498 			sc->sc_doresetcal = AH_TRUE;
5499 		}
5500 	}
5501 
5502 	/* Only call if we're doing a short/long cal, not for ANI calibration */
5503 	if (shortCal || longCal) {
5504 		if (ath_hal_calibrateN(ah, sc->sc_curchan, longCal, &isCalDone)) {
5505 			if (longCal) {
5506 				/*
5507 				 * Calibrate noise floor data again in case of change.
5508 				 */
5509 				ath_hal_process_noisefloor(ah);
5510 			}
5511 		} else {
5512 			DPRINTF(sc, ATH_DEBUG_ANY,
5513 				"%s: calibration of channel %u failed\n",
5514 				__func__, sc->sc_curchan->ic_freq);
5515 			sc->sc_stats.ast_per_calfail++;
5516 		}
5517 		if (shortCal)
5518 			sc->sc_lastshortcal = ticks;
5519 	}
5520 	if (!isCalDone) {
5521 restart:
5522 		/*
5523 		 * Use a shorter interval to potentially collect multiple
5524 		 * data samples required to complete calibration.  Once
5525 		 * we're told the work is done we drop back to a longer
5526 		 * interval between requests.  We're more aggressive doing
5527 		 * work when operating as an AP to improve operation right
5528 		 * after startup.
5529 		 */
5530 		sc->sc_lastshortcal = ticks;
5531 		nextcal = ath_shortcalinterval*hz/1000;
5532 		if (sc->sc_opmode != HAL_M_HOSTAP)
5533 			nextcal *= 10;
5534 		sc->sc_doresetcal = AH_TRUE;
5535 	} else {
5536 		/* nextcal should be the shortest time for next event */
5537 		nextcal = ath_longcalinterval*hz;
5538 		if (sc->sc_lastcalreset == 0)
5539 			sc->sc_lastcalreset = sc->sc_lastlongcal;
5540 		else if (ticks - sc->sc_lastcalreset >= ath_resetcalinterval*hz)
5541 			sc->sc_resetcal = 1;	/* setup reset next trip */
5542 		sc->sc_doresetcal = AH_FALSE;
5543 	}
5544 	/* ANI calibration may occur more often than short/long/resetcal */
5545 	if (ath_anicalinterval > 0)
5546 		nextcal = MIN(nextcal, ath_anicalinterval*hz/1000);
5547 
5548 	if (nextcal != 0) {
5549 		DPRINTF(sc, ATH_DEBUG_CALIBRATE, "%s: next +%u (%sisCalDone)\n",
5550 		    __func__, nextcal, isCalDone ? "" : "!");
5551 		callout_reset(&sc->sc_cal_ch, nextcal, ath_calibrate, sc);
5552 	} else {
5553 		DPRINTF(sc, ATH_DEBUG_CALIBRATE, "%s: calibration disabled\n",
5554 		    __func__);
5555 		/* NB: don't rearm timer */
5556 	}
5557 }
5558 
5559 static void
5560 ath_scan_start(struct ieee80211com *ic)
5561 {
5562 	struct ifnet *ifp = ic->ic_ifp;
5563 	struct ath_softc *sc = ifp->if_softc;
5564 	struct ath_hal *ah = sc->sc_ah;
5565 	u_int32_t rfilt;
5566 
5567 	/* XXX calibration timer? */
5568 
5569 	sc->sc_scanning = 1;
5570 	sc->sc_syncbeacon = 0;
5571 	rfilt = ath_calcrxfilter(sc);
5572 	ath_hal_setrxfilter(ah, rfilt);
5573 	ath_hal_setassocid(ah, ifp->if_broadcastaddr, 0);
5574 
5575 	DPRINTF(sc, ATH_DEBUG_STATE, "%s: RX filter 0x%x bssid %s aid 0\n",
5576 		 __func__, rfilt, ether_sprintf(ifp->if_broadcastaddr));
5577 }
5578 
5579 static void
5580 ath_scan_end(struct ieee80211com *ic)
5581 {
5582 	struct ifnet *ifp = ic->ic_ifp;
5583 	struct ath_softc *sc = ifp->if_softc;
5584 	struct ath_hal *ah = sc->sc_ah;
5585 	u_int32_t rfilt;
5586 
5587 	sc->sc_scanning = 0;
5588 	rfilt = ath_calcrxfilter(sc);
5589 	ath_hal_setrxfilter(ah, rfilt);
5590 	ath_hal_setassocid(ah, sc->sc_curbssid, sc->sc_curaid);
5591 
5592 	ath_hal_process_noisefloor(ah);
5593 
5594 	DPRINTF(sc, ATH_DEBUG_STATE, "%s: RX filter 0x%x bssid %s aid 0x%x\n",
5595 		 __func__, rfilt, ether_sprintf(sc->sc_curbssid),
5596 		 sc->sc_curaid);
5597 }
5598 
5599 static void
5600 ath_set_channel(struct ieee80211com *ic)
5601 {
5602 	struct ifnet *ifp = ic->ic_ifp;
5603 	struct ath_softc *sc = ifp->if_softc;
5604 
5605 	(void) ath_chan_set(sc, ic->ic_curchan);
5606 	/*
5607 	 * If we are returning to our bss channel then mark state
5608 	 * so the next recv'd beacon's tsf will be used to sync the
5609 	 * beacon timers.  Note that since we only hear beacons in
5610 	 * sta/ibss mode this has no effect in other operating modes.
5611 	 */
5612 	if (!sc->sc_scanning && ic->ic_curchan == ic->ic_bsschan)
5613 		sc->sc_syncbeacon = 1;
5614 }
5615 
5616 /*
5617  * Walk the vap list and check if there any vap's in RUN state.
5618  */
5619 static int
5620 ath_isanyrunningvaps(struct ieee80211vap *this)
5621 {
5622 	struct ieee80211com *ic = this->iv_ic;
5623 	struct ieee80211vap *vap;
5624 
5625 	IEEE80211_LOCK_ASSERT(ic);
5626 
5627 	TAILQ_FOREACH(vap, &ic->ic_vaps, iv_next) {
5628 		if (vap != this && vap->iv_state >= IEEE80211_S_RUN)
5629 			return 1;
5630 	}
5631 	return 0;
5632 }
5633 
5634 static int
5635 ath_newstate(struct ieee80211vap *vap, enum ieee80211_state nstate, int arg)
5636 {
5637 	struct ieee80211com *ic = vap->iv_ic;
5638 	struct ath_softc *sc = ic->ic_ifp->if_softc;
5639 	struct ath_vap *avp = ATH_VAP(vap);
5640 	struct ath_hal *ah = sc->sc_ah;
5641 	struct ieee80211_node *ni = NULL;
5642 	int i, error, stamode;
5643 	u_int32_t rfilt;
5644 	int csa_run_transition = 0;
5645 	static const HAL_LED_STATE leds[] = {
5646 	    HAL_LED_INIT,	/* IEEE80211_S_INIT */
5647 	    HAL_LED_SCAN,	/* IEEE80211_S_SCAN */
5648 	    HAL_LED_AUTH,	/* IEEE80211_S_AUTH */
5649 	    HAL_LED_ASSOC, 	/* IEEE80211_S_ASSOC */
5650 	    HAL_LED_RUN, 	/* IEEE80211_S_CAC */
5651 	    HAL_LED_RUN, 	/* IEEE80211_S_RUN */
5652 	    HAL_LED_RUN, 	/* IEEE80211_S_CSA */
5653 	    HAL_LED_RUN, 	/* IEEE80211_S_SLEEP */
5654 	};
5655 
5656 	DPRINTF(sc, ATH_DEBUG_STATE, "%s: %s -> %s\n", __func__,
5657 		ieee80211_state_name[vap->iv_state],
5658 		ieee80211_state_name[nstate]);
5659 
5660 	if (vap->iv_state == IEEE80211_S_CSA && nstate == IEEE80211_S_RUN)
5661 		csa_run_transition = 1;
5662 
5663 	callout_drain(&sc->sc_cal_ch);
5664 	ath_hal_setledstate(ah, leds[nstate]);	/* set LED */
5665 
5666 	if (nstate == IEEE80211_S_SCAN) {
5667 		/*
5668 		 * Scanning: turn off beacon miss and don't beacon.
5669 		 * Mark beacon state so when we reach RUN state we'll
5670 		 * [re]setup beacons.  Unblock the task q thread so
5671 		 * deferred interrupt processing is done.
5672 		 */
5673 		ath_hal_intrset(ah,
5674 		    sc->sc_imask &~ (HAL_INT_SWBA | HAL_INT_BMISS));
5675 		sc->sc_imask &= ~(HAL_INT_SWBA | HAL_INT_BMISS);
5676 		sc->sc_beacons = 0;
5677 		taskqueue_unblock(sc->sc_tq);
5678 	}
5679 
5680 	ni = vap->iv_bss;
5681 	rfilt = ath_calcrxfilter(sc);
5682 	stamode = (vap->iv_opmode == IEEE80211_M_STA ||
5683 		   vap->iv_opmode == IEEE80211_M_AHDEMO ||
5684 		   vap->iv_opmode == IEEE80211_M_IBSS);
5685 	if (stamode && nstate == IEEE80211_S_RUN) {
5686 		sc->sc_curaid = ni->ni_associd;
5687 		IEEE80211_ADDR_COPY(sc->sc_curbssid, ni->ni_bssid);
5688 		ath_hal_setassocid(ah, sc->sc_curbssid, sc->sc_curaid);
5689 	}
5690 	DPRINTF(sc, ATH_DEBUG_STATE, "%s: RX filter 0x%x bssid %s aid 0x%x\n",
5691 	   __func__, rfilt, ether_sprintf(sc->sc_curbssid), sc->sc_curaid);
5692 	ath_hal_setrxfilter(ah, rfilt);
5693 
5694 	/* XXX is this to restore keycache on resume? */
5695 	if (vap->iv_opmode != IEEE80211_M_STA &&
5696 	    (vap->iv_flags & IEEE80211_F_PRIVACY)) {
5697 		for (i = 0; i < IEEE80211_WEP_NKID; i++)
5698 			if (ath_hal_keyisvalid(ah, i))
5699 				ath_hal_keysetmac(ah, i, ni->ni_bssid);
5700 	}
5701 
5702 	/*
5703 	 * Invoke the parent method to do net80211 work.
5704 	 */
5705 	error = avp->av_newstate(vap, nstate, arg);
5706 	if (error != 0)
5707 		goto bad;
5708 
5709 	if (nstate == IEEE80211_S_RUN) {
5710 		/* NB: collect bss node again, it may have changed */
5711 		ni = vap->iv_bss;
5712 
5713 		DPRINTF(sc, ATH_DEBUG_STATE,
5714 		    "%s(RUN): iv_flags 0x%08x bintvl %d bssid %s "
5715 		    "capinfo 0x%04x chan %d\n", __func__,
5716 		    vap->iv_flags, ni->ni_intval, ether_sprintf(ni->ni_bssid),
5717 		    ni->ni_capinfo, ieee80211_chan2ieee(ic, ic->ic_curchan));
5718 
5719 		switch (vap->iv_opmode) {
5720 #ifdef IEEE80211_SUPPORT_TDMA
5721 		case IEEE80211_M_AHDEMO:
5722 			if ((vap->iv_caps & IEEE80211_C_TDMA) == 0)
5723 				break;
5724 			/* fall thru... */
5725 #endif
5726 		case IEEE80211_M_HOSTAP:
5727 		case IEEE80211_M_IBSS:
5728 		case IEEE80211_M_MBSS:
5729 			/*
5730 			 * Allocate and setup the beacon frame.
5731 			 *
5732 			 * Stop any previous beacon DMA.  This may be
5733 			 * necessary, for example, when an ibss merge
5734 			 * causes reconfiguration; there will be a state
5735 			 * transition from RUN->RUN that means we may
5736 			 * be called with beacon transmission active.
5737 			 */
5738 			ath_hal_stoptxdma(ah, sc->sc_bhalq);
5739 
5740 			error = ath_beacon_alloc(sc, ni);
5741 			if (error != 0)
5742 				goto bad;
5743 			/*
5744 			 * If joining an adhoc network defer beacon timer
5745 			 * configuration to the next beacon frame so we
5746 			 * have a current TSF to use.  Otherwise we're
5747 			 * starting an ibss/bss so there's no need to delay;
5748 			 * if this is the first vap moving to RUN state, then
5749 			 * beacon state needs to be [re]configured.
5750 			 */
5751 			if (vap->iv_opmode == IEEE80211_M_IBSS &&
5752 			    ni->ni_tstamp.tsf != 0) {
5753 				sc->sc_syncbeacon = 1;
5754 			} else if (!sc->sc_beacons) {
5755 #ifdef IEEE80211_SUPPORT_TDMA
5756 				if (vap->iv_caps & IEEE80211_C_TDMA)
5757 					ath_tdma_config(sc, vap);
5758 				else
5759 #endif
5760 					ath_beacon_config(sc, vap);
5761 				sc->sc_beacons = 1;
5762 			}
5763 			break;
5764 		case IEEE80211_M_STA:
5765 			/*
5766 			 * Defer beacon timer configuration to the next
5767 			 * beacon frame so we have a current TSF to use
5768 			 * (any TSF collected when scanning is likely old).
5769 			 * However if it's due to a CSA -> RUN transition,
5770 			 * force a beacon update so we pick up a lack of
5771 			 * beacons from an AP in CAC and thus force a
5772 			 * scan.
5773 			 */
5774 			sc->sc_syncbeacon = 1;
5775 			if (csa_run_transition)
5776 				ath_beacon_config(sc, vap);
5777 			break;
5778 		case IEEE80211_M_MONITOR:
5779 			/*
5780 			 * Monitor mode vaps have only INIT->RUN and RUN->RUN
5781 			 * transitions so we must re-enable interrupts here to
5782 			 * handle the case of a single monitor mode vap.
5783 			 */
5784 			ath_hal_intrset(ah, sc->sc_imask);
5785 			break;
5786 		case IEEE80211_M_WDS:
5787 			break;
5788 		default:
5789 			break;
5790 		}
5791 		/*
5792 		 * Let the hal process statistics collected during a
5793 		 * scan so it can provide calibrated noise floor data.
5794 		 */
5795 		ath_hal_process_noisefloor(ah);
5796 		/*
5797 		 * Reset rssi stats; maybe not the best place...
5798 		 */
5799 		sc->sc_halstats.ns_avgbrssi = ATH_RSSI_DUMMY_MARKER;
5800 		sc->sc_halstats.ns_avgrssi = ATH_RSSI_DUMMY_MARKER;
5801 		sc->sc_halstats.ns_avgtxrssi = ATH_RSSI_DUMMY_MARKER;
5802 		/*
5803 		 * Finally, start any timers and the task q thread
5804 		 * (in case we didn't go through SCAN state).
5805 		 */
5806 		if (ath_longcalinterval != 0) {
5807 			/* start periodic recalibration timer */
5808 			callout_reset(&sc->sc_cal_ch, 1, ath_calibrate, sc);
5809 		} else {
5810 			DPRINTF(sc, ATH_DEBUG_CALIBRATE,
5811 			    "%s: calibration disabled\n", __func__);
5812 		}
5813 		taskqueue_unblock(sc->sc_tq);
5814 	} else if (nstate == IEEE80211_S_INIT) {
5815 		/*
5816 		 * If there are no vaps left in RUN state then
5817 		 * shutdown host/driver operation:
5818 		 * o disable interrupts
5819 		 * o disable the task queue thread
5820 		 * o mark beacon processing as stopped
5821 		 */
5822 		if (!ath_isanyrunningvaps(vap)) {
5823 			sc->sc_imask &= ~(HAL_INT_SWBA | HAL_INT_BMISS);
5824 			/* disable interrupts  */
5825 			ath_hal_intrset(ah, sc->sc_imask &~ HAL_INT_GLOBAL);
5826 			taskqueue_block(sc->sc_tq);
5827 			sc->sc_beacons = 0;
5828 		}
5829 #ifdef IEEE80211_SUPPORT_TDMA
5830 		ath_hal_setcca(ah, AH_TRUE);
5831 #endif
5832 	}
5833 bad:
5834 	return error;
5835 }
5836 
5837 /*
5838  * Allocate a key cache slot to the station so we can
5839  * setup a mapping from key index to node. The key cache
5840  * slot is needed for managing antenna state and for
5841  * compression when stations do not use crypto.  We do
5842  * it uniliaterally here; if crypto is employed this slot
5843  * will be reassigned.
5844  */
5845 static void
5846 ath_setup_stationkey(struct ieee80211_node *ni)
5847 {
5848 	struct ieee80211vap *vap = ni->ni_vap;
5849 	struct ath_softc *sc = vap->iv_ic->ic_ifp->if_softc;
5850 	ieee80211_keyix keyix, rxkeyix;
5851 
5852 	if (!ath_key_alloc(vap, &ni->ni_ucastkey, &keyix, &rxkeyix)) {
5853 		/*
5854 		 * Key cache is full; we'll fall back to doing
5855 		 * the more expensive lookup in software.  Note
5856 		 * this also means no h/w compression.
5857 		 */
5858 		/* XXX msg+statistic */
5859 	} else {
5860 		/* XXX locking? */
5861 		ni->ni_ucastkey.wk_keyix = keyix;
5862 		ni->ni_ucastkey.wk_rxkeyix = rxkeyix;
5863 		/* NB: must mark device key to get called back on delete */
5864 		ni->ni_ucastkey.wk_flags |= IEEE80211_KEY_DEVKEY;
5865 		IEEE80211_ADDR_COPY(ni->ni_ucastkey.wk_macaddr, ni->ni_macaddr);
5866 		/* NB: this will create a pass-thru key entry */
5867 		ath_keyset(sc, vap, &ni->ni_ucastkey, vap->iv_bss);
5868 	}
5869 }
5870 
5871 /*
5872  * Setup driver-specific state for a newly associated node.
5873  * Note that we're called also on a re-associate, the isnew
5874  * param tells us if this is the first time or not.
5875  */
5876 static void
5877 ath_newassoc(struct ieee80211_node *ni, int isnew)
5878 {
5879 	struct ath_node *an = ATH_NODE(ni);
5880 	struct ieee80211vap *vap = ni->ni_vap;
5881 	struct ath_softc *sc = vap->iv_ic->ic_ifp->if_softc;
5882 	const struct ieee80211_txparam *tp = ni->ni_txparms;
5883 
5884 	an->an_mcastrix = ath_tx_findrix(sc, tp->mcastrate);
5885 	an->an_mgmtrix = ath_tx_findrix(sc, tp->mgmtrate);
5886 
5887 	ath_rate_newassoc(sc, an, isnew);
5888 	if (isnew &&
5889 	    (vap->iv_flags & IEEE80211_F_PRIVACY) == 0 && sc->sc_hasclrkey &&
5890 	    ni->ni_ucastkey.wk_keyix == IEEE80211_KEYIX_NONE)
5891 		ath_setup_stationkey(ni);
5892 }
5893 
5894 static int
5895 ath_setregdomain(struct ieee80211com *ic, struct ieee80211_regdomain *reg,
5896 	int nchans, struct ieee80211_channel chans[])
5897 {
5898 	struct ath_softc *sc = ic->ic_ifp->if_softc;
5899 	struct ath_hal *ah = sc->sc_ah;
5900 	HAL_STATUS status;
5901 
5902 	DPRINTF(sc, ATH_DEBUG_REGDOMAIN,
5903 	    "%s: rd %u cc %u location %c%s\n",
5904 	    __func__, reg->regdomain, reg->country, reg->location,
5905 	    reg->ecm ? " ecm" : "");
5906 
5907 	status = ath_hal_set_channels(ah, chans, nchans,
5908 	    reg->country, reg->regdomain);
5909 	if (status != HAL_OK) {
5910 		DPRINTF(sc, ATH_DEBUG_REGDOMAIN, "%s: failed, status %u\n",
5911 		    __func__, status);
5912 		return EINVAL;		/* XXX */
5913 	}
5914 
5915 	return 0;
5916 }
5917 
5918 static void
5919 ath_getradiocaps(struct ieee80211com *ic,
5920 	int maxchans, int *nchans, struct ieee80211_channel chans[])
5921 {
5922 	struct ath_softc *sc = ic->ic_ifp->if_softc;
5923 	struct ath_hal *ah = sc->sc_ah;
5924 
5925 	DPRINTF(sc, ATH_DEBUG_REGDOMAIN, "%s: use rd %u cc %d\n",
5926 	    __func__, SKU_DEBUG, CTRY_DEFAULT);
5927 
5928 	/* XXX check return */
5929 	(void) ath_hal_getchannels(ah, chans, maxchans, nchans,
5930 	    HAL_MODE_ALL, CTRY_DEFAULT, SKU_DEBUG, AH_TRUE);
5931 
5932 }
5933 
5934 static int
5935 ath_getchannels(struct ath_softc *sc)
5936 {
5937 	struct ifnet *ifp = sc->sc_ifp;
5938 	struct ieee80211com *ic = ifp->if_l2com;
5939 	struct ath_hal *ah = sc->sc_ah;
5940 	HAL_STATUS status;
5941 
5942 	/*
5943 	 * Collect channel set based on EEPROM contents.
5944 	 */
5945 	status = ath_hal_init_channels(ah, ic->ic_channels, IEEE80211_CHAN_MAX,
5946 	    &ic->ic_nchans, HAL_MODE_ALL, CTRY_DEFAULT, SKU_NONE, AH_TRUE);
5947 	if (status != HAL_OK) {
5948 		if_printf(ifp, "%s: unable to collect channel list from hal, "
5949 		    "status %d\n", __func__, status);
5950 		return EINVAL;
5951 	}
5952 	(void) ath_hal_getregdomain(ah, &sc->sc_eerd);
5953 	ath_hal_getcountrycode(ah, &sc->sc_eecc);	/* NB: cannot fail */
5954 	/* XXX map Atheros sku's to net80211 SKU's */
5955 	/* XXX net80211 types too small */
5956 	ic->ic_regdomain.regdomain = (uint16_t) sc->sc_eerd;
5957 	ic->ic_regdomain.country = (uint16_t) sc->sc_eecc;
5958 	ic->ic_regdomain.isocc[0] = ' ';	/* XXX don't know */
5959 	ic->ic_regdomain.isocc[1] = ' ';
5960 
5961 	ic->ic_regdomain.ecm = 1;
5962 	ic->ic_regdomain.location = 'I';
5963 
5964 	DPRINTF(sc, ATH_DEBUG_REGDOMAIN,
5965 	    "%s: eeprom rd %u cc %u (mapped rd %u cc %u) location %c%s\n",
5966 	    __func__, sc->sc_eerd, sc->sc_eecc,
5967 	    ic->ic_regdomain.regdomain, ic->ic_regdomain.country,
5968 	    ic->ic_regdomain.location, ic->ic_regdomain.ecm ? " ecm" : "");
5969 	return 0;
5970 }
5971 
5972 static int
5973 ath_rate_setup(struct ath_softc *sc, u_int mode)
5974 {
5975 	struct ath_hal *ah = sc->sc_ah;
5976 	const HAL_RATE_TABLE *rt;
5977 
5978 	switch (mode) {
5979 	case IEEE80211_MODE_11A:
5980 		rt = ath_hal_getratetable(ah, HAL_MODE_11A);
5981 		break;
5982 	case IEEE80211_MODE_HALF:
5983 		rt = ath_hal_getratetable(ah, HAL_MODE_11A_HALF_RATE);
5984 		break;
5985 	case IEEE80211_MODE_QUARTER:
5986 		rt = ath_hal_getratetable(ah, HAL_MODE_11A_QUARTER_RATE);
5987 		break;
5988 	case IEEE80211_MODE_11B:
5989 		rt = ath_hal_getratetable(ah, HAL_MODE_11B);
5990 		break;
5991 	case IEEE80211_MODE_11G:
5992 		rt = ath_hal_getratetable(ah, HAL_MODE_11G);
5993 		break;
5994 	case IEEE80211_MODE_TURBO_A:
5995 		rt = ath_hal_getratetable(ah, HAL_MODE_108A);
5996 		break;
5997 	case IEEE80211_MODE_TURBO_G:
5998 		rt = ath_hal_getratetable(ah, HAL_MODE_108G);
5999 		break;
6000 	case IEEE80211_MODE_STURBO_A:
6001 		rt = ath_hal_getratetable(ah, HAL_MODE_TURBO);
6002 		break;
6003 	case IEEE80211_MODE_11NA:
6004 		rt = ath_hal_getratetable(ah, HAL_MODE_11NA_HT20);
6005 		break;
6006 	case IEEE80211_MODE_11NG:
6007 		rt = ath_hal_getratetable(ah, HAL_MODE_11NG_HT20);
6008 		break;
6009 	default:
6010 		DPRINTF(sc, ATH_DEBUG_ANY, "%s: invalid mode %u\n",
6011 			__func__, mode);
6012 		return 0;
6013 	}
6014 	sc->sc_rates[mode] = rt;
6015 	return (rt != NULL);
6016 }
6017 
6018 static void
6019 ath_setcurmode(struct ath_softc *sc, enum ieee80211_phymode mode)
6020 {
6021 #define	N(a)	(sizeof(a)/sizeof(a[0]))
6022 	/* NB: on/off times from the Atheros NDIS driver, w/ permission */
6023 	static const struct {
6024 		u_int		rate;		/* tx/rx 802.11 rate */
6025 		u_int16_t	timeOn;		/* LED on time (ms) */
6026 		u_int16_t	timeOff;	/* LED off time (ms) */
6027 	} blinkrates[] = {
6028 		{ 108,  40,  10 },
6029 		{  96,  44,  11 },
6030 		{  72,  50,  13 },
6031 		{  48,  57,  14 },
6032 		{  36,  67,  16 },
6033 		{  24,  80,  20 },
6034 		{  22, 100,  25 },
6035 		{  18, 133,  34 },
6036 		{  12, 160,  40 },
6037 		{  10, 200,  50 },
6038 		{   6, 240,  58 },
6039 		{   4, 267,  66 },
6040 		{   2, 400, 100 },
6041 		{   0, 500, 130 },
6042 		/* XXX half/quarter rates */
6043 	};
6044 	const HAL_RATE_TABLE *rt;
6045 	int i, j;
6046 
6047 	memset(sc->sc_rixmap, 0xff, sizeof(sc->sc_rixmap));
6048 	rt = sc->sc_rates[mode];
6049 	KASSERT(rt != NULL, ("no h/w rate set for phy mode %u", mode));
6050 	for (i = 0; i < rt->rateCount; i++) {
6051 		uint8_t ieeerate = rt->info[i].dot11Rate & IEEE80211_RATE_VAL;
6052 		if (rt->info[i].phy != IEEE80211_T_HT)
6053 			sc->sc_rixmap[ieeerate] = i;
6054 		else
6055 			sc->sc_rixmap[ieeerate | IEEE80211_RATE_MCS] = i;
6056 	}
6057 	memset(sc->sc_hwmap, 0, sizeof(sc->sc_hwmap));
6058 	for (i = 0; i < N(sc->sc_hwmap); i++) {
6059 		if (i >= rt->rateCount) {
6060 			sc->sc_hwmap[i].ledon = (500 * hz) / 1000;
6061 			sc->sc_hwmap[i].ledoff = (130 * hz) / 1000;
6062 			continue;
6063 		}
6064 		sc->sc_hwmap[i].ieeerate =
6065 			rt->info[i].dot11Rate & IEEE80211_RATE_VAL;
6066 		if (rt->info[i].phy == IEEE80211_T_HT)
6067 			sc->sc_hwmap[i].ieeerate |= IEEE80211_RATE_MCS;
6068 		sc->sc_hwmap[i].txflags = IEEE80211_RADIOTAP_F_DATAPAD;
6069 		if (rt->info[i].shortPreamble ||
6070 		    rt->info[i].phy == IEEE80211_T_OFDM)
6071 			sc->sc_hwmap[i].txflags |= IEEE80211_RADIOTAP_F_SHORTPRE;
6072 		sc->sc_hwmap[i].rxflags = sc->sc_hwmap[i].txflags;
6073 		for (j = 0; j < N(blinkrates)-1; j++)
6074 			if (blinkrates[j].rate == sc->sc_hwmap[i].ieeerate)
6075 				break;
6076 		/* NB: this uses the last entry if the rate isn't found */
6077 		/* XXX beware of overlow */
6078 		sc->sc_hwmap[i].ledon = (blinkrates[j].timeOn * hz) / 1000;
6079 		sc->sc_hwmap[i].ledoff = (blinkrates[j].timeOff * hz) / 1000;
6080 	}
6081 	sc->sc_currates = rt;
6082 	sc->sc_curmode = mode;
6083 	/*
6084 	 * All protection frames are transmited at 2Mb/s for
6085 	 * 11g, otherwise at 1Mb/s.
6086 	 */
6087 	if (mode == IEEE80211_MODE_11G)
6088 		sc->sc_protrix = ath_tx_findrix(sc, 2*2);
6089 	else
6090 		sc->sc_protrix = ath_tx_findrix(sc, 2*1);
6091 	/* NB: caller is responsible for resetting rate control state */
6092 #undef N
6093 }
6094 
6095 static void
6096 ath_watchdog(void *arg)
6097 {
6098 	struct ath_softc *sc = arg;
6099 	int do_reset = 0;
6100 
6101 	if (sc->sc_wd_timer != 0 && --sc->sc_wd_timer == 0) {
6102 		struct ifnet *ifp = sc->sc_ifp;
6103 		uint32_t hangs;
6104 
6105 		if (ath_hal_gethangstate(sc->sc_ah, 0xffff, &hangs) &&
6106 		    hangs != 0) {
6107 			if_printf(ifp, "%s hang detected (0x%x)\n",
6108 			    hangs & 0xff ? "bb" : "mac", hangs);
6109 		} else
6110 			if_printf(ifp, "device timeout\n");
6111 		do_reset = 1;
6112 		ifp->if_oerrors++;
6113 		sc->sc_stats.ast_watchdog++;
6114 	}
6115 
6116 	/*
6117 	 * We can't hold the lock across the ath_reset() call.
6118 	 */
6119 	if (do_reset) {
6120 		ATH_UNLOCK(sc);
6121 		ath_reset(sc->sc_ifp, ATH_RESET_NOLOSS);
6122 		ATH_LOCK(sc);
6123 	}
6124 
6125 	callout_schedule(&sc->sc_wd_ch, hz);
6126 }
6127 
6128 #ifdef ATH_DIAGAPI
6129 /*
6130  * Diagnostic interface to the HAL.  This is used by various
6131  * tools to do things like retrieve register contents for
6132  * debugging.  The mechanism is intentionally opaque so that
6133  * it can change frequently w/o concern for compatiblity.
6134  */
6135 static int
6136 ath_ioctl_diag(struct ath_softc *sc, struct ath_diag *ad)
6137 {
6138 	struct ath_hal *ah = sc->sc_ah;
6139 	u_int id = ad->ad_id & ATH_DIAG_ID;
6140 	void *indata = NULL;
6141 	void *outdata = NULL;
6142 	u_int32_t insize = ad->ad_in_size;
6143 	u_int32_t outsize = ad->ad_out_size;
6144 	int error = 0;
6145 
6146 	if (ad->ad_id & ATH_DIAG_IN) {
6147 		/*
6148 		 * Copy in data.
6149 		 */
6150 		indata = malloc(insize, M_TEMP, M_NOWAIT);
6151 		if (indata == NULL) {
6152 			error = ENOMEM;
6153 			goto bad;
6154 		}
6155 		error = copyin(ad->ad_in_data, indata, insize);
6156 		if (error)
6157 			goto bad;
6158 	}
6159 	if (ad->ad_id & ATH_DIAG_DYN) {
6160 		/*
6161 		 * Allocate a buffer for the results (otherwise the HAL
6162 		 * returns a pointer to a buffer where we can read the
6163 		 * results).  Note that we depend on the HAL leaving this
6164 		 * pointer for us to use below in reclaiming the buffer;
6165 		 * may want to be more defensive.
6166 		 */
6167 		outdata = malloc(outsize, M_TEMP, M_NOWAIT);
6168 		if (outdata == NULL) {
6169 			error = ENOMEM;
6170 			goto bad;
6171 		}
6172 	}
6173 	if (ath_hal_getdiagstate(ah, id, indata, insize, &outdata, &outsize)) {
6174 		if (outsize < ad->ad_out_size)
6175 			ad->ad_out_size = outsize;
6176 		if (outdata != NULL)
6177 			error = copyout(outdata, ad->ad_out_data,
6178 					ad->ad_out_size);
6179 	} else {
6180 		error = EINVAL;
6181 	}
6182 bad:
6183 	if ((ad->ad_id & ATH_DIAG_IN) && indata != NULL)
6184 		free(indata, M_TEMP);
6185 	if ((ad->ad_id & ATH_DIAG_DYN) && outdata != NULL)
6186 		free(outdata, M_TEMP);
6187 	return error;
6188 }
6189 #endif /* ATH_DIAGAPI */
6190 
6191 static int
6192 ath_ioctl(struct ifnet *ifp, u_long cmd, caddr_t data)
6193 {
6194 #define	IS_RUNNING(ifp) \
6195 	((ifp->if_flags & IFF_UP) && (ifp->if_drv_flags & IFF_DRV_RUNNING))
6196 	struct ath_softc *sc = ifp->if_softc;
6197 	struct ieee80211com *ic = ifp->if_l2com;
6198 	struct ifreq *ifr = (struct ifreq *)data;
6199 	const HAL_RATE_TABLE *rt;
6200 	int error = 0;
6201 
6202 	switch (cmd) {
6203 	case SIOCSIFFLAGS:
6204 		ATH_LOCK(sc);
6205 		if (IS_RUNNING(ifp)) {
6206 			/*
6207 			 * To avoid rescanning another access point,
6208 			 * do not call ath_init() here.  Instead,
6209 			 * only reflect promisc mode settings.
6210 			 */
6211 			ath_mode_init(sc);
6212 		} else if (ifp->if_flags & IFF_UP) {
6213 			/*
6214 			 * Beware of being called during attach/detach
6215 			 * to reset promiscuous mode.  In that case we
6216 			 * will still be marked UP but not RUNNING.
6217 			 * However trying to re-init the interface
6218 			 * is the wrong thing to do as we've already
6219 			 * torn down much of our state.  There's
6220 			 * probably a better way to deal with this.
6221 			 */
6222 			if (!sc->sc_invalid)
6223 				ath_init(sc);	/* XXX lose error */
6224 		} else {
6225 			ath_stop_locked(ifp);
6226 #ifdef notyet
6227 			/* XXX must wakeup in places like ath_vap_delete */
6228 			if (!sc->sc_invalid)
6229 				ath_hal_setpower(sc->sc_ah, HAL_PM_FULL_SLEEP);
6230 #endif
6231 		}
6232 		ATH_UNLOCK(sc);
6233 		break;
6234 	case SIOCGIFMEDIA:
6235 	case SIOCSIFMEDIA:
6236 		error = ifmedia_ioctl(ifp, ifr, &ic->ic_media, cmd);
6237 		break;
6238 	case SIOCGATHSTATS:
6239 		/* NB: embed these numbers to get a consistent view */
6240 		sc->sc_stats.ast_tx_packets = ifp->if_opackets;
6241 		sc->sc_stats.ast_rx_packets = ifp->if_ipackets;
6242 		sc->sc_stats.ast_tx_rssi = ATH_RSSI(sc->sc_halstats.ns_avgtxrssi);
6243 		sc->sc_stats.ast_rx_rssi = ATH_RSSI(sc->sc_halstats.ns_avgrssi);
6244 #ifdef IEEE80211_SUPPORT_TDMA
6245 		sc->sc_stats.ast_tdma_tsfadjp = TDMA_AVG(sc->sc_avgtsfdeltap);
6246 		sc->sc_stats.ast_tdma_tsfadjm = TDMA_AVG(sc->sc_avgtsfdeltam);
6247 #endif
6248 		rt = sc->sc_currates;
6249 		sc->sc_stats.ast_tx_rate =
6250 		    rt->info[sc->sc_txrix].dot11Rate &~ IEEE80211_RATE_BASIC;
6251 		if (rt->info[sc->sc_txrix].phy & IEEE80211_T_HT)
6252 			sc->sc_stats.ast_tx_rate |= IEEE80211_RATE_MCS;
6253 		return copyout(&sc->sc_stats,
6254 		    ifr->ifr_data, sizeof (sc->sc_stats));
6255 	case SIOCZATHSTATS:
6256 		error = priv_check(curthread, PRIV_DRIVER);
6257 		if (error == 0)
6258 			memset(&sc->sc_stats, 0, sizeof(sc->sc_stats));
6259 		break;
6260 #ifdef ATH_DIAGAPI
6261 	case SIOCGATHDIAG:
6262 		error = ath_ioctl_diag(sc, (struct ath_diag *) ifr);
6263 		break;
6264 	case SIOCGATHPHYERR:
6265 		error = ath_ioctl_phyerr(sc,(struct ath_diag*) ifr);
6266 		break;
6267 #endif
6268 	case SIOCGIFADDR:
6269 		error = ether_ioctl(ifp, cmd, data);
6270 		break;
6271 	default:
6272 		error = EINVAL;
6273 		break;
6274 	}
6275 	return error;
6276 #undef IS_RUNNING
6277 }
6278 
6279 /*
6280  * Announce various information on device/driver attach.
6281  */
6282 static void
6283 ath_announce(struct ath_softc *sc)
6284 {
6285 	struct ifnet *ifp = sc->sc_ifp;
6286 	struct ath_hal *ah = sc->sc_ah;
6287 
6288 	if_printf(ifp, "AR%s mac %d.%d RF%s phy %d.%d\n",
6289 		ath_hal_mac_name(ah), ah->ah_macVersion, ah->ah_macRev,
6290 		ath_hal_rf_name(ah), ah->ah_phyRev >> 4, ah->ah_phyRev & 0xf);
6291 	if_printf(ifp, "2GHz radio: 0x%.4x; 5GHz radio: 0x%.4x\n",
6292 		ah->ah_analog2GhzRev, ah->ah_analog5GhzRev);
6293 	if (bootverbose) {
6294 		int i;
6295 		for (i = 0; i <= WME_AC_VO; i++) {
6296 			struct ath_txq *txq = sc->sc_ac2q[i];
6297 			if_printf(ifp, "Use hw queue %u for %s traffic\n",
6298 				txq->axq_qnum, ieee80211_wme_acnames[i]);
6299 		}
6300 		if_printf(ifp, "Use hw queue %u for CAB traffic\n",
6301 			sc->sc_cabq->axq_qnum);
6302 		if_printf(ifp, "Use hw queue %u for beacons\n", sc->sc_bhalq);
6303 	}
6304 	if (ath_rxbuf != ATH_RXBUF)
6305 		if_printf(ifp, "using %u rx buffers\n", ath_rxbuf);
6306 	if (ath_txbuf != ATH_TXBUF)
6307 		if_printf(ifp, "using %u tx buffers\n", ath_txbuf);
6308 	if (sc->sc_mcastkey && bootverbose)
6309 		if_printf(ifp, "using multicast key search\n");
6310 }
6311 
6312 #ifdef IEEE80211_SUPPORT_TDMA
6313 static void
6314 ath_tdma_settimers(struct ath_softc *sc, u_int32_t nexttbtt, u_int32_t bintval)
6315 {
6316 	struct ath_hal *ah = sc->sc_ah;
6317 	HAL_BEACON_TIMERS bt;
6318 
6319 	bt.bt_intval = bintval | HAL_BEACON_ENA;
6320 	bt.bt_nexttbtt = nexttbtt;
6321 	bt.bt_nextdba = (nexttbtt<<3) - sc->sc_tdmadbaprep;
6322 	bt.bt_nextswba = (nexttbtt<<3) - sc->sc_tdmaswbaprep;
6323 	bt.bt_nextatim = nexttbtt+1;
6324 	/* Enables TBTT, DBA, SWBA timers by default */
6325 	bt.bt_flags = 0;
6326 	ath_hal_beaconsettimers(ah, &bt);
6327 }
6328 
6329 /*
6330  * Calculate the beacon interval.  This is periodic in the
6331  * superframe for the bss.  We assume each station is configured
6332  * identically wrt transmit rate so the guard time we calculate
6333  * above will be the same on all stations.  Note we need to
6334  * factor in the xmit time because the hardware will schedule
6335  * a frame for transmit if the start of the frame is within
6336  * the burst time.  When we get hardware that properly kills
6337  * frames in the PCU we can reduce/eliminate the guard time.
6338  *
6339  * Roundup to 1024 is so we have 1 TU buffer in the guard time
6340  * to deal with the granularity of the nexttbtt timer.  11n MAC's
6341  * with 1us timer granularity should allow us to reduce/eliminate
6342  * this.
6343  */
6344 static void
6345 ath_tdma_bintvalsetup(struct ath_softc *sc,
6346 	const struct ieee80211_tdma_state *tdma)
6347 {
6348 	/* copy from vap state (XXX check all vaps have same value?) */
6349 	sc->sc_tdmaslotlen = tdma->tdma_slotlen;
6350 
6351 	sc->sc_tdmabintval = roundup((sc->sc_tdmaslotlen+sc->sc_tdmaguard) *
6352 		tdma->tdma_slotcnt, 1024);
6353 	sc->sc_tdmabintval >>= 10;		/* TSF -> TU */
6354 	if (sc->sc_tdmabintval & 1)
6355 		sc->sc_tdmabintval++;
6356 
6357 	if (tdma->tdma_slot == 0) {
6358 		/*
6359 		 * Only slot 0 beacons; other slots respond.
6360 		 */
6361 		sc->sc_imask |= HAL_INT_SWBA;
6362 		sc->sc_tdmaswba = 0;		/* beacon immediately */
6363 	} else {
6364 		/* XXX all vaps must be slot 0 or slot !0 */
6365 		sc->sc_imask &= ~HAL_INT_SWBA;
6366 	}
6367 }
6368 
6369 /*
6370  * Max 802.11 overhead.  This assumes no 4-address frames and
6371  * the encapsulation done by ieee80211_encap (llc).  We also
6372  * include potential crypto overhead.
6373  */
6374 #define	IEEE80211_MAXOVERHEAD \
6375 	(sizeof(struct ieee80211_qosframe) \
6376 	 + sizeof(struct llc) \
6377 	 + IEEE80211_ADDR_LEN \
6378 	 + IEEE80211_WEP_IVLEN \
6379 	 + IEEE80211_WEP_KIDLEN \
6380 	 + IEEE80211_WEP_CRCLEN \
6381 	 + IEEE80211_WEP_MICLEN \
6382 	 + IEEE80211_CRC_LEN)
6383 
6384 /*
6385  * Setup initially for tdma operation.  Start the beacon
6386  * timers and enable SWBA if we are slot 0.  Otherwise
6387  * we wait for slot 0 to arrive so we can sync up before
6388  * starting to transmit.
6389  */
6390 static void
6391 ath_tdma_config(struct ath_softc *sc, struct ieee80211vap *vap)
6392 {
6393 	struct ath_hal *ah = sc->sc_ah;
6394 	struct ifnet *ifp = sc->sc_ifp;
6395 	struct ieee80211com *ic = ifp->if_l2com;
6396 	const struct ieee80211_txparam *tp;
6397 	const struct ieee80211_tdma_state *tdma = NULL;
6398 	int rix;
6399 
6400 	if (vap == NULL) {
6401 		vap = TAILQ_FIRST(&ic->ic_vaps);   /* XXX */
6402 		if (vap == NULL) {
6403 			if_printf(ifp, "%s: no vaps?\n", __func__);
6404 			return;
6405 		}
6406 	}
6407 	tp = vap->iv_bss->ni_txparms;
6408 	/*
6409 	 * Calculate the guard time for each slot.  This is the
6410 	 * time to send a maximal-size frame according to the
6411 	 * fixed/lowest transmit rate.  Note that the interface
6412 	 * mtu does not include the 802.11 overhead so we must
6413 	 * tack that on (ath_hal_computetxtime includes the
6414 	 * preamble and plcp in it's calculation).
6415 	 */
6416 	tdma = vap->iv_tdma;
6417 	if (tp->ucastrate != IEEE80211_FIXED_RATE_NONE)
6418 		rix = ath_tx_findrix(sc, tp->ucastrate);
6419 	else
6420 		rix = ath_tx_findrix(sc, tp->mcastrate);
6421 	/* XXX short preamble assumed */
6422 	sc->sc_tdmaguard = ath_hal_computetxtime(ah, sc->sc_currates,
6423 		ifp->if_mtu + IEEE80211_MAXOVERHEAD, rix, AH_TRUE);
6424 
6425 	ath_hal_intrset(ah, 0);
6426 
6427 	ath_beaconq_config(sc);			/* setup h/w beacon q */
6428 	if (sc->sc_setcca)
6429 		ath_hal_setcca(ah, AH_FALSE);	/* disable CCA */
6430 	ath_tdma_bintvalsetup(sc, tdma);	/* calculate beacon interval */
6431 	ath_tdma_settimers(sc, sc->sc_tdmabintval,
6432 		sc->sc_tdmabintval | HAL_BEACON_RESET_TSF);
6433 	sc->sc_syncbeacon = 0;
6434 
6435 	sc->sc_avgtsfdeltap = TDMA_DUMMY_MARKER;
6436 	sc->sc_avgtsfdeltam = TDMA_DUMMY_MARKER;
6437 
6438 	ath_hal_intrset(ah, sc->sc_imask);
6439 
6440 	DPRINTF(sc, ATH_DEBUG_TDMA, "%s: slot %u len %uus cnt %u "
6441 	    "bsched %u guard %uus bintval %u TU dba prep %u\n", __func__,
6442 	    tdma->tdma_slot, tdma->tdma_slotlen, tdma->tdma_slotcnt,
6443 	    tdma->tdma_bintval, sc->sc_tdmaguard, sc->sc_tdmabintval,
6444 	    sc->sc_tdmadbaprep);
6445 }
6446 
6447 /*
6448  * Update tdma operation.  Called from the 802.11 layer
6449  * when a beacon is received from the TDMA station operating
6450  * in the slot immediately preceding us in the bss.  Use
6451  * the rx timestamp for the beacon frame to update our
6452  * beacon timers so we follow their schedule.  Note that
6453  * by using the rx timestamp we implicitly include the
6454  * propagation delay in our schedule.
6455  */
6456 static void
6457 ath_tdma_update(struct ieee80211_node *ni,
6458 	const struct ieee80211_tdma_param *tdma, int changed)
6459 {
6460 #define	TSF_TO_TU(_h,_l) \
6461 	((((u_int32_t)(_h)) << 22) | (((u_int32_t)(_l)) >> 10))
6462 #define	TU_TO_TSF(_tu)	(((u_int64_t)(_tu)) << 10)
6463 	struct ieee80211vap *vap = ni->ni_vap;
6464 	struct ieee80211com *ic = ni->ni_ic;
6465 	struct ath_softc *sc = ic->ic_ifp->if_softc;
6466 	struct ath_hal *ah = sc->sc_ah;
6467 	const HAL_RATE_TABLE *rt = sc->sc_currates;
6468 	u_int64_t tsf, rstamp, nextslot, nexttbtt;
6469 	u_int32_t txtime, nextslottu;
6470 	int32_t tudelta, tsfdelta;
6471 	const struct ath_rx_status *rs;
6472 	int rix;
6473 
6474 	sc->sc_stats.ast_tdma_update++;
6475 
6476 	/*
6477 	 * Check for and adopt configuration changes.
6478 	 */
6479 	if (changed != 0) {
6480 		const struct ieee80211_tdma_state *ts = vap->iv_tdma;
6481 
6482 		ath_tdma_bintvalsetup(sc, ts);
6483 		if (changed & TDMA_UPDATE_SLOTLEN)
6484 			ath_wme_update(ic);
6485 
6486 		DPRINTF(sc, ATH_DEBUG_TDMA,
6487 		    "%s: adopt slot %u slotcnt %u slotlen %u us "
6488 		    "bintval %u TU\n", __func__,
6489 		    ts->tdma_slot, ts->tdma_slotcnt, ts->tdma_slotlen,
6490 		    sc->sc_tdmabintval);
6491 
6492 		/* XXX right? */
6493 		ath_hal_intrset(ah, sc->sc_imask);
6494 		/* NB: beacon timers programmed below */
6495 	}
6496 
6497 	/* extend rx timestamp to 64 bits */
6498 	rs = sc->sc_lastrs;
6499 	tsf = ath_hal_gettsf64(ah);
6500 	rstamp = ath_extend_tsf(sc, rs->rs_tstamp, tsf);
6501 	/*
6502 	 * The rx timestamp is set by the hardware on completing
6503 	 * reception (at the point where the rx descriptor is DMA'd
6504 	 * to the host).  To find the start of our next slot we
6505 	 * must adjust this time by the time required to send
6506 	 * the packet just received.
6507 	 */
6508 	rix = rt->rateCodeToIndex[rs->rs_rate];
6509 	txtime = ath_hal_computetxtime(ah, rt, rs->rs_datalen, rix,
6510 	    rt->info[rix].shortPreamble);
6511 	/* NB: << 9 is to cvt to TU and /2 */
6512 	nextslot = (rstamp - txtime) + (sc->sc_tdmabintval << 9);
6513 	nextslottu = TSF_TO_TU(nextslot>>32, nextslot) & HAL_BEACON_PERIOD;
6514 
6515 	/*
6516 	 * Retrieve the hardware NextTBTT in usecs
6517 	 * and calculate the difference between what the
6518 	 * other station thinks and what we have programmed.  This
6519 	 * lets us figure how to adjust our timers to match.  The
6520 	 * adjustments are done by pulling the TSF forward and possibly
6521 	 * rewriting the beacon timers.
6522 	 */
6523 	nexttbtt = ath_hal_getnexttbtt(ah);
6524 	tsfdelta = (int32_t)((nextslot % TU_TO_TSF(HAL_BEACON_PERIOD + 1)) - nexttbtt);
6525 
6526 	DPRINTF(sc, ATH_DEBUG_TDMA_TIMER,
6527 	    "tsfdelta %d avg +%d/-%d\n", tsfdelta,
6528 	    TDMA_AVG(sc->sc_avgtsfdeltap), TDMA_AVG(sc->sc_avgtsfdeltam));
6529 
6530 	if (tsfdelta < 0) {
6531 		TDMA_SAMPLE(sc->sc_avgtsfdeltap, 0);
6532 		TDMA_SAMPLE(sc->sc_avgtsfdeltam, -tsfdelta);
6533 		tsfdelta = -tsfdelta % 1024;
6534 		nextslottu++;
6535 	} else if (tsfdelta > 0) {
6536 		TDMA_SAMPLE(sc->sc_avgtsfdeltap, tsfdelta);
6537 		TDMA_SAMPLE(sc->sc_avgtsfdeltam, 0);
6538 		tsfdelta = 1024 - (tsfdelta % 1024);
6539 		nextslottu++;
6540 	} else {
6541 		TDMA_SAMPLE(sc->sc_avgtsfdeltap, 0);
6542 		TDMA_SAMPLE(sc->sc_avgtsfdeltam, 0);
6543 	}
6544 	tudelta = nextslottu - TSF_TO_TU(nexttbtt >> 32, nexttbtt);
6545 
6546 	/*
6547 	 * Copy sender's timetstamp into tdma ie so they can
6548 	 * calculate roundtrip time.  We submit a beacon frame
6549 	 * below after any timer adjustment.  The frame goes out
6550 	 * at the next TBTT so the sender can calculate the
6551 	 * roundtrip by inspecting the tdma ie in our beacon frame.
6552 	 *
6553 	 * NB: This tstamp is subtlely preserved when
6554 	 *     IEEE80211_BEACON_TDMA is marked (e.g. when the
6555 	 *     slot position changes) because ieee80211_add_tdma
6556 	 *     skips over the data.
6557 	 */
6558 	memcpy(ATH_VAP(vap)->av_boff.bo_tdma +
6559 		__offsetof(struct ieee80211_tdma_param, tdma_tstamp),
6560 		&ni->ni_tstamp.data, 8);
6561 #if 0
6562 	DPRINTF(sc, ATH_DEBUG_TDMA_TIMER,
6563 	    "tsf %llu nextslot %llu (%d, %d) nextslottu %u nexttbtt %llu (%d)\n",
6564 	    (unsigned long long) tsf, (unsigned long long) nextslot,
6565 	    (int)(nextslot - tsf), tsfdelta, nextslottu, nexttbtt, tudelta);
6566 #endif
6567 	/*
6568 	 * Adjust the beacon timers only when pulling them forward
6569 	 * or when going back by less than the beacon interval.
6570 	 * Negative jumps larger than the beacon interval seem to
6571 	 * cause the timers to stop and generally cause instability.
6572 	 * This basically filters out jumps due to missed beacons.
6573 	 */
6574 	if (tudelta != 0 && (tudelta > 0 || -tudelta < sc->sc_tdmabintval)) {
6575 		ath_tdma_settimers(sc, nextslottu, sc->sc_tdmabintval);
6576 		sc->sc_stats.ast_tdma_timers++;
6577 	}
6578 	if (tsfdelta > 0) {
6579 		ath_hal_adjusttsf(ah, tsfdelta);
6580 		sc->sc_stats.ast_tdma_tsf++;
6581 	}
6582 	ath_tdma_beacon_send(sc, vap);		/* prepare response */
6583 #undef TU_TO_TSF
6584 #undef TSF_TO_TU
6585 }
6586 
6587 /*
6588  * Transmit a beacon frame at SWBA.  Dynamic updates
6589  * to the frame contents are done as needed.
6590  */
6591 static void
6592 ath_tdma_beacon_send(struct ath_softc *sc, struct ieee80211vap *vap)
6593 {
6594 	struct ath_hal *ah = sc->sc_ah;
6595 	struct ath_buf *bf;
6596 	int otherant;
6597 
6598 	/*
6599 	 * Check if the previous beacon has gone out.  If
6600 	 * not don't try to post another, skip this period
6601 	 * and wait for the next.  Missed beacons indicate
6602 	 * a problem and should not occur.  If we miss too
6603 	 * many consecutive beacons reset the device.
6604 	 */
6605 	if (ath_hal_numtxpending(ah, sc->sc_bhalq) != 0) {
6606 		sc->sc_bmisscount++;
6607 		DPRINTF(sc, ATH_DEBUG_BEACON,
6608 			"%s: missed %u consecutive beacons\n",
6609 			__func__, sc->sc_bmisscount);
6610 		if (sc->sc_bmisscount >= ath_bstuck_threshold)
6611 			taskqueue_enqueue(sc->sc_tq, &sc->sc_bstucktask);
6612 		return;
6613 	}
6614 	if (sc->sc_bmisscount != 0) {
6615 		DPRINTF(sc, ATH_DEBUG_BEACON,
6616 			"%s: resume beacon xmit after %u misses\n",
6617 			__func__, sc->sc_bmisscount);
6618 		sc->sc_bmisscount = 0;
6619 	}
6620 
6621 	/*
6622 	 * Check recent per-antenna transmit statistics and flip
6623 	 * the default antenna if noticeably more frames went out
6624 	 * on the non-default antenna.
6625 	 * XXX assumes 2 anntenae
6626 	 */
6627 	if (!sc->sc_diversity) {
6628 		otherant = sc->sc_defant & 1 ? 2 : 1;
6629 		if (sc->sc_ant_tx[otherant] > sc->sc_ant_tx[sc->sc_defant] + 2)
6630 			ath_setdefantenna(sc, otherant);
6631 		sc->sc_ant_tx[1] = sc->sc_ant_tx[2] = 0;
6632 	}
6633 
6634 	bf = ath_beacon_generate(sc, vap);
6635 	if (bf != NULL) {
6636 		/*
6637 		 * Stop any current dma and put the new frame on the queue.
6638 		 * This should never fail since we check above that no frames
6639 		 * are still pending on the queue.
6640 		 */
6641 		if (!ath_hal_stoptxdma(ah, sc->sc_bhalq)) {
6642 			DPRINTF(sc, ATH_DEBUG_ANY,
6643 				"%s: beacon queue %u did not stop?\n",
6644 				__func__, sc->sc_bhalq);
6645 			/* NB: the HAL still stops DMA, so proceed */
6646 		}
6647 		ath_hal_puttxbuf(ah, sc->sc_bhalq, bf->bf_daddr);
6648 		ath_hal_txstart(ah, sc->sc_bhalq);
6649 
6650 		sc->sc_stats.ast_be_xmit++;		/* XXX per-vap? */
6651 
6652 		/*
6653 		 * Record local TSF for our last send for use
6654 		 * in arbitrating slot collisions.
6655 		 */
6656 		vap->iv_bss->ni_tstamp.tsf = ath_hal_gettsf64(ah);
6657 	}
6658 }
6659 #endif /* IEEE80211_SUPPORT_TDMA */
6660 
6661 static void
6662 ath_dfs_tasklet(void *p, int npending)
6663 {
6664 	struct ath_softc *sc = (struct ath_softc *) p;
6665 	struct ifnet *ifp = sc->sc_ifp;
6666 	struct ieee80211com *ic = ifp->if_l2com;
6667 
6668 	/*
6669 	 * If previous processing has found a radar event,
6670 	 * signal this to the net80211 layer to begin DFS
6671 	 * processing.
6672 	 */
6673 	if (ath_dfs_process_radar_event(sc, sc->sc_curchan)) {
6674 		/* DFS event found, initiate channel change */
6675 		ieee80211_dfs_notify_radar(ic, sc->sc_curchan);
6676 	}
6677 }
6678 
6679 MODULE_VERSION(if_ath, 1);
6680 MODULE_DEPEND(if_ath, wlan, 1, 1, 1);          /* 802.11 media layer */
6681