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