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