xref: /freebsd/sys/dev/ath/if_ath.c (revision 99f3b482da15db6f2ae4702d592b53dd36d4cf55)
1 /*-
2  * Copyright (c) 2002-2006 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  * 3. Neither the names of the above-listed copyright holders nor the names
16  *    of any contributors may be used to endorse or promote products derived
17  *    from this software without specific prior written permission.
18  *
19  * Alternatively, this software may be distributed under the terms of the
20  * GNU General Public License ("GPL") version 2 as published by the Free
21  * Software Foundation.
22  *
23  * NO WARRANTY
24  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
25  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
26  * LIMITED TO, THE IMPLIED WARRANTIES OF NONINFRINGEMENT, MERCHANTIBILITY
27  * AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
28  * THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR SPECIAL, EXEMPLARY,
29  * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
30  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
31  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER
32  * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
33  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
34  * THE POSSIBILITY OF SUCH DAMAGES.
35  */
36 
37 #include <sys/cdefs.h>
38 __FBSDID("$FreeBSD$");
39 
40 /*
41  * Driver for the Atheros Wireless LAN controller.
42  *
43  * This software is derived from work of Atsushi Onoe; his contribution
44  * is greatly appreciated.
45  */
46 
47 #include "opt_inet.h"
48 #include "opt_ath.h"
49 
50 #include <sys/param.h>
51 #include <sys/systm.h>
52 #include <sys/sysctl.h>
53 #include <sys/mbuf.h>
54 #include <sys/malloc.h>
55 #include <sys/lock.h>
56 #include <sys/mutex.h>
57 #include <sys/kernel.h>
58 #include <sys/socket.h>
59 #include <sys/sockio.h>
60 #include <sys/errno.h>
61 #include <sys/callout.h>
62 #include <sys/bus.h>
63 #include <sys/endian.h>
64 #include <sys/kthread.h>
65 #include <sys/taskqueue.h>
66 
67 #include <machine/bus.h>
68 
69 #include <net/if.h>
70 #include <net/if_dl.h>
71 #include <net/if_media.h>
72 #include <net/if_types.h>
73 #include <net/if_arp.h>
74 #include <net/ethernet.h>
75 #include <net/if_llc.h>
76 
77 #include <net80211/ieee80211_var.h>
78 
79 #include <net/bpf.h>
80 
81 #ifdef INET
82 #include <netinet/in.h>
83 #include <netinet/if_ether.h>
84 #endif
85 
86 #include <dev/ath/if_athvar.h>
87 #include <contrib/dev/ath/ah_desc.h>
88 #include <contrib/dev/ath/ah_devid.h>		/* XXX for softled */
89 
90 #ifdef ATH_TX99_DIAG
91 #include <dev/ath/ath_tx99/ath_tx99.h>
92 #endif
93 
94 /* unaligned little endian access */
95 #define LE_READ_2(p)							\
96 	((u_int16_t)							\
97 	 ((((u_int8_t *)(p))[0]      ) | (((u_int8_t *)(p))[1] <<  8)))
98 #define LE_READ_4(p)							\
99 	((u_int32_t)							\
100 	 ((((u_int8_t *)(p))[0]      ) | (((u_int8_t *)(p))[1] <<  8) |	\
101 	  (((u_int8_t *)(p))[2] << 16) | (((u_int8_t *)(p))[3] << 24)))
102 
103 enum {
104 	ATH_LED_TX,
105 	ATH_LED_RX,
106 	ATH_LED_POLL,
107 };
108 
109 static void	ath_init(void *);
110 static void	ath_stop_locked(struct ifnet *);
111 static void	ath_stop(struct ifnet *);
112 static void	ath_start(struct ifnet *);
113 static int	ath_reset(struct ifnet *);
114 static int	ath_media_change(struct ifnet *);
115 static void	ath_watchdog(struct ifnet *);
116 static int	ath_ioctl(struct ifnet *, u_long, caddr_t);
117 static void	ath_fatal_proc(void *, int);
118 static void	ath_rxorn_proc(void *, int);
119 static void	ath_bmiss_proc(void *, int);
120 static void	ath_radar_proc(void *, int);
121 static int	ath_key_alloc(struct ieee80211com *,
122 			const struct ieee80211_key *,
123 			ieee80211_keyix *, ieee80211_keyix *);
124 static int	ath_key_delete(struct ieee80211com *,
125 			const struct ieee80211_key *);
126 static int	ath_key_set(struct ieee80211com *, const struct ieee80211_key *,
127 			const u_int8_t mac[IEEE80211_ADDR_LEN]);
128 static void	ath_key_update_begin(struct ieee80211com *);
129 static void	ath_key_update_end(struct ieee80211com *);
130 static void	ath_mode_init(struct ath_softc *);
131 static void	ath_setslottime(struct ath_softc *);
132 static void	ath_updateslot(struct ifnet *);
133 static int	ath_beaconq_setup(struct ath_hal *);
134 static int	ath_beacon_alloc(struct ath_softc *, struct ieee80211_node *);
135 static void	ath_beacon_setup(struct ath_softc *, struct ath_buf *);
136 static void	ath_beacon_proc(void *, int);
137 static void	ath_bstuck_proc(void *, int);
138 static void	ath_beacon_free(struct ath_softc *);
139 static void	ath_beacon_config(struct ath_softc *);
140 static void	ath_descdma_cleanup(struct ath_softc *sc,
141 			struct ath_descdma *, ath_bufhead *);
142 static int	ath_desc_alloc(struct ath_softc *);
143 static void	ath_desc_free(struct ath_softc *);
144 static struct ieee80211_node *ath_node_alloc(struct ieee80211_node_table *);
145 static void	ath_node_free(struct ieee80211_node *);
146 static u_int8_t	ath_node_getrssi(const struct ieee80211_node *);
147 static int	ath_rxbuf_init(struct ath_softc *, struct ath_buf *);
148 static void	ath_recv_mgmt(struct ieee80211com *ic, struct mbuf *m,
149 			struct ieee80211_node *ni,
150 			int subtype, int rssi, u_int32_t rstamp);
151 static void	ath_setdefantenna(struct ath_softc *, u_int);
152 static void	ath_rx_proc(void *, int);
153 static void	ath_txq_init(struct ath_softc *sc, struct ath_txq *, int);
154 static struct ath_txq *ath_txq_setup(struct ath_softc*, int qtype, int subtype);
155 static int	ath_tx_setup(struct ath_softc *, int, int);
156 static int	ath_wme_update(struct ieee80211com *);
157 static void	ath_tx_cleanupq(struct ath_softc *, struct ath_txq *);
158 static void	ath_tx_cleanup(struct ath_softc *);
159 static int	ath_tx_start(struct ath_softc *, struct ieee80211_node *,
160 			     struct ath_buf *, struct mbuf *);
161 static void	ath_tx_proc_q0(void *, int);
162 static void	ath_tx_proc_q0123(void *, int);
163 static void	ath_tx_proc(void *, int);
164 static int	ath_chan_set(struct ath_softc *, struct ieee80211_channel *);
165 static void	ath_draintxq(struct ath_softc *);
166 static void	ath_stoprecv(struct ath_softc *);
167 static int	ath_startrecv(struct ath_softc *);
168 static void	ath_chan_change(struct ath_softc *, struct ieee80211_channel *);
169 static void	ath_next_scan(void *);
170 static void	ath_calibrate(void *);
171 static int	ath_newstate(struct ieee80211com *, enum ieee80211_state, int);
172 static void	ath_setup_stationkey(struct ieee80211_node *);
173 static void	ath_newassoc(struct ieee80211_node *, int);
174 static int	ath_getchannels(struct ath_softc *, u_int cc,
175 			HAL_BOOL outdoor, HAL_BOOL xchanmode);
176 static void	ath_led_event(struct ath_softc *, int);
177 static void	ath_update_txpow(struct ath_softc *);
178 
179 static int	ath_rate_setup(struct ath_softc *, u_int mode);
180 static void	ath_setcurmode(struct ath_softc *, enum ieee80211_phymode);
181 
182 static void	ath_sysctlattach(struct ath_softc *);
183 static int	ath_raw_xmit(struct ieee80211_node *,
184 			struct mbuf *, const struct ieee80211_bpf_params *);
185 static void	ath_bpfattach(struct ath_softc *);
186 static void	ath_announce(struct ath_softc *);
187 
188 SYSCTL_DECL(_hw_ath);
189 
190 /* XXX validate sysctl values */
191 static	int ath_dwelltime = 200;		/* 5 channels/second */
192 SYSCTL_INT(_hw_ath, OID_AUTO, dwell, CTLFLAG_RW, &ath_dwelltime,
193 	    0, "channel dwell time (ms) for AP/station scanning");
194 static	int ath_calinterval = 30;		/* calibrate every 30 secs */
195 SYSCTL_INT(_hw_ath, OID_AUTO, calibrate, CTLFLAG_RW, &ath_calinterval,
196 	    0, "chip calibration interval (secs)");
197 static	int ath_outdoor = AH_TRUE;		/* outdoor operation */
198 SYSCTL_INT(_hw_ath, OID_AUTO, outdoor, CTLFLAG_RD, &ath_outdoor,
199 	    0, "outdoor operation");
200 TUNABLE_INT("hw.ath.outdoor", &ath_outdoor);
201 static	int ath_xchanmode = AH_TRUE;		/* extended channel use */
202 SYSCTL_INT(_hw_ath, OID_AUTO, xchanmode, CTLFLAG_RD, &ath_xchanmode,
203 	    0, "extended channel mode");
204 TUNABLE_INT("hw.ath.xchanmode", &ath_xchanmode);
205 static	int ath_countrycode = CTRY_DEFAULT;	/* country code */
206 SYSCTL_INT(_hw_ath, OID_AUTO, countrycode, CTLFLAG_RD, &ath_countrycode,
207 	    0, "country code");
208 TUNABLE_INT("hw.ath.countrycode", &ath_countrycode);
209 static	int ath_regdomain = 0;			/* regulatory domain */
210 SYSCTL_INT(_hw_ath, OID_AUTO, regdomain, CTLFLAG_RD, &ath_regdomain,
211 	    0, "regulatory domain");
212 
213 static	int ath_rxbuf = ATH_RXBUF;		/* # rx buffers to allocate */
214 SYSCTL_INT(_hw_ath, OID_AUTO, rxbuf, CTLFLAG_RD, &ath_rxbuf,
215 	    0, "rx buffers allocated");
216 TUNABLE_INT("hw.ath.rxbuf", &ath_rxbuf);
217 static	int ath_txbuf = ATH_TXBUF;		/* # tx buffers to allocate */
218 SYSCTL_INT(_hw_ath, OID_AUTO, txbuf, CTLFLAG_RD, &ath_txbuf,
219 	    0, "tx buffers allocated");
220 TUNABLE_INT("hw.ath.txbuf", &ath_txbuf);
221 
222 #ifdef ATH_DEBUG
223 static	int ath_debug = 0;
224 SYSCTL_INT(_hw_ath, OID_AUTO, debug, CTLFLAG_RW, &ath_debug,
225 	    0, "control debugging printfs");
226 TUNABLE_INT("hw.ath.debug", &ath_debug);
227 enum {
228 	ATH_DEBUG_XMIT		= 0x00000001,	/* basic xmit operation */
229 	ATH_DEBUG_XMIT_DESC	= 0x00000002,	/* xmit descriptors */
230 	ATH_DEBUG_RECV		= 0x00000004,	/* basic recv operation */
231 	ATH_DEBUG_RECV_DESC	= 0x00000008,	/* recv descriptors */
232 	ATH_DEBUG_RATE		= 0x00000010,	/* rate control */
233 	ATH_DEBUG_RESET		= 0x00000020,	/* reset processing */
234 	ATH_DEBUG_MODE		= 0x00000040,	/* mode init/setup */
235 	ATH_DEBUG_BEACON 	= 0x00000080,	/* beacon handling */
236 	ATH_DEBUG_WATCHDOG 	= 0x00000100,	/* watchdog timeout */
237 	ATH_DEBUG_INTR		= 0x00001000,	/* ISR */
238 	ATH_DEBUG_TX_PROC	= 0x00002000,	/* tx ISR proc */
239 	ATH_DEBUG_RX_PROC	= 0x00004000,	/* rx ISR proc */
240 	ATH_DEBUG_BEACON_PROC	= 0x00008000,	/* beacon ISR proc */
241 	ATH_DEBUG_CALIBRATE	= 0x00010000,	/* periodic calibration */
242 	ATH_DEBUG_KEYCACHE	= 0x00020000,	/* key cache management */
243 	ATH_DEBUG_STATE		= 0x00040000,	/* 802.11 state transitions */
244 	ATH_DEBUG_NODE		= 0x00080000,	/* node management */
245 	ATH_DEBUG_LED		= 0x00100000,	/* led management */
246 	ATH_DEBUG_FF		= 0x00200000,	/* fast frames */
247 	ATH_DEBUG_DFS		= 0x00400000,	/* DFS processing */
248 	ATH_DEBUG_FATAL		= 0x80000000,	/* fatal errors */
249 	ATH_DEBUG_ANY		= 0xffffffff
250 };
251 #define	IFF_DUMPPKTS(sc, m) \
252 	((sc->sc_debug & (m)) || \
253 	    (sc->sc_ifp->if_flags & (IFF_DEBUG|IFF_LINK2)) == (IFF_DEBUG|IFF_LINK2))
254 #define	DPRINTF(sc, m, fmt, ...) do {				\
255 	if (sc->sc_debug & (m))					\
256 		printf(fmt, __VA_ARGS__);			\
257 } while (0)
258 #define	KEYPRINTF(sc, ix, hk, mac) do {				\
259 	if (sc->sc_debug & ATH_DEBUG_KEYCACHE)			\
260 		ath_keyprint(__func__, ix, hk, mac);		\
261 } while (0)
262 static	void ath_printrxbuf(struct ath_buf *bf, u_int ix, int);
263 static	void ath_printtxbuf(struct ath_buf *bf, u_int qnum, u_int ix, int done);
264 #else
265 #define	IFF_DUMPPKTS(sc, m) \
266 	((sc->sc_ifp->if_flags & (IFF_DEBUG|IFF_LINK2)) == (IFF_DEBUG|IFF_LINK2))
267 #define	DPRINTF(sc, m, fmt, ...) do {				\
268 	(void) sc;						\
269 } while (0)
270 #define	KEYPRINTF(sc, k, ix, mac) do {				\
271 	(void) sc;						\
272 } while (0)
273 #endif
274 
275 MALLOC_DEFINE(M_ATHDEV, "athdev", "ath driver dma buffers");
276 
277 int
278 ath_attach(u_int16_t devid, struct ath_softc *sc)
279 {
280 	struct ifnet *ifp;
281 	struct ieee80211com *ic = &sc->sc_ic;
282 	struct ath_hal *ah = NULL;
283 	HAL_STATUS status;
284 	int error = 0, i;
285 
286 	DPRINTF(sc, ATH_DEBUG_ANY, "%s: devid 0x%x\n", __func__, devid);
287 
288 	ifp = sc->sc_ifp = if_alloc(IFT_ETHER);
289 	if (ifp == NULL) {
290 		device_printf(sc->sc_dev, "can not if_alloc()\n");
291 		error = ENOSPC;
292 		goto bad;
293 	}
294 
295 	/* set these up early for if_printf use */
296 	if_initname(ifp, device_get_name(sc->sc_dev),
297 		device_get_unit(sc->sc_dev));
298 
299 	ah = ath_hal_attach(devid, sc, sc->sc_st, sc->sc_sh, &status);
300 	if (ah == NULL) {
301 		if_printf(ifp, "unable to attach hardware; HAL status %u\n",
302 			status);
303 		error = ENXIO;
304 		goto bad;
305 	}
306 	if (ah->ah_abi != HAL_ABI_VERSION) {
307 		if_printf(ifp, "HAL ABI mismatch detected "
308 			"(HAL:0x%x != driver:0x%x)\n",
309 			ah->ah_abi, HAL_ABI_VERSION);
310 		error = ENXIO;
311 		goto bad;
312 	}
313 	sc->sc_ah = ah;
314 	sc->sc_invalid = 0;	/* ready to go, enable interrupt handling */
315 
316 	/*
317 	 * Check if the MAC has multi-rate retry support.
318 	 * We do this by trying to setup a fake extended
319 	 * descriptor.  MAC's that don't have support will
320 	 * return false w/o doing anything.  MAC's that do
321 	 * support it will return true w/o doing anything.
322 	 */
323 	sc->sc_mrretry = ath_hal_setupxtxdesc(ah, NULL, 0,0, 0,0, 0,0);
324 
325 	/*
326 	 * Check if the device has hardware counters for PHY
327 	 * errors.  If so we need to enable the MIB interrupt
328 	 * so we can act on stat triggers.
329 	 */
330 	if (ath_hal_hwphycounters(ah))
331 		sc->sc_needmib = 1;
332 
333 	/*
334 	 * Get the hardware key cache size.
335 	 */
336 	sc->sc_keymax = ath_hal_keycachesize(ah);
337 	if (sc->sc_keymax > ATH_KEYMAX) {
338 		if_printf(ifp, "Warning, using only %u of %u key cache slots\n",
339 			ATH_KEYMAX, sc->sc_keymax);
340 		sc->sc_keymax = ATH_KEYMAX;
341 	}
342 	/*
343 	 * Reset the key cache since some parts do not
344 	 * reset the contents on initial power up.
345 	 */
346 	for (i = 0; i < sc->sc_keymax; i++)
347 		ath_hal_keyreset(ah, i);
348 	/*
349 	 * Mark key cache slots associated with global keys
350 	 * as in use.  If we knew TKIP was not to be used we
351 	 * could leave the +32, +64, and +32+64 slots free.
352 	 * XXX only for splitmic.
353 	 */
354 	for (i = 0; i < IEEE80211_WEP_NKID; i++) {
355 		setbit(sc->sc_keymap, i);
356 		setbit(sc->sc_keymap, i+32);
357 		setbit(sc->sc_keymap, i+64);
358 		setbit(sc->sc_keymap, i+32+64);
359 	}
360 
361 	/*
362 	 * Collect the channel list using the default country
363 	 * code and including outdoor channels.  The 802.11 layer
364 	 * is resposible for filtering this list based on settings
365 	 * like the phy mode.
366 	 */
367 	error = ath_getchannels(sc, ath_countrycode,
368 			ath_outdoor, ath_xchanmode);
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 	/* NB: setup here so ath_rate_update is happy */
381 	ath_setcurmode(sc, IEEE80211_MODE_11A);
382 
383 	/*
384 	 * Allocate tx+rx descriptors and populate the lists.
385 	 */
386 	error = ath_desc_alloc(sc);
387 	if (error != 0) {
388 		if_printf(ifp, "failed to allocate descriptors: %d\n", error);
389 		goto bad;
390 	}
391 	callout_init(&sc->sc_scan_ch, debug_mpsafenet ? CALLOUT_MPSAFE : 0);
392 	callout_init(&sc->sc_cal_ch, CALLOUT_MPSAFE);
393 	callout_init(&sc->sc_dfs_ch, CALLOUT_MPSAFE);
394 
395 	ATH_TXBUF_LOCK_INIT(sc);
396 
397 	sc->sc_tq = taskqueue_create("ath_taskq", M_NOWAIT,
398 		taskqueue_thread_enqueue, &sc->sc_tq);
399 	taskqueue_start_threads(&sc->sc_tq, 1, PI_NET,
400 		"%s taskq", ifp->if_xname);
401 
402 	TASK_INIT(&sc->sc_rxtask, 0, ath_rx_proc, sc);
403 	TASK_INIT(&sc->sc_rxorntask, 0, ath_rxorn_proc, sc);
404 	TASK_INIT(&sc->sc_bmisstask, 0, ath_bmiss_proc, sc);
405 	TASK_INIT(&sc->sc_bstucktask,0, ath_bstuck_proc, sc);
406 	TASK_INIT(&sc->sc_radartask, 0, ath_radar_proc, sc);
407 
408 	/*
409 	 * Allocate hardware transmit queues: one queue for
410 	 * beacon frames and one data queue for each QoS
411 	 * priority.  Note that the hal handles reseting
412 	 * these queues at the needed time.
413 	 *
414 	 * XXX PS-Poll
415 	 */
416 	sc->sc_bhalq = ath_beaconq_setup(ah);
417 	if (sc->sc_bhalq == (u_int) -1) {
418 		if_printf(ifp, "unable to setup a beacon xmit queue!\n");
419 		error = EIO;
420 		goto bad2;
421 	}
422 	sc->sc_cabq = ath_txq_setup(sc, HAL_TX_QUEUE_CAB, 0);
423 	if (sc->sc_cabq == NULL) {
424 		if_printf(ifp, "unable to setup CAB xmit queue!\n");
425 		error = EIO;
426 		goto bad2;
427 	}
428 	ath_txq_init(sc, &sc->sc_mcastq, -1);	/* NB: s/w q, qnum not used */
429 	/* NB: insure BK queue is the lowest priority h/w queue */
430 	if (!ath_tx_setup(sc, WME_AC_BK, HAL_WME_AC_BK)) {
431 		if_printf(ifp, "unable to setup xmit queue for %s traffic!\n",
432 			ieee80211_wme_acnames[WME_AC_BK]);
433 		error = EIO;
434 		goto bad2;
435 	}
436 	if (!ath_tx_setup(sc, WME_AC_BE, HAL_WME_AC_BE) ||
437 	    !ath_tx_setup(sc, WME_AC_VI, HAL_WME_AC_VI) ||
438 	    !ath_tx_setup(sc, WME_AC_VO, HAL_WME_AC_VO)) {
439 		/*
440 		 * Not enough hardware tx queues to properly do WME;
441 		 * just punt and assign them all to the same h/w queue.
442 		 * We could do a better job of this if, for example,
443 		 * we allocate queues when we switch from station to
444 		 * AP mode.
445 		 */
446 		if (sc->sc_ac2q[WME_AC_VI] != NULL)
447 			ath_tx_cleanupq(sc, sc->sc_ac2q[WME_AC_VI]);
448 		if (sc->sc_ac2q[WME_AC_BE] != NULL)
449 			ath_tx_cleanupq(sc, sc->sc_ac2q[WME_AC_BE]);
450 		sc->sc_ac2q[WME_AC_BE] = sc->sc_ac2q[WME_AC_BK];
451 		sc->sc_ac2q[WME_AC_VI] = sc->sc_ac2q[WME_AC_BK];
452 		sc->sc_ac2q[WME_AC_VO] = sc->sc_ac2q[WME_AC_BK];
453 	}
454 
455 	/*
456 	 * Special case certain configurations.  Note the
457 	 * CAB queue is handled by these specially so don't
458 	 * include them when checking the txq setup mask.
459 	 */
460 	switch (sc->sc_txqsetup &~ (1<<sc->sc_cabq->axq_qnum)) {
461 	case 0x01:
462 		TASK_INIT(&sc->sc_txtask, 0, ath_tx_proc_q0, sc);
463 		break;
464 	case 0x0f:
465 		TASK_INIT(&sc->sc_txtask, 0, ath_tx_proc_q0123, sc);
466 		break;
467 	default:
468 		TASK_INIT(&sc->sc_txtask, 0, ath_tx_proc, sc);
469 		break;
470 	}
471 
472 	/*
473 	 * Setup rate control.  Some rate control modules
474 	 * call back to change the anntena state so expose
475 	 * the necessary entry points.
476 	 * XXX maybe belongs in struct ath_ratectrl?
477 	 */
478 	sc->sc_setdefantenna = ath_setdefantenna;
479 	sc->sc_rc = ath_rate_attach(sc);
480 	if (sc->sc_rc == NULL) {
481 		error = EIO;
482 		goto bad2;
483 	}
484 
485 	sc->sc_blinking = 0;
486 	sc->sc_ledstate = 1;
487 	sc->sc_ledon = 0;			/* low true */
488 	sc->sc_ledidle = (2700*hz)/1000;	/* 2.7sec */
489 	callout_init(&sc->sc_ledtimer, CALLOUT_MPSAFE);
490 	/*
491 	 * Auto-enable soft led processing for IBM cards and for
492 	 * 5211 minipci cards.  Users can also manually enable/disable
493 	 * support with a sysctl.
494 	 */
495 	sc->sc_softled = (devid == AR5212_DEVID_IBM || devid == AR5211_DEVID);
496 	if (sc->sc_softled) {
497 		ath_hal_gpioCfgOutput(ah, sc->sc_ledpin);
498 		ath_hal_gpioset(ah, sc->sc_ledpin, !sc->sc_ledon);
499 	}
500 
501 	ifp->if_softc = sc;
502 	ifp->if_flags = IFF_SIMPLEX | IFF_BROADCAST | IFF_MULTICAST;
503 	ifp->if_start = ath_start;
504 	ifp->if_watchdog = ath_watchdog;
505 	ifp->if_ioctl = ath_ioctl;
506 	ifp->if_init = ath_init;
507 	IFQ_SET_MAXLEN(&ifp->if_snd, IFQ_MAXLEN);
508 	ifp->if_snd.ifq_drv_maxlen = IFQ_MAXLEN;
509 	IFQ_SET_READY(&ifp->if_snd);
510 
511 	ic->ic_ifp = ifp;
512 	ic->ic_reset = ath_reset;
513 	ic->ic_newassoc = ath_newassoc;
514 	ic->ic_updateslot = ath_updateslot;
515 	ic->ic_wme.wme_update = ath_wme_update;
516 	/* XXX not right but it's not used anywhere important */
517 	ic->ic_phytype = IEEE80211_T_OFDM;
518 	ic->ic_opmode = IEEE80211_M_STA;
519 	ic->ic_caps =
520 		  IEEE80211_C_IBSS		/* ibss, nee adhoc, mode */
521 		| IEEE80211_C_HOSTAP		/* hostap mode */
522 		| IEEE80211_C_MONITOR		/* monitor mode */
523 		| IEEE80211_C_AHDEMO		/* adhoc demo mode */
524 		| IEEE80211_C_SHPREAMBLE	/* short preamble supported */
525 		| IEEE80211_C_SHSLOT		/* short slot time supported */
526 		| IEEE80211_C_WPA		/* capable of WPA1+WPA2 */
527 		;
528 	/*
529 	 * Query the hal to figure out h/w crypto support.
530 	 */
531 	if (ath_hal_ciphersupported(ah, HAL_CIPHER_WEP))
532 		ic->ic_caps |= IEEE80211_C_WEP;
533 	if (ath_hal_ciphersupported(ah, HAL_CIPHER_AES_OCB))
534 		ic->ic_caps |= IEEE80211_C_AES;
535 	if (ath_hal_ciphersupported(ah, HAL_CIPHER_AES_CCM))
536 		ic->ic_caps |= IEEE80211_C_AES_CCM;
537 	if (ath_hal_ciphersupported(ah, HAL_CIPHER_CKIP))
538 		ic->ic_caps |= IEEE80211_C_CKIP;
539 	if (ath_hal_ciphersupported(ah, HAL_CIPHER_TKIP)) {
540 		ic->ic_caps |= IEEE80211_C_TKIP;
541 		/*
542 		 * Check if h/w does the MIC and/or whether the
543 		 * separate key cache entries are required to
544 		 * handle both tx+rx MIC keys.
545 		 */
546 		if (ath_hal_ciphersupported(ah, HAL_CIPHER_MIC))
547 			ic->ic_caps |= IEEE80211_C_TKIPMIC;
548 		if (ath_hal_tkipsplit(ah))
549 			sc->sc_splitmic = 1;
550 	}
551 	sc->sc_hasclrkey = ath_hal_ciphersupported(ah, HAL_CIPHER_CLR);
552 	sc->sc_mcastkey = ath_hal_getmcastkeysearch(ah);
553 	/*
554 	 * TPC support can be done either with a global cap or
555 	 * per-packet support.  The latter is not available on
556 	 * all parts.  We're a bit pedantic here as all parts
557 	 * support a global cap.
558 	 */
559 	if (ath_hal_hastpc(ah) || ath_hal_hastxpowlimit(ah))
560 		ic->ic_caps |= IEEE80211_C_TXPMGT;
561 
562 	/*
563 	 * Mark WME capability only if we have sufficient
564 	 * hardware queues to do proper priority scheduling.
565 	 */
566 	if (sc->sc_ac2q[WME_AC_BE] != sc->sc_ac2q[WME_AC_BK])
567 		ic->ic_caps |= IEEE80211_C_WME;
568 	/*
569 	 * Check for misc other capabilities.
570 	 */
571 	if (ath_hal_hasbursting(ah))
572 		ic->ic_caps |= IEEE80211_C_BURST;
573 
574 	/*
575 	 * Indicate we need the 802.11 header padded to a
576 	 * 32-bit boundary for 4-address and QoS frames.
577 	 */
578 	ic->ic_flags |= IEEE80211_F_DATAPAD;
579 
580 	/*
581 	 * Query the hal about antenna support.
582 	 */
583 	sc->sc_defant = ath_hal_getdefantenna(ah);
584 
585 	/*
586 	 * Not all chips have the VEOL support we want to
587 	 * use with IBSS beacons; check here for it.
588 	 */
589 	sc->sc_hasveol = ath_hal_hasveol(ah);
590 
591 	/* get mac address from hardware */
592 	ath_hal_getmac(ah, ic->ic_myaddr);
593 
594 	/* call MI attach routine. */
595 	ieee80211_ifattach(ic);
596 	sc->sc_opmode = ic->ic_opmode;
597 	/* override default methods */
598 	ic->ic_node_alloc = ath_node_alloc;
599 	sc->sc_node_free = ic->ic_node_free;
600 	ic->ic_node_free = ath_node_free;
601 	ic->ic_node_getrssi = ath_node_getrssi;
602 	sc->sc_recv_mgmt = ic->ic_recv_mgmt;
603 	ic->ic_recv_mgmt = ath_recv_mgmt;
604 	sc->sc_newstate = ic->ic_newstate;
605 	ic->ic_newstate = ath_newstate;
606 	ic->ic_crypto.cs_max_keyix = sc->sc_keymax;
607 	ic->ic_crypto.cs_key_alloc = ath_key_alloc;
608 	ic->ic_crypto.cs_key_delete = ath_key_delete;
609 	ic->ic_crypto.cs_key_set = ath_key_set;
610 	ic->ic_crypto.cs_key_update_begin = ath_key_update_begin;
611 	ic->ic_crypto.cs_key_update_end = ath_key_update_end;
612 	ic->ic_raw_xmit = ath_raw_xmit;
613 	/* complete initialization */
614 	ieee80211_media_init(ic, ath_media_change, ieee80211_media_status);
615 
616 	ath_bpfattach(sc);
617 	/*
618 	 * Setup dynamic sysctl's now that country code and
619 	 * regdomain are available from the hal.
620 	 */
621 	ath_sysctlattach(sc);
622 
623 	if (bootverbose)
624 		ieee80211_announce(ic);
625 	ath_announce(sc);
626 	return 0;
627 bad2:
628 	ath_tx_cleanup(sc);
629 	ath_desc_free(sc);
630 bad:
631 	if (ah)
632 		ath_hal_detach(ah);
633 	if (ifp != NULL)
634 		if_free(ifp);
635 	sc->sc_invalid = 1;
636 	return error;
637 }
638 
639 int
640 ath_detach(struct ath_softc *sc)
641 {
642 	struct ifnet *ifp = sc->sc_ifp;
643 
644 	DPRINTF(sc, ATH_DEBUG_ANY, "%s: if_flags %x\n",
645 		__func__, ifp->if_flags);
646 
647 	ath_stop(ifp);
648 	bpfdetach(ifp);
649 	/*
650 	 * NB: the order of these is important:
651 	 * o call the 802.11 layer before detaching the hal to
652 	 *   insure callbacks into the driver to delete global
653 	 *   key cache entries can be handled
654 	 * o reclaim the tx queue data structures after calling
655 	 *   the 802.11 layer as we'll get called back to reclaim
656 	 *   node state and potentially want to use them
657 	 * o to cleanup the tx queues the hal is called, so detach
658 	 *   it last
659 	 * Other than that, it's straightforward...
660 	 */
661 	ieee80211_ifdetach(&sc->sc_ic);
662 #ifdef ATH_TX99_DIAG
663 	if (sc->sc_tx99 != NULL)
664 		sc->sc_tx99->detach(sc->sc_tx99);
665 #endif
666 	taskqueue_free(sc->sc_tq);
667 	ath_rate_detach(sc->sc_rc);
668 	ath_desc_free(sc);
669 	ath_tx_cleanup(sc);
670 	ath_hal_detach(sc->sc_ah);
671 	if_free(ifp);
672 
673 	return 0;
674 }
675 
676 void
677 ath_suspend(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 }
686 
687 void
688 ath_resume(struct ath_softc *sc)
689 {
690 	struct ifnet *ifp = sc->sc_ifp;
691 
692 	DPRINTF(sc, ATH_DEBUG_ANY, "%s: if_flags %x\n",
693 		__func__, ifp->if_flags);
694 
695 	if (ifp->if_flags & IFF_UP) {
696 		ath_init(sc);
697 		if (ifp->if_drv_flags & IFF_DRV_RUNNING)
698 			ath_start(ifp);
699 	}
700 	if (sc->sc_softled) {
701 		ath_hal_gpioCfgOutput(sc->sc_ah, sc->sc_ledpin);
702 		ath_hal_gpioset(sc->sc_ah, sc->sc_ledpin, !sc->sc_ledon);
703 	}
704 }
705 
706 void
707 ath_shutdown(struct ath_softc *sc)
708 {
709 	struct ifnet *ifp = sc->sc_ifp;
710 
711 	DPRINTF(sc, ATH_DEBUG_ANY, "%s: if_flags %x\n",
712 		__func__, ifp->if_flags);
713 
714 	ath_stop(ifp);
715 }
716 
717 /*
718  * Interrupt handler.  Most of the actual processing is deferred.
719  */
720 void
721 ath_intr(void *arg)
722 {
723 	struct ath_softc *sc = arg;
724 	struct ifnet *ifp = sc->sc_ifp;
725 	struct ath_hal *ah = sc->sc_ah;
726 	HAL_INT status;
727 
728 	if (sc->sc_invalid) {
729 		/*
730 		 * The hardware is not ready/present, don't touch anything.
731 		 * Note this can happen early on if the IRQ is shared.
732 		 */
733 		DPRINTF(sc, ATH_DEBUG_ANY, "%s: invalid; ignored\n", __func__);
734 		return;
735 	}
736 	if (!ath_hal_intrpend(ah))		/* shared irq, not for us */
737 		return;
738 	if (!((ifp->if_flags & IFF_UP) && (ifp->if_drv_flags &
739 	    IFF_DRV_RUNNING))) {
740 		DPRINTF(sc, ATH_DEBUG_ANY, "%s: if_flags 0x%x\n",
741 			__func__, ifp->if_flags);
742 		ath_hal_getisr(ah, &status);	/* clear ISR */
743 		ath_hal_intrset(ah, 0);		/* disable further intr's */
744 		return;
745 	}
746 	/*
747 	 * Figure out the reason(s) for the interrupt.  Note
748 	 * that the hal returns a pseudo-ISR that may include
749 	 * bits we haven't explicitly enabled so we mask the
750 	 * value to insure we only process bits we requested.
751 	 */
752 	ath_hal_getisr(ah, &status);		/* NB: clears ISR too */
753 	DPRINTF(sc, ATH_DEBUG_INTR, "%s: status 0x%x\n", __func__, status);
754 	status &= sc->sc_imask;			/* discard unasked for bits */
755 	if (status & HAL_INT_FATAL) {
756 		sc->sc_stats.ast_hardware++;
757 		ath_hal_intrset(ah, 0);		/* disable intr's until reset */
758 		ath_fatal_proc(sc, 0);
759 	} else if (status & HAL_INT_RXORN) {
760 		sc->sc_stats.ast_rxorn++;
761 		ath_hal_intrset(ah, 0);		/* disable intr's until reset */
762 		taskqueue_enqueue(sc->sc_tq, &sc->sc_rxorntask);
763 	} else {
764 		if (status & HAL_INT_SWBA) {
765 			/*
766 			 * Software beacon alert--time to send a beacon.
767 			 * Handle beacon transmission directly; deferring
768 			 * this is too slow to meet timing constraints
769 			 * under load.
770 			 */
771 			ath_beacon_proc(sc, 0);
772 		}
773 		if (status & HAL_INT_RXEOL) {
774 			/*
775 			 * NB: the hardware should re-read the link when
776 			 *     RXE bit is written, but it doesn't work at
777 			 *     least on older hardware revs.
778 			 */
779 			sc->sc_stats.ast_rxeol++;
780 			sc->sc_rxlink = NULL;
781 		}
782 		if (status & HAL_INT_TXURN) {
783 			sc->sc_stats.ast_txurn++;
784 			/* bump tx trigger level */
785 			ath_hal_updatetxtriglevel(ah, AH_TRUE);
786 		}
787 		if (status & HAL_INT_RX)
788 			taskqueue_enqueue(sc->sc_tq, &sc->sc_rxtask);
789 		if (status & HAL_INT_TX)
790 			taskqueue_enqueue(sc->sc_tq, &sc->sc_txtask);
791 		if (status & HAL_INT_BMISS) {
792 			sc->sc_stats.ast_bmiss++;
793 			taskqueue_enqueue(sc->sc_tq, &sc->sc_bmisstask);
794 		}
795 		if (status & HAL_INT_MIB) {
796 			sc->sc_stats.ast_mib++;
797 			/*
798 			 * Disable interrupts until we service the MIB
799 			 * interrupt; otherwise it will continue to fire.
800 			 */
801 			ath_hal_intrset(ah, 0);
802 			/*
803 			 * Let the hal handle the event.  We assume it will
804 			 * clear whatever condition caused the interrupt.
805 			 */
806 			ath_hal_mibevent(ah, &sc->sc_halstats);
807 			ath_hal_intrset(ah, sc->sc_imask);
808 		}
809 	}
810 }
811 
812 static void
813 ath_fatal_proc(void *arg, int pending)
814 {
815 	struct ath_softc *sc = arg;
816 	struct ifnet *ifp = sc->sc_ifp;
817 	u_int32_t *state;
818 	u_int32_t len;
819 
820 	if_printf(ifp, "hardware error; resetting\n");
821 	/*
822 	 * Fatal errors are unrecoverable.  Typically these
823 	 * are caused by DMA errors.  Collect h/w state from
824 	 * the hal so we can diagnose what's going on.
825 	 */
826 	if (ath_hal_getfatalstate(sc->sc_ah, &state, &len)) {
827 		KASSERT(len >= 6*sizeof(u_int32_t), ("len %u bytes", len));
828 		if_printf(ifp, "0x%08x 0x%08x 0x%08x, 0x%08x 0x%08x 0x%08x\n",
829 		    state[0], state[1] , state[2], state[3],
830 		    state[4], state[5]);
831 	}
832 	ath_reset(ifp);
833 }
834 
835 static void
836 ath_rxorn_proc(void *arg, int pending)
837 {
838 	struct ath_softc *sc = arg;
839 	struct ifnet *ifp = sc->sc_ifp;
840 
841 	if_printf(ifp, "rx FIFO overrun; resetting\n");
842 	ath_reset(ifp);
843 }
844 
845 static void
846 ath_bmiss_proc(void *arg, int pending)
847 {
848 	struct ath_softc *sc = arg;
849 	struct ieee80211com *ic = &sc->sc_ic;
850 
851 	DPRINTF(sc, ATH_DEBUG_ANY, "%s: pending %u\n", __func__, pending);
852 	KASSERT(ic->ic_opmode == IEEE80211_M_STA,
853 		("unexpect operating mode %u", ic->ic_opmode));
854 	if (ic->ic_state == IEEE80211_S_RUN) {
855 		u_int64_t lastrx = sc->sc_lastrx;
856 		u_int64_t tsf = ath_hal_gettsf64(sc->sc_ah);
857 		u_int bmisstimeout =
858 			ic->ic_bmissthreshold * ic->ic_bss->ni_intval * 1024;
859 
860 		DPRINTF(sc, ATH_DEBUG_BEACON,
861 		    "%s: tsf %llu lastrx %lld (%llu) bmiss %u\n",
862 		    __func__, (unsigned long long) tsf,
863 		    (unsigned long long)(tsf - lastrx),
864 		    (unsigned long long) lastrx, bmisstimeout);
865 		/*
866 		 * Workaround phantom bmiss interrupts by sanity-checking
867 		 * the time of our last rx'd frame.  If it is within the
868 		 * beacon miss interval then ignore the interrupt.  If it's
869 		 * truly a bmiss we'll get another interrupt soon and that'll
870 		 * be dispatched up for processing.
871 		 */
872 		if (tsf - lastrx > bmisstimeout) {
873 			NET_LOCK_GIANT();
874 			ieee80211_beacon_miss(ic);
875 			NET_UNLOCK_GIANT();
876 		} else
877 			sc->sc_stats.ast_bmiss_phantom++;
878 	}
879 }
880 
881 static void
882 ath_radar_proc(void *arg, int pending)
883 {
884 	struct ath_softc *sc = arg;
885 	struct ifnet *ifp = sc->sc_ifp;
886 	struct ath_hal *ah = sc->sc_ah;
887 	HAL_CHANNEL hchan;
888 
889 	if (ath_hal_procdfs(ah, &hchan)) {
890 		if_printf(ifp, "radar detected on channel %u/0x%x/0x%x\n",
891 			hchan.channel, hchan.channelFlags, hchan.privFlags);
892 		/*
893 		 * Initiate channel change.
894 		 */
895 		/* XXX not yet */
896 	}
897 }
898 
899 static u_int
900 ath_chan2flags(struct ieee80211com *ic, struct ieee80211_channel *chan)
901 {
902 #define	N(a)	(sizeof(a) / sizeof(a[0]))
903 	static const u_int modeflags[] = {
904 		0,			/* IEEE80211_MODE_AUTO */
905 		CHANNEL_A,		/* IEEE80211_MODE_11A */
906 		CHANNEL_B,		/* IEEE80211_MODE_11B */
907 		CHANNEL_PUREG,		/* IEEE80211_MODE_11G */
908 		0,			/* IEEE80211_MODE_FH */
909 		CHANNEL_ST,		/* IEEE80211_MODE_TURBO_A */
910 		CHANNEL_108G		/* IEEE80211_MODE_TURBO_G */
911 	};
912 	enum ieee80211_phymode mode = ieee80211_chan2mode(ic, chan);
913 
914 	KASSERT(mode < N(modeflags), ("unexpected phy mode %u", mode));
915 	KASSERT(modeflags[mode] != 0, ("mode %u undefined", mode));
916 	return modeflags[mode];
917 #undef N
918 }
919 
920 static void
921 ath_init(void *arg)
922 {
923 	struct ath_softc *sc = (struct ath_softc *) arg;
924 	struct ieee80211com *ic = &sc->sc_ic;
925 	struct ifnet *ifp = sc->sc_ifp;
926 	struct ath_hal *ah = sc->sc_ah;
927 	HAL_STATUS status;
928 
929 	DPRINTF(sc, ATH_DEBUG_ANY, "%s: if_flags 0x%x\n",
930 		__func__, ifp->if_flags);
931 
932 	ATH_LOCK(sc);
933 	/*
934 	 * Stop anything previously setup.  This is safe
935 	 * whether this is the first time through or not.
936 	 */
937 	ath_stop_locked(ifp);
938 
939 	/*
940 	 * The basic interface to setting the hardware in a good
941 	 * state is ``reset''.  On return the hardware is known to
942 	 * be powered up and with interrupts disabled.  This must
943 	 * be followed by initialization of the appropriate bits
944 	 * and then setup of the interrupt mask.
945 	 */
946 	sc->sc_curchan.channel = ic->ic_curchan->ic_freq;
947 	sc->sc_curchan.channelFlags = ath_chan2flags(ic, ic->ic_curchan);
948 	if (!ath_hal_reset(ah, sc->sc_opmode, &sc->sc_curchan, AH_FALSE, &status)) {
949 		if_printf(ifp, "unable to reset hardware; hal status %u\n",
950 			status);
951 		goto done;
952 	}
953 
954 	/*
955 	 * This is needed only to setup initial state
956 	 * but it's best done after a reset.
957 	 */
958 	ath_update_txpow(sc);
959 	/*
960 	 * Likewise this is set during reset so update
961 	 * state cached in the driver.
962 	 */
963 	sc->sc_diversity = ath_hal_getdiversity(ah);
964 	sc->sc_calinterval = 1;
965 	sc->sc_caltries = 0;
966 
967 	/*
968 	 * Setup the hardware after reset: the key cache
969 	 * is filled as needed and the receive engine is
970 	 * set going.  Frame transmit is handled entirely
971 	 * in the frame output path; there's nothing to do
972 	 * here except setup the interrupt mask.
973 	 */
974 	if (ath_startrecv(sc) != 0) {
975 		if_printf(ifp, "unable to start recv logic\n");
976 		goto done;
977 	}
978 
979 	/*
980 	 * Enable interrupts.
981 	 */
982 	sc->sc_imask = HAL_INT_RX | HAL_INT_TX
983 		  | HAL_INT_RXEOL | HAL_INT_RXORN
984 		  | HAL_INT_FATAL | HAL_INT_GLOBAL;
985 	/*
986 	 * Enable MIB interrupts when there are hardware phy counters.
987 	 * Note we only do this (at the moment) for station mode.
988 	 */
989 	if (sc->sc_needmib && ic->ic_opmode == IEEE80211_M_STA)
990 		sc->sc_imask |= HAL_INT_MIB;
991 	ath_hal_intrset(ah, sc->sc_imask);
992 
993 	ifp->if_drv_flags |= IFF_DRV_RUNNING;
994 	ic->ic_state = IEEE80211_S_INIT;
995 
996 	/*
997 	 * The hardware should be ready to go now so it's safe
998 	 * to kick the 802.11 state machine as it's likely to
999 	 * immediately call back to us to send mgmt frames.
1000 	 */
1001 	ath_chan_change(sc, ic->ic_curchan);
1002 #ifdef ATH_TX99_DIAG
1003 	if (sc->sc_tx99 != NULL)
1004 		sc->sc_tx99->start(sc->sc_tx99);
1005 	else
1006 #endif
1007 	if (ic->ic_opmode != IEEE80211_M_MONITOR) {
1008 		if (ic->ic_roaming != IEEE80211_ROAMING_MANUAL)
1009 			ieee80211_new_state(ic, IEEE80211_S_SCAN, -1);
1010 	} else
1011 		ieee80211_new_state(ic, IEEE80211_S_RUN, -1);
1012 done:
1013 	ATH_UNLOCK(sc);
1014 }
1015 
1016 static void
1017 ath_stop_locked(struct ifnet *ifp)
1018 {
1019 	struct ath_softc *sc = ifp->if_softc;
1020 	struct ieee80211com *ic = &sc->sc_ic;
1021 	struct ath_hal *ah = sc->sc_ah;
1022 
1023 	DPRINTF(sc, ATH_DEBUG_ANY, "%s: invalid %u if_flags 0x%x\n",
1024 		__func__, sc->sc_invalid, ifp->if_flags);
1025 
1026 	ATH_LOCK_ASSERT(sc);
1027 	if (ifp->if_drv_flags & IFF_DRV_RUNNING) {
1028 		/*
1029 		 * Shutdown the hardware and driver:
1030 		 *    reset 802.11 state machine
1031 		 *    turn off timers
1032 		 *    disable interrupts
1033 		 *    turn off the radio
1034 		 *    clear transmit machinery
1035 		 *    clear receive machinery
1036 		 *    drain and release tx queues
1037 		 *    reclaim beacon resources
1038 		 *    power down hardware
1039 		 *
1040 		 * Note that some of this work is not possible if the
1041 		 * hardware is gone (invalid).
1042 		 */
1043 #ifdef ATH_TX99_DIAG
1044 		if (sc->sc_tx99 != NULL)
1045 			sc->sc_tx99->stop(sc->sc_tx99);
1046 #endif
1047 		ieee80211_new_state(ic, IEEE80211_S_INIT, -1);
1048 		ifp->if_drv_flags &= ~IFF_DRV_RUNNING;
1049 		ifp->if_timer = 0;
1050 		if (!sc->sc_invalid) {
1051 			if (sc->sc_softled) {
1052 				callout_stop(&sc->sc_ledtimer);
1053 				ath_hal_gpioset(ah, sc->sc_ledpin,
1054 					!sc->sc_ledon);
1055 				sc->sc_blinking = 0;
1056 			}
1057 			ath_hal_intrset(ah, 0);
1058 		}
1059 		ath_draintxq(sc);
1060 		if (!sc->sc_invalid) {
1061 			ath_stoprecv(sc);
1062 			ath_hal_phydisable(ah);
1063 		} else
1064 			sc->sc_rxlink = NULL;
1065 		IFQ_DRV_PURGE(&ifp->if_snd);
1066 		ath_beacon_free(sc);
1067 	}
1068 }
1069 
1070 static void
1071 ath_stop(struct ifnet *ifp)
1072 {
1073 	struct ath_softc *sc = ifp->if_softc;
1074 
1075 	ATH_LOCK(sc);
1076 	ath_stop_locked(ifp);
1077 	if (!sc->sc_invalid) {
1078 		/*
1079 		 * Set the chip in full sleep mode.  Note that we are
1080 		 * careful to do this only when bringing the interface
1081 		 * completely to a stop.  When the chip is in this state
1082 		 * it must be carefully woken up or references to
1083 		 * registers in the PCI clock domain may freeze the bus
1084 		 * (and system).  This varies by chip and is mostly an
1085 		 * issue with newer parts that go to sleep more quickly.
1086 		 */
1087 		ath_hal_setpower(sc->sc_ah, HAL_PM_FULL_SLEEP);
1088 	}
1089 	ATH_UNLOCK(sc);
1090 }
1091 
1092 /*
1093  * Reset the hardware w/o losing operational state.  This is
1094  * basically a more efficient way of doing ath_stop, ath_init,
1095  * followed by state transitions to the current 802.11
1096  * operational state.  Used to recover from various errors and
1097  * to reset or reload hardware state.
1098  */
1099 static int
1100 ath_reset(struct ifnet *ifp)
1101 {
1102 	struct ath_softc *sc = ifp->if_softc;
1103 	struct ieee80211com *ic = &sc->sc_ic;
1104 	struct ath_hal *ah = sc->sc_ah;
1105 	struct ieee80211_channel *c;
1106 	HAL_STATUS status;
1107 
1108 	/*
1109 	 * Convert to a HAL channel description with the flags
1110 	 * constrained to reflect the current operating mode.
1111 	 */
1112 	c = ic->ic_curchan;
1113 	sc->sc_curchan.channel = c->ic_freq;
1114 	sc->sc_curchan.channelFlags = ath_chan2flags(ic, c);
1115 
1116 	ath_hal_intrset(ah, 0);		/* disable interrupts */
1117 	ath_draintxq(sc);		/* stop xmit side */
1118 	ath_stoprecv(sc);		/* stop recv side */
1119 	/* NB: indicate channel change so we do a full reset */
1120 	if (!ath_hal_reset(ah, sc->sc_opmode, &sc->sc_curchan, AH_TRUE, &status))
1121 		if_printf(ifp, "%s: unable to reset hardware; hal status %u\n",
1122 			__func__, status);
1123 	ath_update_txpow(sc);		/* update tx power state */
1124 	sc->sc_diversity = ath_hal_getdiversity(ah);
1125 	sc->sc_calinterval = 1;
1126 	sc->sc_caltries = 0;
1127 	/*
1128 	 * We may be doing a reset in response to an ioctl
1129 	 * that changes the channel so update any state that
1130 	 * might change as a result.
1131 	 */
1132 	ath_chan_change(sc, c);
1133 	if (ath_startrecv(sc) != 0)	/* restart recv */
1134 		if_printf(ifp, "%s: unable to start recv logic\n", __func__);
1135 	if (ic->ic_state == IEEE80211_S_RUN)
1136 		ath_beacon_config(sc);	/* restart beacons */
1137 	ath_hal_intrset(ah, sc->sc_imask);
1138 
1139 	ath_start(ifp);			/* restart xmit */
1140 	return 0;
1141 }
1142 
1143 static void
1144 ath_start(struct ifnet *ifp)
1145 {
1146 	struct ath_softc *sc = ifp->if_softc;
1147 	struct ath_hal *ah = sc->sc_ah;
1148 	struct ieee80211com *ic = &sc->sc_ic;
1149 	struct ieee80211_node *ni;
1150 	struct ath_buf *bf;
1151 	struct mbuf *m;
1152 	struct ieee80211_frame *wh;
1153 	struct ether_header *eh;
1154 
1155 	if ((ifp->if_drv_flags & IFF_DRV_RUNNING) == 0 || sc->sc_invalid)
1156 		return;
1157 	for (;;) {
1158 		/*
1159 		 * Grab a TX buffer and associated resources.
1160 		 */
1161 		ATH_TXBUF_LOCK(sc);
1162 		bf = STAILQ_FIRST(&sc->sc_txbuf);
1163 		if (bf != NULL)
1164 			STAILQ_REMOVE_HEAD(&sc->sc_txbuf, bf_list);
1165 		ATH_TXBUF_UNLOCK(sc);
1166 		if (bf == NULL) {
1167 			DPRINTF(sc, ATH_DEBUG_XMIT, "%s: out of xmit buffers\n",
1168 				__func__);
1169 			sc->sc_stats.ast_tx_qstop++;
1170 			ifp->if_drv_flags |= IFF_DRV_OACTIVE;
1171 			break;
1172 		}
1173 		/*
1174 		 * Poll the management queue for frames; they
1175 		 * have priority over normal data frames.
1176 		 */
1177 		IF_DEQUEUE(&ic->ic_mgtq, m);
1178 		if (m == NULL) {
1179 			/*
1180 			 * No data frames go out unless we're associated.
1181 			 */
1182 			if (ic->ic_state != IEEE80211_S_RUN) {
1183 				DPRINTF(sc, ATH_DEBUG_XMIT,
1184 				    "%s: discard data packet, state %s\n",
1185 				    __func__,
1186 				    ieee80211_state_name[ic->ic_state]);
1187 				sc->sc_stats.ast_tx_discard++;
1188 				ATH_TXBUF_LOCK(sc);
1189 				STAILQ_INSERT_TAIL(&sc->sc_txbuf, bf, bf_list);
1190 				ATH_TXBUF_UNLOCK(sc);
1191 				break;
1192 			}
1193 			IFQ_DRV_DEQUEUE(&ifp->if_snd, m);	/* XXX: LOCK */
1194 			if (m == NULL) {
1195 				ATH_TXBUF_LOCK(sc);
1196 				STAILQ_INSERT_TAIL(&sc->sc_txbuf, bf, bf_list);
1197 				ATH_TXBUF_UNLOCK(sc);
1198 				break;
1199 			}
1200 			/*
1201 			 * Find the node for the destination so we can do
1202 			 * things like power save and fast frames aggregation.
1203 			 */
1204 			if (m->m_len < sizeof(struct ether_header) &&
1205 			   (m = m_pullup(m, sizeof(struct ether_header))) == NULL) {
1206 				ic->ic_stats.is_tx_nobuf++;	/* XXX */
1207 				ni = NULL;
1208 				goto bad;
1209 			}
1210 			eh = mtod(m, struct ether_header *);
1211 			ni = ieee80211_find_txnode(ic, eh->ether_dhost);
1212 			if (ni == NULL) {
1213 				/* NB: ieee80211_find_txnode does stat+msg */
1214 				m_freem(m);
1215 				goto bad;
1216 			}
1217 			if ((ni->ni_flags & IEEE80211_NODE_PWR_MGT) &&
1218 			    (m->m_flags & M_PWR_SAV) == 0) {
1219 				/*
1220 				 * Station in power save mode; pass the frame
1221 				 * to the 802.11 layer and continue.  We'll get
1222 				 * the frame back when the time is right.
1223 				 */
1224 				ieee80211_pwrsave(ic, ni, m);
1225 				goto reclaim;
1226 			}
1227 			/* calculate priority so we can find the tx queue */
1228 			if (ieee80211_classify(ic, m, ni)) {
1229 				DPRINTF(sc, ATH_DEBUG_XMIT,
1230 					"%s: discard, classification failure\n",
1231 					__func__);
1232 				m_freem(m);
1233 				goto bad;
1234 			}
1235 			ifp->if_opackets++;
1236 			BPF_MTAP(ifp, m);
1237 			/*
1238 			 * Encapsulate the packet in prep for transmission.
1239 			 */
1240 			m = ieee80211_encap(ic, m, ni);
1241 			if (m == NULL) {
1242 				DPRINTF(sc, ATH_DEBUG_XMIT,
1243 					"%s: encapsulation failure\n",
1244 					__func__);
1245 				sc->sc_stats.ast_tx_encap++;
1246 				goto bad;
1247 			}
1248 		} else {
1249 			/*
1250 			 * Hack!  The referenced node pointer is in the
1251 			 * rcvif field of the packet header.  This is
1252 			 * placed there by ieee80211_mgmt_output because
1253 			 * we need to hold the reference with the frame
1254 			 * and there's no other way (other than packet
1255 			 * tags which we consider too expensive to use)
1256 			 * to pass it along.
1257 			 */
1258 			ni = (struct ieee80211_node *) m->m_pkthdr.rcvif;
1259 			m->m_pkthdr.rcvif = NULL;
1260 
1261 			wh = mtod(m, struct ieee80211_frame *);
1262 			if ((wh->i_fc[0] & IEEE80211_FC0_SUBTYPE_MASK) ==
1263 			    IEEE80211_FC0_SUBTYPE_PROBE_RESP) {
1264 				/* fill time stamp */
1265 				u_int64_t tsf;
1266 				u_int32_t *tstamp;
1267 
1268 				tsf = ath_hal_gettsf64(ah);
1269 				/* XXX: adjust 100us delay to xmit */
1270 				tsf += 100;
1271 				tstamp = (u_int32_t *)&wh[1];
1272 				tstamp[0] = htole32(tsf & 0xffffffff);
1273 				tstamp[1] = htole32(tsf >> 32);
1274 			}
1275 			sc->sc_stats.ast_tx_mgmt++;
1276 		}
1277 
1278 		if (ath_tx_start(sc, ni, bf, m)) {
1279 	bad:
1280 			ifp->if_oerrors++;
1281 	reclaim:
1282 			ATH_TXBUF_LOCK(sc);
1283 			STAILQ_INSERT_TAIL(&sc->sc_txbuf, bf, bf_list);
1284 			ATH_TXBUF_UNLOCK(sc);
1285 			if (ni != NULL)
1286 				ieee80211_free_node(ni);
1287 			continue;
1288 		}
1289 
1290 		sc->sc_tx_timer = 5;
1291 		ifp->if_timer = 1;
1292 	}
1293 }
1294 
1295 static int
1296 ath_media_change(struct ifnet *ifp)
1297 {
1298 #define	IS_UP(ifp) \
1299 	((ifp->if_flags & IFF_UP) && (ifp->if_drv_flags & IFF_DRV_RUNNING))
1300 	int error;
1301 
1302 	error = ieee80211_media_change(ifp);
1303 	if (error == ENETRESET) {
1304 		struct ath_softc *sc = ifp->if_softc;
1305 		struct ieee80211com *ic = &sc->sc_ic;
1306 
1307 		if (ic->ic_opmode == IEEE80211_M_AHDEMO) {
1308 			/*
1309 			 * Adhoc demo mode is just ibss mode w/o beacons
1310 			 * (mostly).  The hal knows nothing about it;
1311 			 * tell it we're operating in ibss mode.
1312 			 */
1313 			sc->sc_opmode = HAL_M_IBSS;
1314 		} else
1315 			sc->sc_opmode = ic->ic_opmode;
1316 		if (IS_UP(ifp))
1317 			ath_init(ifp->if_softc);	/* XXX lose error */
1318 		error = 0;
1319 	}
1320 	return error;
1321 #undef IS_UP
1322 }
1323 
1324 #ifdef ATH_DEBUG
1325 static void
1326 ath_keyprint(const char *tag, u_int ix,
1327 	const HAL_KEYVAL *hk, const u_int8_t mac[IEEE80211_ADDR_LEN])
1328 {
1329 	static const char *ciphers[] = {
1330 		"WEP",
1331 		"AES-OCB",
1332 		"AES-CCM",
1333 		"CKIP",
1334 		"TKIP",
1335 		"CLR",
1336 	};
1337 	int i, n;
1338 
1339 	printf("%s: [%02u] %-7s ", tag, ix, ciphers[hk->kv_type]);
1340 	for (i = 0, n = hk->kv_len; i < n; i++)
1341 		printf("%02x", hk->kv_val[i]);
1342 	printf(" mac %s", ether_sprintf(mac));
1343 	if (hk->kv_type == HAL_CIPHER_TKIP) {
1344 		printf(" mic ");
1345 		for (i = 0; i < sizeof(hk->kv_mic); i++)
1346 			printf("%02x", hk->kv_mic[i]);
1347 	}
1348 	printf("\n");
1349 }
1350 #endif
1351 
1352 /*
1353  * Set a TKIP key into the hardware.  This handles the
1354  * potential distribution of key state to multiple key
1355  * cache slots for TKIP.
1356  */
1357 static int
1358 ath_keyset_tkip(struct ath_softc *sc, const struct ieee80211_key *k,
1359 	HAL_KEYVAL *hk, const u_int8_t mac[IEEE80211_ADDR_LEN])
1360 {
1361 #define	IEEE80211_KEY_XR	(IEEE80211_KEY_XMIT | IEEE80211_KEY_RECV)
1362 	static const u_int8_t zerobssid[IEEE80211_ADDR_LEN];
1363 	struct ath_hal *ah = sc->sc_ah;
1364 
1365 	KASSERT(k->wk_cipher->ic_cipher == IEEE80211_CIPHER_TKIP,
1366 		("got a non-TKIP key, cipher %u", k->wk_cipher->ic_cipher));
1367 	KASSERT(sc->sc_splitmic, ("key cache !split"));
1368 	if ((k->wk_flags & IEEE80211_KEY_XR) == IEEE80211_KEY_XR) {
1369 		/*
1370 		 * TX key goes at first index, RX key at the rx index.
1371 		 * The hal handles the MIC keys at index+64.
1372 		 */
1373 		memcpy(hk->kv_mic, k->wk_txmic, sizeof(hk->kv_mic));
1374 		KEYPRINTF(sc, k->wk_keyix, hk, zerobssid);
1375 		if (!ath_hal_keyset(ah, k->wk_keyix, hk, zerobssid))
1376 			return 0;
1377 
1378 		memcpy(hk->kv_mic, k->wk_rxmic, sizeof(hk->kv_mic));
1379 		KEYPRINTF(sc, k->wk_keyix+32, hk, mac);
1380 		/* XXX delete tx key on failure? */
1381 		return ath_hal_keyset(ah, k->wk_keyix+32, hk, mac);
1382 	} else if (k->wk_flags & IEEE80211_KEY_XR) {
1383 		/*
1384 		 * TX/RX key goes at first index.
1385 		 * The hal handles the MIC keys are index+64.
1386 		 */
1387 		memcpy(hk->kv_mic, k->wk_flags & IEEE80211_KEY_XMIT ?
1388 			k->wk_txmic : k->wk_rxmic, sizeof(hk->kv_mic));
1389 		KEYPRINTF(sc, k->wk_keyix, hk, mac);
1390 		return ath_hal_keyset(ah, k->wk_keyix, hk, mac);
1391 	}
1392 	return 0;
1393 #undef IEEE80211_KEY_XR
1394 }
1395 
1396 /*
1397  * Set a net80211 key into the hardware.  This handles the
1398  * potential distribution of key state to multiple key
1399  * cache slots for TKIP with hardware MIC support.
1400  */
1401 static int
1402 ath_keyset(struct ath_softc *sc, const struct ieee80211_key *k,
1403 	const u_int8_t mac0[IEEE80211_ADDR_LEN],
1404 	struct ieee80211_node *bss)
1405 {
1406 #define	N(a)	(sizeof(a)/sizeof(a[0]))
1407 	static const u_int8_t ciphermap[] = {
1408 		HAL_CIPHER_WEP,		/* IEEE80211_CIPHER_WEP */
1409 		HAL_CIPHER_TKIP,	/* IEEE80211_CIPHER_TKIP */
1410 		HAL_CIPHER_AES_OCB,	/* IEEE80211_CIPHER_AES_OCB */
1411 		HAL_CIPHER_AES_CCM,	/* IEEE80211_CIPHER_AES_CCM */
1412 		(u_int8_t) -1,		/* 4 is not allocated */
1413 		HAL_CIPHER_CKIP,	/* IEEE80211_CIPHER_CKIP */
1414 		HAL_CIPHER_CLR,		/* IEEE80211_CIPHER_NONE */
1415 	};
1416 	struct ath_hal *ah = sc->sc_ah;
1417 	const struct ieee80211_cipher *cip = k->wk_cipher;
1418 	u_int8_t gmac[IEEE80211_ADDR_LEN];
1419 	const u_int8_t *mac;
1420 	HAL_KEYVAL hk;
1421 
1422 	memset(&hk, 0, sizeof(hk));
1423 	/*
1424 	 * Software crypto uses a "clear key" so non-crypto
1425 	 * state kept in the key cache are maintained and
1426 	 * so that rx frames have an entry to match.
1427 	 */
1428 	if ((k->wk_flags & IEEE80211_KEY_SWCRYPT) == 0) {
1429 		KASSERT(cip->ic_cipher < N(ciphermap),
1430 			("invalid cipher type %u", cip->ic_cipher));
1431 		hk.kv_type = ciphermap[cip->ic_cipher];
1432 		hk.kv_len = k->wk_keylen;
1433 		memcpy(hk.kv_val, k->wk_key, k->wk_keylen);
1434 	} else
1435 		hk.kv_type = HAL_CIPHER_CLR;
1436 
1437 	if ((k->wk_flags & IEEE80211_KEY_GROUP) && sc->sc_mcastkey) {
1438 		/*
1439 		 * Group keys on hardware that supports multicast frame
1440 		 * key search use a mac that is the sender's address with
1441 		 * the high bit set instead of the app-specified address.
1442 		 */
1443 		IEEE80211_ADDR_COPY(gmac, bss->ni_macaddr);
1444 		gmac[0] |= 0x80;
1445 		mac = gmac;
1446 	} else
1447 		mac = mac0;
1448 
1449 	if (hk.kv_type == HAL_CIPHER_TKIP &&
1450 	    (k->wk_flags & IEEE80211_KEY_SWMIC) == 0 &&
1451 	    sc->sc_splitmic) {
1452 		return ath_keyset_tkip(sc, k, &hk, mac);
1453 	} else {
1454 		KEYPRINTF(sc, k->wk_keyix, &hk, mac);
1455 		return ath_hal_keyset(ah, k->wk_keyix, &hk, mac);
1456 	}
1457 #undef N
1458 }
1459 
1460 /*
1461  * Allocate tx/rx key slots for TKIP.  We allocate two slots for
1462  * each key, one for decrypt/encrypt and the other for the MIC.
1463  */
1464 static u_int16_t
1465 key_alloc_2pair(struct ath_softc *sc,
1466 	ieee80211_keyix *txkeyix, ieee80211_keyix *rxkeyix)
1467 {
1468 #define	N(a)	(sizeof(a)/sizeof(a[0]))
1469 	u_int i, keyix;
1470 
1471 	KASSERT(sc->sc_splitmic, ("key cache !split"));
1472 	/* XXX could optimize */
1473 	for (i = 0; i < N(sc->sc_keymap)/4; i++) {
1474 		u_int8_t b = sc->sc_keymap[i];
1475 		if (b != 0xff) {
1476 			/*
1477 			 * One or more slots in this byte are free.
1478 			 */
1479 			keyix = i*NBBY;
1480 			while (b & 1) {
1481 		again:
1482 				keyix++;
1483 				b >>= 1;
1484 			}
1485 			/* XXX IEEE80211_KEY_XMIT | IEEE80211_KEY_RECV */
1486 			if (isset(sc->sc_keymap, keyix+32) ||
1487 			    isset(sc->sc_keymap, keyix+64) ||
1488 			    isset(sc->sc_keymap, keyix+32+64)) {
1489 				/* full pair unavailable */
1490 				/* XXX statistic */
1491 				if (keyix == (i+1)*NBBY) {
1492 					/* no slots were appropriate, advance */
1493 					continue;
1494 				}
1495 				goto again;
1496 			}
1497 			setbit(sc->sc_keymap, keyix);
1498 			setbit(sc->sc_keymap, keyix+64);
1499 			setbit(sc->sc_keymap, keyix+32);
1500 			setbit(sc->sc_keymap, keyix+32+64);
1501 			DPRINTF(sc, ATH_DEBUG_KEYCACHE,
1502 				"%s: key pair %u,%u %u,%u\n",
1503 				__func__, keyix, keyix+64,
1504 				keyix+32, keyix+32+64);
1505 			*txkeyix = keyix;
1506 			*rxkeyix = keyix+32;
1507 			return 1;
1508 		}
1509 	}
1510 	DPRINTF(sc, ATH_DEBUG_KEYCACHE, "%s: out of pair space\n", __func__);
1511 	return 0;
1512 #undef N
1513 }
1514 
1515 /*
1516  * Allocate a single key cache slot.
1517  */
1518 static int
1519 key_alloc_single(struct ath_softc *sc,
1520 	ieee80211_keyix *txkeyix, ieee80211_keyix *rxkeyix)
1521 {
1522 #define	N(a)	(sizeof(a)/sizeof(a[0]))
1523 	u_int i, keyix;
1524 
1525 	/* XXX try i,i+32,i+64,i+32+64 to minimize key pair conflicts */
1526 	for (i = 0; i < N(sc->sc_keymap); i++) {
1527 		u_int8_t b = sc->sc_keymap[i];
1528 		if (b != 0xff) {
1529 			/*
1530 			 * One or more slots are free.
1531 			 */
1532 			keyix = i*NBBY;
1533 			while (b & 1)
1534 				keyix++, b >>= 1;
1535 			setbit(sc->sc_keymap, keyix);
1536 			DPRINTF(sc, ATH_DEBUG_KEYCACHE, "%s: key %u\n",
1537 				__func__, keyix);
1538 			*txkeyix = *rxkeyix = keyix;
1539 			return 1;
1540 		}
1541 	}
1542 	DPRINTF(sc, ATH_DEBUG_KEYCACHE, "%s: out of space\n", __func__);
1543 	return 0;
1544 #undef N
1545 }
1546 
1547 /*
1548  * Allocate one or more key cache slots for a uniacst key.  The
1549  * key itself is needed only to identify the cipher.  For hardware
1550  * TKIP with split cipher+MIC keys we allocate two key cache slot
1551  * pairs so that we can setup separate TX and RX MIC keys.  Note
1552  * that the MIC key for a TKIP key at slot i is assumed by the
1553  * hardware to be at slot i+64.  This limits TKIP keys to the first
1554  * 64 entries.
1555  */
1556 static int
1557 ath_key_alloc(struct ieee80211com *ic, const struct ieee80211_key *k,
1558 	ieee80211_keyix *keyix, ieee80211_keyix *rxkeyix)
1559 {
1560 	struct ath_softc *sc = ic->ic_ifp->if_softc;
1561 
1562 	/*
1563 	 * Group key allocation must be handled specially for
1564 	 * parts that do not support multicast key cache search
1565 	 * functionality.  For those parts the key id must match
1566 	 * the h/w key index so lookups find the right key.  On
1567 	 * parts w/ the key search facility we install the sender's
1568 	 * mac address (with the high bit set) and let the hardware
1569 	 * find the key w/o using the key id.  This is preferred as
1570 	 * it permits us to support multiple users for adhoc and/or
1571 	 * multi-station operation.
1572 	 */
1573 	if ((k->wk_flags & IEEE80211_KEY_GROUP) && !sc->sc_mcastkey) {
1574 		if (!(&ic->ic_nw_keys[0] <= k &&
1575 		      k < &ic->ic_nw_keys[IEEE80211_WEP_NKID])) {
1576 			/* should not happen */
1577 			DPRINTF(sc, ATH_DEBUG_KEYCACHE,
1578 				"%s: bogus group key\n", __func__);
1579 			return 0;
1580 		}
1581 		/*
1582 		 * XXX we pre-allocate the global keys so
1583 		 * have no way to check if they've already been allocated.
1584 		 */
1585 		*keyix = *rxkeyix = k - ic->ic_nw_keys;
1586 		return 1;
1587 	}
1588 
1589 	/*
1590 	 * We allocate two pair for TKIP when using the h/w to do
1591 	 * the MIC.  For everything else, including software crypto,
1592 	 * we allocate a single entry.  Note that s/w crypto requires
1593 	 * a pass-through slot on the 5211 and 5212.  The 5210 does
1594 	 * not support pass-through cache entries and we map all
1595 	 * those requests to slot 0.
1596 	 */
1597 	if (k->wk_flags & IEEE80211_KEY_SWCRYPT) {
1598 		return key_alloc_single(sc, keyix, rxkeyix);
1599 	} else if (k->wk_cipher->ic_cipher == IEEE80211_CIPHER_TKIP &&
1600 	    (k->wk_flags & IEEE80211_KEY_SWMIC) == 0 && sc->sc_splitmic) {
1601 		return key_alloc_2pair(sc, keyix, rxkeyix);
1602 	} else {
1603 		return key_alloc_single(sc, keyix, rxkeyix);
1604 	}
1605 }
1606 
1607 /*
1608  * Delete an entry in the key cache allocated by ath_key_alloc.
1609  */
1610 static int
1611 ath_key_delete(struct ieee80211com *ic, const struct ieee80211_key *k)
1612 {
1613 	struct ath_softc *sc = ic->ic_ifp->if_softc;
1614 	struct ath_hal *ah = sc->sc_ah;
1615 	const struct ieee80211_cipher *cip = k->wk_cipher;
1616 	u_int keyix = k->wk_keyix;
1617 
1618 	DPRINTF(sc, ATH_DEBUG_KEYCACHE, "%s: delete key %u\n", __func__, keyix);
1619 
1620 	ath_hal_keyreset(ah, keyix);
1621 	/*
1622 	 * Handle split tx/rx keying required for TKIP with h/w MIC.
1623 	 */
1624 	if (cip->ic_cipher == IEEE80211_CIPHER_TKIP &&
1625 	    (k->wk_flags & IEEE80211_KEY_SWMIC) == 0 && sc->sc_splitmic)
1626 		ath_hal_keyreset(ah, keyix+32);		/* RX key */
1627 	if (keyix >= IEEE80211_WEP_NKID) {
1628 		/*
1629 		 * Don't touch keymap entries for global keys so
1630 		 * they are never considered for dynamic allocation.
1631 		 */
1632 		clrbit(sc->sc_keymap, keyix);
1633 		if (cip->ic_cipher == IEEE80211_CIPHER_TKIP &&
1634 		    (k->wk_flags & IEEE80211_KEY_SWMIC) == 0 &&
1635 		    sc->sc_splitmic) {
1636 			clrbit(sc->sc_keymap, keyix+64);	/* TX key MIC */
1637 			clrbit(sc->sc_keymap, keyix+32);	/* RX key */
1638 			clrbit(sc->sc_keymap, keyix+32+64);	/* RX key MIC */
1639 		}
1640 	}
1641 	return 1;
1642 }
1643 
1644 /*
1645  * Set the key cache contents for the specified key.  Key cache
1646  * slot(s) must already have been allocated by ath_key_alloc.
1647  */
1648 static int
1649 ath_key_set(struct ieee80211com *ic, const struct ieee80211_key *k,
1650 	const u_int8_t mac[IEEE80211_ADDR_LEN])
1651 {
1652 	struct ath_softc *sc = ic->ic_ifp->if_softc;
1653 
1654 	return ath_keyset(sc, k, mac, ic->ic_bss);
1655 }
1656 
1657 /*
1658  * Block/unblock tx+rx processing while a key change is done.
1659  * We assume the caller serializes key management operations
1660  * so we only need to worry about synchronization with other
1661  * uses that originate in the driver.
1662  */
1663 static void
1664 ath_key_update_begin(struct ieee80211com *ic)
1665 {
1666 	struct ifnet *ifp = ic->ic_ifp;
1667 	struct ath_softc *sc = ifp->if_softc;
1668 
1669 	DPRINTF(sc, ATH_DEBUG_KEYCACHE, "%s:\n", __func__);
1670 #if 0
1671 	tasklet_disable(&sc->sc_rxtq);
1672 #endif
1673 	IF_LOCK(&ifp->if_snd);		/* NB: doesn't block mgmt frames */
1674 }
1675 
1676 static void
1677 ath_key_update_end(struct ieee80211com *ic)
1678 {
1679 	struct ifnet *ifp = ic->ic_ifp;
1680 	struct ath_softc *sc = ifp->if_softc;
1681 
1682 	DPRINTF(sc, ATH_DEBUG_KEYCACHE, "%s:\n", __func__);
1683 	IF_UNLOCK(&ifp->if_snd);
1684 #if 0
1685 	tasklet_enable(&sc->sc_rxtq);
1686 #endif
1687 }
1688 
1689 /*
1690  * Calculate the receive filter according to the
1691  * operating mode and state:
1692  *
1693  * o always accept unicast, broadcast, and multicast traffic
1694  * o maintain current state of phy error reception (the hal
1695  *   may enable phy error frames for noise immunity work)
1696  * o probe request frames are accepted only when operating in
1697  *   hostap, adhoc, or monitor modes
1698  * o enable promiscuous mode according to the interface state
1699  * o accept beacons:
1700  *   - when operating in adhoc mode so the 802.11 layer creates
1701  *     node table entries for peers,
1702  *   - when operating in station mode for collecting rssi data when
1703  *     the station is otherwise quiet, or
1704  *   - when scanning
1705  * o accept control frames:
1706  *   - when in monitor mode
1707  */
1708 static u_int32_t
1709 ath_calcrxfilter(struct ath_softc *sc, enum ieee80211_state state)
1710 {
1711 #define	RX_FILTER_PRESERVE	(HAL_RX_FILTER_PHYERR | HAL_RX_FILTER_PHYRADAR)
1712 	struct ieee80211com *ic = &sc->sc_ic;
1713 	struct ath_hal *ah = sc->sc_ah;
1714 	struct ifnet *ifp = sc->sc_ifp;
1715 	u_int32_t rfilt;
1716 
1717 	rfilt = (ath_hal_getrxfilter(ah) & RX_FILTER_PRESERVE)
1718 	      | HAL_RX_FILTER_UCAST | HAL_RX_FILTER_BCAST | HAL_RX_FILTER_MCAST;
1719 	if (ic->ic_opmode != IEEE80211_M_STA)
1720 		rfilt |= HAL_RX_FILTER_PROBEREQ;
1721 	if (ic->ic_opmode != IEEE80211_M_HOSTAP &&
1722 	    (ifp->if_flags & IFF_PROMISC))
1723 		rfilt |= HAL_RX_FILTER_PROM;
1724 	if (ic->ic_opmode == IEEE80211_M_STA ||
1725 	    ic->ic_opmode == IEEE80211_M_IBSS ||
1726 	    state == IEEE80211_S_SCAN)
1727 		rfilt |= HAL_RX_FILTER_BEACON;
1728 	if (ic->ic_opmode == IEEE80211_M_MONITOR)
1729 		rfilt |= HAL_RX_FILTER_CONTROL;
1730 	return rfilt;
1731 #undef RX_FILTER_PRESERVE
1732 }
1733 
1734 static void
1735 ath_mode_init(struct ath_softc *sc)
1736 {
1737 	struct ieee80211com *ic = &sc->sc_ic;
1738 	struct ath_hal *ah = sc->sc_ah;
1739 	struct ifnet *ifp = sc->sc_ifp;
1740 	u_int32_t rfilt, mfilt[2], val;
1741 	u_int8_t pos;
1742 	struct ifmultiaddr *ifma;
1743 
1744 	/* configure rx filter */
1745 	rfilt = ath_calcrxfilter(sc, ic->ic_state);
1746 	ath_hal_setrxfilter(ah, rfilt);
1747 
1748 	/* configure operational mode */
1749 	ath_hal_setopmode(ah);
1750 
1751 	/*
1752 	 * Handle any link-level address change.  Note that we only
1753 	 * need to force ic_myaddr; any other addresses are handled
1754 	 * as a byproduct of the ifnet code marking the interface
1755 	 * down then up.
1756 	 *
1757 	 * XXX should get from lladdr instead of arpcom but that's more work
1758 	 */
1759 	IEEE80211_ADDR_COPY(ic->ic_myaddr, IF_LLADDR(ifp));
1760 	ath_hal_setmac(ah, ic->ic_myaddr);
1761 
1762 	/* calculate and install multicast filter */
1763 	if ((ifp->if_flags & IFF_ALLMULTI) == 0) {
1764 		mfilt[0] = mfilt[1] = 0;
1765 		IF_ADDR_LOCK(ifp);
1766 		TAILQ_FOREACH(ifma, &ifp->if_multiaddrs, ifma_link) {
1767 			caddr_t dl;
1768 
1769 			/* calculate XOR of eight 6bit values */
1770 			dl = LLADDR((struct sockaddr_dl *) ifma->ifma_addr);
1771 			val = LE_READ_4(dl + 0);
1772 			pos = (val >> 18) ^ (val >> 12) ^ (val >> 6) ^ val;
1773 			val = LE_READ_4(dl + 3);
1774 			pos ^= (val >> 18) ^ (val >> 12) ^ (val >> 6) ^ val;
1775 			pos &= 0x3f;
1776 			mfilt[pos / 32] |= (1 << (pos % 32));
1777 		}
1778 		IF_ADDR_UNLOCK(ifp);
1779 	} else {
1780 		mfilt[0] = mfilt[1] = ~0;
1781 	}
1782 	ath_hal_setmcastfilter(ah, mfilt[0], mfilt[1]);
1783 	DPRINTF(sc, ATH_DEBUG_MODE, "%s: RX filter 0x%x, MC filter %08x:%08x\n",
1784 		__func__, rfilt, mfilt[0], mfilt[1]);
1785 }
1786 
1787 /*
1788  * Set the slot time based on the current setting.
1789  */
1790 static void
1791 ath_setslottime(struct ath_softc *sc)
1792 {
1793 	struct ieee80211com *ic = &sc->sc_ic;
1794 	struct ath_hal *ah = sc->sc_ah;
1795 
1796 	if (ic->ic_flags & IEEE80211_F_SHSLOT)
1797 		ath_hal_setslottime(ah, HAL_SLOT_TIME_9);
1798 	else
1799 		ath_hal_setslottime(ah, HAL_SLOT_TIME_20);
1800 	sc->sc_updateslot = OK;
1801 }
1802 
1803 /*
1804  * Callback from the 802.11 layer to update the
1805  * slot time based on the current setting.
1806  */
1807 static void
1808 ath_updateslot(struct ifnet *ifp)
1809 {
1810 	struct ath_softc *sc = ifp->if_softc;
1811 	struct ieee80211com *ic = &sc->sc_ic;
1812 
1813 	/*
1814 	 * When not coordinating the BSS, change the hardware
1815 	 * immediately.  For other operation we defer the change
1816 	 * until beacon updates have propagated to the stations.
1817 	 */
1818 	if (ic->ic_opmode == IEEE80211_M_HOSTAP)
1819 		sc->sc_updateslot = UPDATE;
1820 	else
1821 		ath_setslottime(sc);
1822 }
1823 
1824 /*
1825  * Setup a h/w transmit queue for beacons.
1826  */
1827 static int
1828 ath_beaconq_setup(struct ath_hal *ah)
1829 {
1830 	HAL_TXQ_INFO qi;
1831 
1832 	memset(&qi, 0, sizeof(qi));
1833 	qi.tqi_aifs = HAL_TXQ_USEDEFAULT;
1834 	qi.tqi_cwmin = HAL_TXQ_USEDEFAULT;
1835 	qi.tqi_cwmax = HAL_TXQ_USEDEFAULT;
1836 	/* NB: for dynamic turbo, don't enable any other interrupts */
1837 	qi.tqi_qflags = HAL_TXQ_TXDESCINT_ENABLE;
1838 	return ath_hal_setuptxqueue(ah, HAL_TX_QUEUE_BEACON, &qi);
1839 }
1840 
1841 /*
1842  * Setup the transmit queue parameters for the beacon queue.
1843  */
1844 static int
1845 ath_beaconq_config(struct ath_softc *sc)
1846 {
1847 #define	ATH_EXPONENT_TO_VALUE(v)	((1<<(v))-1)
1848 	struct ieee80211com *ic = &sc->sc_ic;
1849 	struct ath_hal *ah = sc->sc_ah;
1850 	HAL_TXQ_INFO qi;
1851 
1852 	ath_hal_gettxqueueprops(ah, sc->sc_bhalq, &qi);
1853 	if (ic->ic_opmode == IEEE80211_M_HOSTAP) {
1854 		/*
1855 		 * Always burst out beacon and CAB traffic.
1856 		 */
1857 		qi.tqi_aifs = ATH_BEACON_AIFS_DEFAULT;
1858 		qi.tqi_cwmin = ATH_BEACON_CWMIN_DEFAULT;
1859 		qi.tqi_cwmax = ATH_BEACON_CWMAX_DEFAULT;
1860 	} else {
1861 		struct wmeParams *wmep =
1862 			&ic->ic_wme.wme_chanParams.cap_wmeParams[WME_AC_BE];
1863 		/*
1864 		 * Adhoc mode; important thing is to use 2x cwmin.
1865 		 */
1866 		qi.tqi_aifs = wmep->wmep_aifsn;
1867 		qi.tqi_cwmin = 2*ATH_EXPONENT_TO_VALUE(wmep->wmep_logcwmin);
1868 		qi.tqi_cwmax = ATH_EXPONENT_TO_VALUE(wmep->wmep_logcwmax);
1869 	}
1870 
1871 	if (!ath_hal_settxqueueprops(ah, sc->sc_bhalq, &qi)) {
1872 		device_printf(sc->sc_dev, "unable to update parameters for "
1873 			"beacon hardware queue!\n");
1874 		return 0;
1875 	} else {
1876 		ath_hal_resettxqueue(ah, sc->sc_bhalq); /* push to h/w */
1877 		return 1;
1878 	}
1879 #undef ATH_EXPONENT_TO_VALUE
1880 }
1881 
1882 /*
1883  * Allocate and setup an initial beacon frame.
1884  */
1885 static int
1886 ath_beacon_alloc(struct ath_softc *sc, struct ieee80211_node *ni)
1887 {
1888 	struct ieee80211com *ic = ni->ni_ic;
1889 	struct ath_buf *bf;
1890 	struct mbuf *m;
1891 	int error;
1892 
1893 	bf = STAILQ_FIRST(&sc->sc_bbuf);
1894 	if (bf == NULL) {
1895 		DPRINTF(sc, ATH_DEBUG_BEACON, "%s: no dma buffers\n", __func__);
1896 		sc->sc_stats.ast_be_nombuf++;	/* XXX */
1897 		return ENOMEM;			/* XXX */
1898 	}
1899 	/*
1900 	 * NB: the beacon data buffer must be 32-bit aligned;
1901 	 * we assume the mbuf routines will return us something
1902 	 * with this alignment (perhaps should assert).
1903 	 */
1904 	m = ieee80211_beacon_alloc(ic, ni, &sc->sc_boff);
1905 	if (m == NULL) {
1906 		DPRINTF(sc, ATH_DEBUG_BEACON, "%s: cannot get mbuf\n",
1907 			__func__);
1908 		sc->sc_stats.ast_be_nombuf++;
1909 		return ENOMEM;
1910 	}
1911 	error = bus_dmamap_load_mbuf_sg(sc->sc_dmat, bf->bf_dmamap, m,
1912 				     bf->bf_segs, &bf->bf_nseg,
1913 				     BUS_DMA_NOWAIT);
1914 	if (error == 0) {
1915 		bf->bf_m = m;
1916 		bf->bf_node = ieee80211_ref_node(ni);
1917 	} else {
1918 		m_freem(m);
1919 	}
1920 	return error;
1921 }
1922 
1923 /*
1924  * Setup the beacon frame for transmit.
1925  */
1926 static void
1927 ath_beacon_setup(struct ath_softc *sc, struct ath_buf *bf)
1928 {
1929 #define	USE_SHPREAMBLE(_ic) \
1930 	(((_ic)->ic_flags & (IEEE80211_F_SHPREAMBLE | IEEE80211_F_USEBARKER))\
1931 		== IEEE80211_F_SHPREAMBLE)
1932 	struct ieee80211_node *ni = bf->bf_node;
1933 	struct ieee80211com *ic = ni->ni_ic;
1934 	struct mbuf *m = bf->bf_m;
1935 	struct ath_hal *ah = sc->sc_ah;
1936 	struct ath_desc *ds;
1937 	int flags, antenna;
1938 	const HAL_RATE_TABLE *rt;
1939 	u_int8_t rix, rate;
1940 
1941 	DPRINTF(sc, ATH_DEBUG_BEACON_PROC, "%s: m %p len %u\n",
1942 		__func__, m, m->m_len);
1943 
1944 	/* setup descriptors */
1945 	ds = bf->bf_desc;
1946 
1947 	flags = HAL_TXDESC_NOACK;
1948 	if (ic->ic_opmode == IEEE80211_M_IBSS && sc->sc_hasveol) {
1949 		ds->ds_link = bf->bf_daddr;	/* self-linked */
1950 		flags |= HAL_TXDESC_VEOL;
1951 		/*
1952 		 * Let hardware handle antenna switching.
1953 		 */
1954 		antenna = sc->sc_txantenna;
1955 	} else {
1956 		ds->ds_link = 0;
1957 		/*
1958 		 * Switch antenna every 4 beacons.
1959 		 * XXX assumes two antenna
1960 		 */
1961 		antenna = sc->sc_txantenna != 0 ? sc->sc_txantenna
1962 			: (sc->sc_stats.ast_be_xmit & 4 ? 2 : 1);
1963 	}
1964 
1965 	KASSERT(bf->bf_nseg == 1,
1966 		("multi-segment beacon frame; nseg %u", bf->bf_nseg));
1967 	ds->ds_data = bf->bf_segs[0].ds_addr;
1968 	/*
1969 	 * Calculate rate code.
1970 	 * XXX everything at min xmit rate
1971 	 */
1972 	rix = sc->sc_minrateix;
1973 	rt = sc->sc_currates;
1974 	rate = rt->info[rix].rateCode;
1975 	if (USE_SHPREAMBLE(ic))
1976 		rate |= rt->info[rix].shortPreamble;
1977 	ath_hal_setuptxdesc(ah, ds
1978 		, m->m_len + IEEE80211_CRC_LEN	/* frame length */
1979 		, sizeof(struct ieee80211_frame)/* header length */
1980 		, HAL_PKT_TYPE_BEACON		/* Atheros packet type */
1981 		, ni->ni_txpower		/* txpower XXX */
1982 		, rate, 1			/* series 0 rate/tries */
1983 		, HAL_TXKEYIX_INVALID		/* no encryption */
1984 		, antenna			/* antenna mode */
1985 		, flags				/* no ack, veol for beacons */
1986 		, 0				/* rts/cts rate */
1987 		, 0				/* rts/cts duration */
1988 	);
1989 	/* NB: beacon's BufLen must be a multiple of 4 bytes */
1990 	ath_hal_filltxdesc(ah, ds
1991 		, roundup(m->m_len, 4)		/* buffer length */
1992 		, AH_TRUE			/* first segment */
1993 		, AH_TRUE			/* last segment */
1994 		, ds				/* first descriptor */
1995 	);
1996 #undef USE_SHPREAMBLE
1997 }
1998 
1999 /*
2000  * Append the contents of src to dst; both queues
2001  * are assumed to be locked.
2002  */
2003 static void
2004 ath_txqmove(struct ath_txq *dst, struct ath_txq *src)
2005 {
2006 	STAILQ_CONCAT(&dst->axq_q, &src->axq_q);
2007 	dst->axq_link = src->axq_link;
2008 	src->axq_link = NULL;
2009 	dst->axq_depth += src->axq_depth;
2010 	src->axq_depth = 0;
2011 }
2012 
2013 /*
2014  * Transmit a beacon frame at SWBA.  Dynamic updates to the
2015  * frame contents are done as needed and the slot time is
2016  * also adjusted based on current state.
2017  */
2018 static void
2019 ath_beacon_proc(void *arg, int pending)
2020 {
2021 	struct ath_softc *sc = arg;
2022 	struct ath_buf *bf = STAILQ_FIRST(&sc->sc_bbuf);
2023 	struct ieee80211_node *ni = bf->bf_node;
2024 	struct ieee80211com *ic = ni->ni_ic;
2025 	struct ath_hal *ah = sc->sc_ah;
2026 	struct ath_txq *cabq = sc->sc_cabq;
2027 	struct mbuf *m;
2028 	int ncabq, nmcastq, error, otherant;
2029 
2030 	DPRINTF(sc, ATH_DEBUG_BEACON_PROC, "%s: pending %u\n",
2031 		__func__, pending);
2032 
2033 	if (ic->ic_opmode == IEEE80211_M_STA ||
2034 	    ic->ic_opmode == IEEE80211_M_MONITOR ||
2035 	    bf == NULL || bf->bf_m == NULL) {
2036 		DPRINTF(sc, ATH_DEBUG_ANY, "%s: ic_flags=%x bf=%p bf_m=%p\n",
2037 			__func__, ic->ic_flags, bf, bf ? bf->bf_m : NULL);
2038 		return;
2039 	}
2040 	/*
2041 	 * Check if the previous beacon has gone out.  If
2042 	 * not don't try to post another, skip this period
2043 	 * and wait for the next.  Missed beacons indicate
2044 	 * a problem and should not occur.  If we miss too
2045 	 * many consecutive beacons reset the device.
2046 	 */
2047 	if (ath_hal_numtxpending(ah, sc->sc_bhalq) != 0) {
2048 		sc->sc_bmisscount++;
2049 		DPRINTF(sc, ATH_DEBUG_BEACON,
2050 			"%s: missed %u consecutive beacons\n",
2051 			__func__, sc->sc_bmisscount);
2052 		if (sc->sc_bmisscount > 3)		/* NB: 3 is a guess */
2053 			taskqueue_enqueue(sc->sc_tq, &sc->sc_bstucktask);
2054 		return;
2055 	}
2056 	if (sc->sc_bmisscount != 0) {
2057 		DPRINTF(sc, ATH_DEBUG_BEACON,
2058 			"%s: resume beacon xmit after %u misses\n",
2059 			__func__, sc->sc_bmisscount);
2060 		sc->sc_bmisscount = 0;
2061 	}
2062 
2063 	/*
2064 	 * Update dynamic beacon contents.  If this returns
2065 	 * non-zero then we need to remap the memory because
2066 	 * the beacon frame changed size (probably because
2067 	 * of the TIM bitmap).
2068 	 */
2069 	m = bf->bf_m;
2070 	nmcastq = sc->sc_mcastq.axq_depth;
2071 	ncabq = ath_hal_numtxpending(ah, cabq->axq_qnum);
2072 	if (ieee80211_beacon_update(ic, bf->bf_node, &sc->sc_boff, m, ncabq+nmcastq)) {
2073 		/* XXX too conservative? */
2074 		bus_dmamap_unload(sc->sc_dmat, bf->bf_dmamap);
2075 		error = bus_dmamap_load_mbuf_sg(sc->sc_dmat, bf->bf_dmamap, m,
2076 					     bf->bf_segs, &bf->bf_nseg,
2077 					     BUS_DMA_NOWAIT);
2078 		if (error != 0) {
2079 			if_printf(ic->ic_ifp,
2080 			    "%s: bus_dmamap_load_mbuf_sg failed, error %u\n",
2081 			    __func__, error);
2082 			return;
2083 		}
2084 	}
2085 	if (ncabq && (sc->sc_boff.bo_tim[4] & 1)) {
2086 		/*
2087 		 * CABQ traffic from the previous DTIM is still pending.
2088 		 * This is ok for now but when there are multiple vap's
2089 		 * and we are using staggered beacons we'll want to drain
2090 		 * the cabq before loading frames for the different vap.
2091 		 */
2092 		DPRINTF(sc, ATH_DEBUG_BEACON,
2093 		    "%s: cabq did not drain, mcastq %u cabq %u/%u\n",
2094 		    __func__, nmcastq, ncabq, cabq->axq_depth);
2095 		sc->sc_stats.ast_cabq_busy++;
2096 	}
2097 
2098 	/*
2099 	 * Handle slot time change when a non-ERP station joins/leaves
2100 	 * an 11g network.  The 802.11 layer notifies us via callback,
2101 	 * we mark updateslot, then wait one beacon before effecting
2102 	 * the change.  This gives associated stations at least one
2103 	 * beacon interval to note the state change.
2104 	 */
2105 	/* XXX locking */
2106 	if (sc->sc_updateslot == UPDATE)
2107 		sc->sc_updateslot = COMMIT;	/* commit next beacon */
2108 	else if (sc->sc_updateslot == COMMIT)
2109 		ath_setslottime(sc);		/* commit change to h/w */
2110 
2111 	/*
2112 	 * Check recent per-antenna transmit statistics and flip
2113 	 * the default antenna if noticeably more frames went out
2114 	 * on the non-default antenna.
2115 	 * XXX assumes 2 anntenae
2116 	 */
2117 	otherant = sc->sc_defant & 1 ? 2 : 1;
2118 	if (sc->sc_ant_tx[otherant] > sc->sc_ant_tx[sc->sc_defant] + 2)
2119 		ath_setdefantenna(sc, otherant);
2120 	sc->sc_ant_tx[1] = sc->sc_ant_tx[2] = 0;
2121 
2122 	/*
2123 	 * Construct tx descriptor.
2124 	 */
2125 	ath_beacon_setup(sc, bf);
2126 
2127 	/*
2128 	 * Stop any current dma and put the new frame on the queue.
2129 	 * This should never fail since we check above that no frames
2130 	 * are still pending on the queue.
2131 	 */
2132 	if (!ath_hal_stoptxdma(ah, sc->sc_bhalq)) {
2133 		DPRINTF(sc, ATH_DEBUG_ANY,
2134 			"%s: beacon queue %u did not stop?\n",
2135 			__func__, sc->sc_bhalq);
2136 	}
2137 	bus_dmamap_sync(sc->sc_dmat, bf->bf_dmamap, BUS_DMASYNC_PREWRITE);
2138 
2139 	/*
2140 	 * Enable the CAB queue before the beacon queue to
2141 	 * insure cab frames are triggered by this beacon.
2142 	 */
2143 	if (sc->sc_boff.bo_tim_len && (sc->sc_boff.bo_tim[4] & 1)) {
2144 		/* NB: only at DTIM */
2145 		ATH_TXQ_LOCK(cabq);
2146 		ATH_TXQ_LOCK(&sc->sc_mcastq);
2147 		if (nmcastq) {
2148 			struct ath_buf *bfm;
2149 
2150 			/*
2151 			 * Move frames from the s/w mcast q to the h/w cab q.
2152 			 */
2153 			bfm = STAILQ_FIRST(&sc->sc_mcastq.axq_q);
2154 			if (cabq->axq_link != NULL) {
2155 				*cabq->axq_link = bfm->bf_daddr;
2156 			} else
2157 				ath_hal_puttxbuf(ah, cabq->axq_qnum,
2158 					bfm->bf_daddr);
2159 			ath_txqmove(cabq, &sc->sc_mcastq);
2160 
2161 			sc->sc_stats.ast_cabq_xmit += nmcastq;
2162 		}
2163 		/* NB: gated by beacon so safe to start here */
2164 		ath_hal_txstart(ah, cabq->axq_qnum);
2165 		ATH_TXQ_UNLOCK(cabq);
2166 		ATH_TXQ_UNLOCK(&sc->sc_mcastq);
2167 	}
2168 	ath_hal_puttxbuf(ah, sc->sc_bhalq, bf->bf_daddr);
2169 	ath_hal_txstart(ah, sc->sc_bhalq);
2170 	DPRINTF(sc, ATH_DEBUG_BEACON_PROC,
2171 		"%s: TXDP[%u] = %p (%p)\n", __func__,
2172 		sc->sc_bhalq, (caddr_t)bf->bf_daddr, bf->bf_desc);
2173 
2174 	sc->sc_stats.ast_be_xmit++;
2175 }
2176 
2177 /*
2178  * Reset the hardware after detecting beacons have stopped.
2179  */
2180 static void
2181 ath_bstuck_proc(void *arg, int pending)
2182 {
2183 	struct ath_softc *sc = arg;
2184 	struct ifnet *ifp = sc->sc_ifp;
2185 
2186 	if_printf(ifp, "stuck beacon; resetting (bmiss count %u)\n",
2187 		sc->sc_bmisscount);
2188 	ath_reset(ifp);
2189 }
2190 
2191 /*
2192  * Reclaim beacon resources.
2193  */
2194 static void
2195 ath_beacon_free(struct ath_softc *sc)
2196 {
2197 	struct ath_buf *bf;
2198 
2199 	STAILQ_FOREACH(bf, &sc->sc_bbuf, bf_list) {
2200 		if (bf->bf_m != NULL) {
2201 			bus_dmamap_unload(sc->sc_dmat, bf->bf_dmamap);
2202 			m_freem(bf->bf_m);
2203 			bf->bf_m = NULL;
2204 		}
2205 		if (bf->bf_node != NULL) {
2206 			ieee80211_free_node(bf->bf_node);
2207 			bf->bf_node = NULL;
2208 		}
2209 	}
2210 }
2211 
2212 /*
2213  * Configure the beacon and sleep timers.
2214  *
2215  * When operating as an AP this resets the TSF and sets
2216  * up the hardware to notify us when we need to issue beacons.
2217  *
2218  * When operating in station mode this sets up the beacon
2219  * timers according to the timestamp of the last received
2220  * beacon and the current TSF, configures PCF and DTIM
2221  * handling, programs the sleep registers so the hardware
2222  * will wakeup in time to receive beacons, and configures
2223  * the beacon miss handling so we'll receive a BMISS
2224  * interrupt when we stop seeing beacons from the AP
2225  * we've associated with.
2226  */
2227 static void
2228 ath_beacon_config(struct ath_softc *sc)
2229 {
2230 #define	TSF_TO_TU(_h,_l) \
2231 	((((u_int32_t)(_h)) << 22) | (((u_int32_t)(_l)) >> 10))
2232 #define	FUDGE	2
2233 	struct ath_hal *ah = sc->sc_ah;
2234 	struct ieee80211com *ic = &sc->sc_ic;
2235 	struct ieee80211_node *ni = ic->ic_bss;
2236 	u_int32_t nexttbtt, intval, tsftu;
2237 	u_int64_t tsf;
2238 
2239 	/* extract tstamp from last beacon and convert to TU */
2240 	nexttbtt = TSF_TO_TU(LE_READ_4(ni->ni_tstamp.data + 4),
2241 			     LE_READ_4(ni->ni_tstamp.data));
2242 	/* NB: the beacon interval is kept internally in TU's */
2243 	intval = ni->ni_intval & HAL_BEACON_PERIOD;
2244 	if (nexttbtt == 0)		/* e.g. for ap mode */
2245 		nexttbtt = intval;
2246 	else if (intval)		/* NB: can be 0 for monitor mode */
2247 		nexttbtt = roundup(nexttbtt, intval);
2248 	DPRINTF(sc, ATH_DEBUG_BEACON, "%s: nexttbtt %u intval %u (%u)\n",
2249 		__func__, nexttbtt, intval, ni->ni_intval);
2250 	if (ic->ic_opmode == IEEE80211_M_STA) {
2251 		HAL_BEACON_STATE bs;
2252 		int dtimperiod, dtimcount;
2253 		int cfpperiod, cfpcount;
2254 
2255 		/*
2256 		 * Setup dtim and cfp parameters according to
2257 		 * last beacon we received (which may be none).
2258 		 */
2259 		dtimperiod = ni->ni_dtim_period;
2260 		if (dtimperiod <= 0)		/* NB: 0 if not known */
2261 			dtimperiod = 1;
2262 		dtimcount = ni->ni_dtim_count;
2263 		if (dtimcount >= dtimperiod)	/* NB: sanity check */
2264 			dtimcount = 0;		/* XXX? */
2265 		cfpperiod = 1;			/* NB: no PCF support yet */
2266 		cfpcount = 0;
2267 		/*
2268 		 * Pull nexttbtt forward to reflect the current
2269 		 * TSF and calculate dtim+cfp state for the result.
2270 		 */
2271 		tsf = ath_hal_gettsf64(ah);
2272 		tsftu = TSF_TO_TU(tsf>>32, tsf) + FUDGE;
2273 		do {
2274 			nexttbtt += intval;
2275 			if (--dtimcount < 0) {
2276 				dtimcount = dtimperiod - 1;
2277 				if (--cfpcount < 0)
2278 					cfpcount = cfpperiod - 1;
2279 			}
2280 		} while (nexttbtt < tsftu);
2281 		memset(&bs, 0, sizeof(bs));
2282 		bs.bs_intval = intval;
2283 		bs.bs_nexttbtt = nexttbtt;
2284 		bs.bs_dtimperiod = dtimperiod*intval;
2285 		bs.bs_nextdtim = bs.bs_nexttbtt + dtimcount*intval;
2286 		bs.bs_cfpperiod = cfpperiod*bs.bs_dtimperiod;
2287 		bs.bs_cfpnext = bs.bs_nextdtim + cfpcount*bs.bs_dtimperiod;
2288 		bs.bs_cfpmaxduration = 0;
2289 #if 0
2290 		/*
2291 		 * The 802.11 layer records the offset to the DTIM
2292 		 * bitmap while receiving beacons; use it here to
2293 		 * enable h/w detection of our AID being marked in
2294 		 * the bitmap vector (to indicate frames for us are
2295 		 * pending at the AP).
2296 		 * XXX do DTIM handling in s/w to WAR old h/w bugs
2297 		 * XXX enable based on h/w rev for newer chips
2298 		 */
2299 		bs.bs_timoffset = ni->ni_timoff;
2300 #endif
2301 		/*
2302 		 * Calculate the number of consecutive beacons to miss
2303 		 * before taking a BMISS interrupt.  The configuration
2304 		 * is specified in ms, so we need to convert that to
2305 		 * TU's and then calculate based on the beacon interval.
2306 		 * Note that we clamp the result to at most 10 beacons.
2307 		 */
2308 		bs.bs_bmissthreshold = ic->ic_bmissthreshold;
2309 		if (bs.bs_bmissthreshold > 10)
2310 			bs.bs_bmissthreshold = 10;
2311 		else if (bs.bs_bmissthreshold <= 0)
2312 			bs.bs_bmissthreshold = 1;
2313 
2314 		/*
2315 		 * Calculate sleep duration.  The configuration is
2316 		 * given in ms.  We insure a multiple of the beacon
2317 		 * period is used.  Also, if the sleep duration is
2318 		 * greater than the DTIM period then it makes senses
2319 		 * to make it a multiple of that.
2320 		 *
2321 		 * XXX fixed at 100ms
2322 		 */
2323 		bs.bs_sleepduration =
2324 			roundup(IEEE80211_MS_TO_TU(100), bs.bs_intval);
2325 		if (bs.bs_sleepduration > bs.bs_dtimperiod)
2326 			bs.bs_sleepduration = roundup(bs.bs_sleepduration, bs.bs_dtimperiod);
2327 
2328 		DPRINTF(sc, ATH_DEBUG_BEACON,
2329 			"%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"
2330 			, __func__
2331 			, tsf, tsftu
2332 			, bs.bs_intval
2333 			, bs.bs_nexttbtt
2334 			, bs.bs_dtimperiod
2335 			, bs.bs_nextdtim
2336 			, bs.bs_bmissthreshold
2337 			, bs.bs_sleepduration
2338 			, bs.bs_cfpperiod
2339 			, bs.bs_cfpmaxduration
2340 			, bs.bs_cfpnext
2341 			, bs.bs_timoffset
2342 		);
2343 		ath_hal_intrset(ah, 0);
2344 		ath_hal_beacontimers(ah, &bs);
2345 		sc->sc_imask |= HAL_INT_BMISS;
2346 		ath_hal_intrset(ah, sc->sc_imask);
2347 	} else {
2348 		ath_hal_intrset(ah, 0);
2349 		if (nexttbtt == intval)
2350 			intval |= HAL_BEACON_RESET_TSF;
2351 		if (ic->ic_opmode == IEEE80211_M_IBSS) {
2352 			/*
2353 			 * In IBSS mode enable the beacon timers but only
2354 			 * enable SWBA interrupts if we need to manually
2355 			 * prepare beacon frames.  Otherwise we use a
2356 			 * self-linked tx descriptor and let the hardware
2357 			 * deal with things.
2358 			 */
2359 			intval |= HAL_BEACON_ENA;
2360 			if (!sc->sc_hasveol)
2361 				sc->sc_imask |= HAL_INT_SWBA;
2362 			if ((intval & HAL_BEACON_RESET_TSF) == 0) {
2363 				/*
2364 				 * Pull nexttbtt forward to reflect
2365 				 * the current TSF.
2366 				 */
2367 				tsf = ath_hal_gettsf64(ah);
2368 				tsftu = TSF_TO_TU(tsf>>32, tsf) + FUDGE;
2369 				do {
2370 					nexttbtt += intval;
2371 				} while (nexttbtt < tsftu);
2372 			}
2373 			ath_beaconq_config(sc);
2374 		} else if (ic->ic_opmode == IEEE80211_M_HOSTAP) {
2375 			/*
2376 			 * In AP mode we enable the beacon timers and
2377 			 * SWBA interrupts to prepare beacon frames.
2378 			 */
2379 			intval |= HAL_BEACON_ENA;
2380 			sc->sc_imask |= HAL_INT_SWBA;	/* beacon prepare */
2381 			ath_beaconq_config(sc);
2382 		}
2383 		ath_hal_beaconinit(ah, nexttbtt, intval);
2384 		sc->sc_bmisscount = 0;
2385 		ath_hal_intrset(ah, sc->sc_imask);
2386 		/*
2387 		 * When using a self-linked beacon descriptor in
2388 		 * ibss mode load it once here.
2389 		 */
2390 		if (ic->ic_opmode == IEEE80211_M_IBSS && sc->sc_hasveol)
2391 			ath_beacon_proc(sc, 0);
2392 	}
2393 	sc->sc_syncbeacon = 0;
2394 #undef FUDGE
2395 #undef TSF_TO_TU
2396 }
2397 
2398 static void
2399 ath_load_cb(void *arg, bus_dma_segment_t *segs, int nsegs, int error)
2400 {
2401 	bus_addr_t *paddr = (bus_addr_t*) arg;
2402 	KASSERT(error == 0, ("error %u on bus_dma callback", error));
2403 	*paddr = segs->ds_addr;
2404 }
2405 
2406 static int
2407 ath_descdma_setup(struct ath_softc *sc,
2408 	struct ath_descdma *dd, ath_bufhead *head,
2409 	const char *name, int nbuf, int ndesc)
2410 {
2411 #define	DS2PHYS(_dd, _ds) \
2412 	((_dd)->dd_desc_paddr + ((caddr_t)(_ds) - (caddr_t)(_dd)->dd_desc))
2413 	struct ifnet *ifp = sc->sc_ifp;
2414 	struct ath_desc *ds;
2415 	struct ath_buf *bf;
2416 	int i, bsize, error;
2417 
2418 	DPRINTF(sc, ATH_DEBUG_RESET, "%s: %s DMA: %u buffers %u desc/buf\n",
2419 	    __func__, name, nbuf, ndesc);
2420 
2421 	dd->dd_name = name;
2422 	dd->dd_desc_len = sizeof(struct ath_desc) * nbuf * ndesc;
2423 
2424 	/*
2425 	 * Setup DMA descriptor area.
2426 	 */
2427 	error = bus_dma_tag_create(NULL,	/* parent */
2428 		       PAGE_SIZE, 0,		/* alignment, bounds */
2429 		       BUS_SPACE_MAXADDR_32BIT,	/* lowaddr */
2430 		       BUS_SPACE_MAXADDR,	/* highaddr */
2431 		       NULL, NULL,		/* filter, filterarg */
2432 		       dd->dd_desc_len,		/* maxsize */
2433 		       1,			/* nsegments */
2434 		       dd->dd_desc_len,		/* maxsegsize */
2435 		       BUS_DMA_ALLOCNOW,	/* flags */
2436 		       NULL,			/* lockfunc */
2437 		       NULL,			/* lockarg */
2438 		       &dd->dd_dmat);
2439 	if (error != 0) {
2440 		if_printf(ifp, "cannot allocate %s DMA tag\n", dd->dd_name);
2441 		return error;
2442 	}
2443 
2444 	/* allocate descriptors */
2445 	error = bus_dmamap_create(dd->dd_dmat, BUS_DMA_NOWAIT, &dd->dd_dmamap);
2446 	if (error != 0) {
2447 		if_printf(ifp, "unable to create dmamap for %s descriptors, "
2448 			"error %u\n", dd->dd_name, error);
2449 		goto fail0;
2450 	}
2451 
2452 	error = bus_dmamem_alloc(dd->dd_dmat, (void**) &dd->dd_desc,
2453 				 BUS_DMA_NOWAIT, &dd->dd_dmamap);
2454 	if (error != 0) {
2455 		if_printf(ifp, "unable to alloc memory for %u %s descriptors, "
2456 			"error %u\n", nbuf * ndesc, dd->dd_name, error);
2457 		goto fail1;
2458 	}
2459 
2460 	error = bus_dmamap_load(dd->dd_dmat, dd->dd_dmamap,
2461 				dd->dd_desc, dd->dd_desc_len,
2462 				ath_load_cb, &dd->dd_desc_paddr,
2463 				BUS_DMA_NOWAIT);
2464 	if (error != 0) {
2465 		if_printf(ifp, "unable to map %s descriptors, error %u\n",
2466 			dd->dd_name, error);
2467 		goto fail2;
2468 	}
2469 
2470 	ds = dd->dd_desc;
2471 	DPRINTF(sc, ATH_DEBUG_RESET, "%s: %s DMA map: %p (%lu) -> %p (%lu)\n",
2472 	    __func__, dd->dd_name, ds, (u_long) dd->dd_desc_len,
2473 	    (caddr_t) dd->dd_desc_paddr, /*XXX*/ (u_long) dd->dd_desc_len);
2474 
2475 	/* allocate rx buffers */
2476 	bsize = sizeof(struct ath_buf) * nbuf;
2477 	bf = malloc(bsize, M_ATHDEV, M_NOWAIT | M_ZERO);
2478 	if (bf == NULL) {
2479 		if_printf(ifp, "malloc of %s buffers failed, size %u\n",
2480 			dd->dd_name, bsize);
2481 		goto fail3;
2482 	}
2483 	dd->dd_bufptr = bf;
2484 
2485 	STAILQ_INIT(head);
2486 	for (i = 0; i < nbuf; i++, bf++, ds += ndesc) {
2487 		bf->bf_desc = ds;
2488 		bf->bf_daddr = DS2PHYS(dd, ds);
2489 		error = bus_dmamap_create(sc->sc_dmat, BUS_DMA_NOWAIT,
2490 				&bf->bf_dmamap);
2491 		if (error != 0) {
2492 			if_printf(ifp, "unable to create dmamap for %s "
2493 				"buffer %u, error %u\n", dd->dd_name, i, error);
2494 			ath_descdma_cleanup(sc, dd, head);
2495 			return error;
2496 		}
2497 		STAILQ_INSERT_TAIL(head, bf, bf_list);
2498 	}
2499 	return 0;
2500 fail3:
2501 	bus_dmamap_unload(dd->dd_dmat, dd->dd_dmamap);
2502 fail2:
2503 	bus_dmamem_free(dd->dd_dmat, dd->dd_desc, dd->dd_dmamap);
2504 fail1:
2505 	bus_dmamap_destroy(dd->dd_dmat, dd->dd_dmamap);
2506 fail0:
2507 	bus_dma_tag_destroy(dd->dd_dmat);
2508 	memset(dd, 0, sizeof(*dd));
2509 	return error;
2510 #undef DS2PHYS
2511 }
2512 
2513 static void
2514 ath_descdma_cleanup(struct ath_softc *sc,
2515 	struct ath_descdma *dd, ath_bufhead *head)
2516 {
2517 	struct ath_buf *bf;
2518 	struct ieee80211_node *ni;
2519 
2520 	bus_dmamap_unload(dd->dd_dmat, dd->dd_dmamap);
2521 	bus_dmamem_free(dd->dd_dmat, dd->dd_desc, dd->dd_dmamap);
2522 	bus_dmamap_destroy(dd->dd_dmat, dd->dd_dmamap);
2523 	bus_dma_tag_destroy(dd->dd_dmat);
2524 
2525 	STAILQ_FOREACH(bf, head, bf_list) {
2526 		if (bf->bf_m) {
2527 			m_freem(bf->bf_m);
2528 			bf->bf_m = NULL;
2529 		}
2530 		if (bf->bf_dmamap != NULL) {
2531 			bus_dmamap_destroy(sc->sc_dmat, bf->bf_dmamap);
2532 			bf->bf_dmamap = NULL;
2533 		}
2534 		ni = bf->bf_node;
2535 		bf->bf_node = NULL;
2536 		if (ni != NULL) {
2537 			/*
2538 			 * Reclaim node reference.
2539 			 */
2540 			ieee80211_free_node(ni);
2541 		}
2542 	}
2543 
2544 	STAILQ_INIT(head);
2545 	free(dd->dd_bufptr, M_ATHDEV);
2546 	memset(dd, 0, sizeof(*dd));
2547 }
2548 
2549 static int
2550 ath_desc_alloc(struct ath_softc *sc)
2551 {
2552 	int error;
2553 
2554 	error = ath_descdma_setup(sc, &sc->sc_rxdma, &sc->sc_rxbuf,
2555 			"rx", ath_rxbuf, 1);
2556 	if (error != 0)
2557 		return error;
2558 
2559 	error = ath_descdma_setup(sc, &sc->sc_txdma, &sc->sc_txbuf,
2560 			"tx", ath_txbuf, ATH_TXDESC);
2561 	if (error != 0) {
2562 		ath_descdma_cleanup(sc, &sc->sc_rxdma, &sc->sc_rxbuf);
2563 		return error;
2564 	}
2565 
2566 	error = ath_descdma_setup(sc, &sc->sc_bdma, &sc->sc_bbuf,
2567 			"beacon", 1, 1);
2568 	if (error != 0) {
2569 		ath_descdma_cleanup(sc, &sc->sc_txdma, &sc->sc_txbuf);
2570 		ath_descdma_cleanup(sc, &sc->sc_rxdma, &sc->sc_rxbuf);
2571 		return error;
2572 	}
2573 	return 0;
2574 }
2575 
2576 static void
2577 ath_desc_free(struct ath_softc *sc)
2578 {
2579 
2580 	if (sc->sc_bdma.dd_desc_len != 0)
2581 		ath_descdma_cleanup(sc, &sc->sc_bdma, &sc->sc_bbuf);
2582 	if (sc->sc_txdma.dd_desc_len != 0)
2583 		ath_descdma_cleanup(sc, &sc->sc_txdma, &sc->sc_txbuf);
2584 	if (sc->sc_rxdma.dd_desc_len != 0)
2585 		ath_descdma_cleanup(sc, &sc->sc_rxdma, &sc->sc_rxbuf);
2586 }
2587 
2588 static struct ieee80211_node *
2589 ath_node_alloc(struct ieee80211_node_table *nt)
2590 {
2591 	struct ieee80211com *ic = nt->nt_ic;
2592 	struct ath_softc *sc = ic->ic_ifp->if_softc;
2593 	const size_t space = sizeof(struct ath_node) + sc->sc_rc->arc_space;
2594 	struct ath_node *an;
2595 
2596 	an = malloc(space, M_80211_NODE, M_NOWAIT|M_ZERO);
2597 	if (an == NULL) {
2598 		/* XXX stat+msg */
2599 		return NULL;
2600 	}
2601 	an->an_avgrssi = ATH_RSSI_DUMMY_MARKER;
2602 	ath_rate_node_init(sc, an);
2603 
2604 	DPRINTF(sc, ATH_DEBUG_NODE, "%s: an %p\n", __func__, an);
2605 	return &an->an_node;
2606 }
2607 
2608 static void
2609 ath_node_free(struct ieee80211_node *ni)
2610 {
2611 	struct ieee80211com *ic = ni->ni_ic;
2612         struct ath_softc *sc = ic->ic_ifp->if_softc;
2613 
2614 	DPRINTF(sc, ATH_DEBUG_NODE, "%s: ni %p\n", __func__, ni);
2615 
2616 	ath_rate_node_cleanup(sc, ATH_NODE(ni));
2617 	sc->sc_node_free(ni);
2618 }
2619 
2620 static u_int8_t
2621 ath_node_getrssi(const struct ieee80211_node *ni)
2622 {
2623 #define	HAL_EP_RND(x, mul) \
2624 	((((x)%(mul)) >= ((mul)/2)) ? ((x) + ((mul) - 1)) / (mul) : (x)/(mul))
2625 	u_int32_t avgrssi = ATH_NODE_CONST(ni)->an_avgrssi;
2626 	int32_t rssi;
2627 
2628 	/*
2629 	 * When only one frame is received there will be no state in
2630 	 * avgrssi so fallback on the value recorded by the 802.11 layer.
2631 	 */
2632 	if (avgrssi != ATH_RSSI_DUMMY_MARKER)
2633 		rssi = HAL_EP_RND(avgrssi, HAL_RSSI_EP_MULTIPLIER);
2634 	else
2635 		rssi = ni->ni_rssi;
2636 	return rssi < 0 ? 0 : rssi > 127 ? 127 : rssi;
2637 #undef HAL_EP_RND
2638 }
2639 
2640 static int
2641 ath_rxbuf_init(struct ath_softc *sc, struct ath_buf *bf)
2642 {
2643 	struct ath_hal *ah = sc->sc_ah;
2644 	int error;
2645 	struct mbuf *m;
2646 	struct ath_desc *ds;
2647 
2648 	m = bf->bf_m;
2649 	if (m == NULL) {
2650 		/*
2651 		 * NB: by assigning a page to the rx dma buffer we
2652 		 * implicitly satisfy the Atheros requirement that
2653 		 * this buffer be cache-line-aligned and sized to be
2654 		 * multiple of the cache line size.  Not doing this
2655 		 * causes weird stuff to happen (for the 5210 at least).
2656 		 */
2657 		m = m_getcl(M_DONTWAIT, MT_DATA, M_PKTHDR);
2658 		if (m == NULL) {
2659 			DPRINTF(sc, ATH_DEBUG_ANY,
2660 				"%s: no mbuf/cluster\n", __func__);
2661 			sc->sc_stats.ast_rx_nombuf++;
2662 			return ENOMEM;
2663 		}
2664 		m->m_pkthdr.len = m->m_len = m->m_ext.ext_size;
2665 
2666 		error = bus_dmamap_load_mbuf_sg(sc->sc_dmat,
2667 					     bf->bf_dmamap, m,
2668 					     bf->bf_segs, &bf->bf_nseg,
2669 					     BUS_DMA_NOWAIT);
2670 		if (error != 0) {
2671 			DPRINTF(sc, ATH_DEBUG_ANY,
2672 			    "%s: bus_dmamap_load_mbuf_sg failed; error %d\n",
2673 			    __func__, error);
2674 			sc->sc_stats.ast_rx_busdma++;
2675 			m_freem(m);
2676 			return error;
2677 		}
2678 		KASSERT(bf->bf_nseg == 1,
2679 			("multi-segment packet; nseg %u", bf->bf_nseg));
2680 		bf->bf_m = m;
2681 	}
2682 	bus_dmamap_sync(sc->sc_dmat, bf->bf_dmamap, BUS_DMASYNC_PREREAD);
2683 
2684 	/*
2685 	 * Setup descriptors.  For receive we always terminate
2686 	 * the descriptor list with a self-linked entry so we'll
2687 	 * not get overrun under high load (as can happen with a
2688 	 * 5212 when ANI processing enables PHY error frames).
2689 	 *
2690 	 * To insure the last descriptor is self-linked we create
2691 	 * each descriptor as self-linked and add it to the end.  As
2692 	 * each additional descriptor is added the previous self-linked
2693 	 * entry is ``fixed'' naturally.  This should be safe even
2694 	 * if DMA is happening.  When processing RX interrupts we
2695 	 * never remove/process the last, self-linked, entry on the
2696 	 * descriptor list.  This insures the hardware always has
2697 	 * someplace to write a new frame.
2698 	 */
2699 	ds = bf->bf_desc;
2700 	ds->ds_link = bf->bf_daddr;	/* link to self */
2701 	ds->ds_data = bf->bf_segs[0].ds_addr;
2702 	ds->ds_vdata = mtod(m, void *);	/* for radar */
2703 	ath_hal_setuprxdesc(ah, ds
2704 		, m->m_len		/* buffer size */
2705 		, 0
2706 	);
2707 
2708 	if (sc->sc_rxlink != NULL)
2709 		*sc->sc_rxlink = bf->bf_daddr;
2710 	sc->sc_rxlink = &ds->ds_link;
2711 	return 0;
2712 }
2713 
2714 /*
2715  * Extend 15-bit time stamp from rx descriptor to
2716  * a full 64-bit TSF using the specified TSF.
2717  */
2718 static __inline u_int64_t
2719 ath_extend_tsf(u_int32_t rstamp, u_int64_t tsf)
2720 {
2721 	if ((tsf & 0x7fff) < rstamp)
2722 		tsf -= 0x8000;
2723 	return ((tsf &~ 0x7fff) | rstamp);
2724 }
2725 
2726 /*
2727  * Intercept management frames to collect beacon rssi data
2728  * and to do ibss merges.
2729  */
2730 static void
2731 ath_recv_mgmt(struct ieee80211com *ic, struct mbuf *m,
2732 	struct ieee80211_node *ni,
2733 	int subtype, int rssi, u_int32_t rstamp)
2734 {
2735 	struct ath_softc *sc = ic->ic_ifp->if_softc;
2736 
2737 	/*
2738 	 * Call up first so subsequent work can use information
2739 	 * potentially stored in the node (e.g. for ibss merge).
2740 	 */
2741 	sc->sc_recv_mgmt(ic, m, ni, subtype, rssi, rstamp);
2742 	switch (subtype) {
2743 	case IEEE80211_FC0_SUBTYPE_BEACON:
2744 		/* update rssi statistics for use by the hal */
2745 		ATH_RSSI_LPF(sc->sc_halstats.ns_avgbrssi, rssi);
2746 		if (sc->sc_syncbeacon &&
2747 		    ni == ic->ic_bss && ic->ic_state == IEEE80211_S_RUN) {
2748 			/*
2749 			 * Resync beacon timers using the tsf of the beacon
2750 			 * frame we just received.
2751 			 */
2752 			ath_beacon_config(sc);
2753 		}
2754 		/* fall thru... */
2755 	case IEEE80211_FC0_SUBTYPE_PROBE_RESP:
2756 		if (ic->ic_opmode == IEEE80211_M_IBSS &&
2757 		    ic->ic_state == IEEE80211_S_RUN) {
2758 			u_int64_t tsf = ath_extend_tsf(rstamp,
2759 				ath_hal_gettsf64(sc->sc_ah));
2760 			/*
2761 			 * Handle ibss merge as needed; check the tsf on the
2762 			 * frame before attempting the merge.  The 802.11 spec
2763 			 * says the station should change it's bssid to match
2764 			 * the oldest station with the same ssid, where oldest
2765 			 * is determined by the tsf.  Note that hardware
2766 			 * reconfiguration happens through callback to
2767 			 * ath_newstate as the state machine will go from
2768 			 * RUN -> RUN when this happens.
2769 			 */
2770 			if (le64toh(ni->ni_tstamp.tsf) >= tsf) {
2771 				DPRINTF(sc, ATH_DEBUG_STATE,
2772 				    "ibss merge, rstamp %u tsf %ju "
2773 				    "tstamp %ju\n", rstamp, (uintmax_t)tsf,
2774 				    (uintmax_t)ni->ni_tstamp.tsf);
2775 				(void) ieee80211_ibss_merge(ni);
2776 			}
2777 		}
2778 		break;
2779 	}
2780 }
2781 
2782 /*
2783  * Set the default antenna.
2784  */
2785 static void
2786 ath_setdefantenna(struct ath_softc *sc, u_int antenna)
2787 {
2788 	struct ath_hal *ah = sc->sc_ah;
2789 
2790 	/* XXX block beacon interrupts */
2791 	ath_hal_setdefantenna(ah, antenna);
2792 	if (sc->sc_defant != antenna)
2793 		sc->sc_stats.ast_ant_defswitch++;
2794 	sc->sc_defant = antenna;
2795 	sc->sc_rxotherant = 0;
2796 }
2797 
2798 static int
2799 ath_rx_tap(struct ath_softc *sc, struct mbuf *m,
2800 	const struct ath_desc *ds, u_int64_t tsf, int16_t nf)
2801 {
2802 	u_int8_t rix;
2803 
2804 	KASSERT(sc->sc_drvbpf != NULL, ("no tap"));
2805 
2806 	/*
2807 	 * Discard anything shorter than an ack or cts.
2808 	 */
2809 	if (m->m_pkthdr.len < IEEE80211_ACK_LEN) {
2810 		DPRINTF(sc, ATH_DEBUG_RECV, "%s: runt packet %d\n",
2811 			__func__, m->m_pkthdr.len);
2812 		sc->sc_stats.ast_rx_tooshort++;
2813 		return 0;
2814 	}
2815 	sc->sc_rx_th.wr_tsf = htole64(
2816 		ath_extend_tsf(ds->ds_rxstat.rs_tstamp, tsf));
2817 	rix = ds->ds_rxstat.rs_rate;
2818 	sc->sc_rx_th.wr_flags = sc->sc_hwmap[rix].rxflags;
2819 	if (ds->ds_rxstat.rs_status & HAL_RXERR_CRC)
2820 		sc->sc_rx_th.wr_flags |= IEEE80211_RADIOTAP_F_BADFCS;
2821 	/* XXX propagate other error flags from descriptor */
2822 	sc->sc_rx_th.wr_rate = sc->sc_hwmap[rix].ieeerate;
2823 	sc->sc_rx_th.wr_antsignal = ds->ds_rxstat.rs_rssi + nf;
2824 	sc->sc_rx_th.wr_antnoise = nf;
2825 	sc->sc_rx_th.wr_antenna = ds->ds_rxstat.rs_antenna;
2826 
2827 	bpf_mtap2(sc->sc_drvbpf, &sc->sc_rx_th, sc->sc_rx_th_len, m);
2828 
2829 	return 1;
2830 }
2831 
2832 static void
2833 ath_rx_proc(void *arg, int npending)
2834 {
2835 #define	PA2DESC(_sc, _pa) \
2836 	((struct ath_desc *)((caddr_t)(_sc)->sc_rxdma.dd_desc + \
2837 		((_pa) - (_sc)->sc_rxdma.dd_desc_paddr)))
2838 	struct ath_softc *sc = arg;
2839 	struct ath_buf *bf;
2840 	struct ieee80211com *ic = &sc->sc_ic;
2841 	struct ifnet *ifp = sc->sc_ifp;
2842 	struct ath_hal *ah = sc->sc_ah;
2843 	struct ath_desc *ds;
2844 	struct mbuf *m;
2845 	struct ieee80211_node *ni;
2846 	struct ath_node *an;
2847 	int len, type, ngood;
2848 	u_int phyerr;
2849 	HAL_STATUS status;
2850 	int16_t nf;
2851 	u_int64_t tsf;
2852 
2853 	NET_LOCK_GIANT();		/* XXX */
2854 
2855 	DPRINTF(sc, ATH_DEBUG_RX_PROC, "%s: pending %u\n", __func__, npending);
2856 	ngood = 0;
2857 	nf = ath_hal_getchannoise(ah, &sc->sc_curchan);
2858 	tsf = ath_hal_gettsf64(ah);
2859 	do {
2860 		bf = STAILQ_FIRST(&sc->sc_rxbuf);
2861 		if (bf == NULL) {		/* NB: shouldn't happen */
2862 			if_printf(ifp, "%s: no buffer!\n", __func__);
2863 			break;
2864 		}
2865 		m = bf->bf_m;
2866 		if (m == NULL) {		/* NB: shouldn't happen */
2867 			/*
2868 			 * If mbuf allocation failed previously there
2869 			 * will be no mbuf; try again to re-populate it.
2870 			 */
2871 			/* XXX make debug msg */
2872 			if_printf(ifp, "%s: no mbuf!\n", __func__);
2873 			STAILQ_REMOVE_HEAD(&sc->sc_rxbuf, bf_list);
2874 			goto rx_next;
2875 		}
2876 		ds = bf->bf_desc;
2877 		if (ds->ds_link == bf->bf_daddr) {
2878 			/* NB: never process the self-linked entry at the end */
2879 			break;
2880 		}
2881 		/* XXX sync descriptor memory */
2882 		/*
2883 		 * Must provide the virtual address of the current
2884 		 * descriptor, the physical address, and the virtual
2885 		 * address of the next descriptor in the h/w chain.
2886 		 * This allows the HAL to look ahead to see if the
2887 		 * hardware is done with a descriptor by checking the
2888 		 * done bit in the following descriptor and the address
2889 		 * of the current descriptor the DMA engine is working
2890 		 * on.  All this is necessary because of our use of
2891 		 * a self-linked list to avoid rx overruns.
2892 		 */
2893 		status = ath_hal_rxprocdesc(ah, ds,
2894 				bf->bf_daddr, PA2DESC(sc, ds->ds_link));
2895 #ifdef ATH_DEBUG
2896 		if (sc->sc_debug & ATH_DEBUG_RECV_DESC)
2897 			ath_printrxbuf(bf, 0, status == HAL_OK);
2898 #endif
2899 		if (status == HAL_EINPROGRESS)
2900 			break;
2901 		STAILQ_REMOVE_HEAD(&sc->sc_rxbuf, bf_list);
2902 		if (ds->ds_rxstat.rs_more) {
2903 			/*
2904 			 * Frame spans multiple descriptors; this
2905 			 * cannot happen yet as we don't support
2906 			 * jumbograms.  If not in monitor mode,
2907 			 * discard the frame.
2908 			 */
2909 			if (ic->ic_opmode != IEEE80211_M_MONITOR) {
2910 				sc->sc_stats.ast_rx_toobig++;
2911 				goto rx_next;
2912 			}
2913 			/* fall thru for monitor mode handling... */
2914 		} else if (ds->ds_rxstat.rs_status != 0) {
2915 			if (ds->ds_rxstat.rs_status & HAL_RXERR_CRC)
2916 				sc->sc_stats.ast_rx_crcerr++;
2917 			if (ds->ds_rxstat.rs_status & HAL_RXERR_FIFO)
2918 				sc->sc_stats.ast_rx_fifoerr++;
2919 			if (ds->ds_rxstat.rs_status & HAL_RXERR_PHY) {
2920 				sc->sc_stats.ast_rx_phyerr++;
2921 				phyerr = ds->ds_rxstat.rs_phyerr & 0x1f;
2922 				sc->sc_stats.ast_rx_phy[phyerr]++;
2923 				goto rx_next;
2924 			}
2925 			if (ds->ds_rxstat.rs_status & HAL_RXERR_DECRYPT) {
2926 				/*
2927 				 * Decrypt error.  If the error occurred
2928 				 * because there was no hardware key, then
2929 				 * let the frame through so the upper layers
2930 				 * can process it.  This is necessary for 5210
2931 				 * parts which have no way to setup a ``clear''
2932 				 * key cache entry.
2933 				 *
2934 				 * XXX do key cache faulting
2935 				 */
2936 				if (ds->ds_rxstat.rs_keyix == HAL_RXKEYIX_INVALID)
2937 					goto rx_accept;
2938 				sc->sc_stats.ast_rx_badcrypt++;
2939 			}
2940 			if (ds->ds_rxstat.rs_status & HAL_RXERR_MIC) {
2941 				sc->sc_stats.ast_rx_badmic++;
2942 				/*
2943 				 * Do minimal work required to hand off
2944 				 * the 802.11 header for notifcation.
2945 				 */
2946 				/* XXX frag's and qos frames */
2947 				len = ds->ds_rxstat.rs_datalen;
2948 				if (len >= sizeof (struct ieee80211_frame)) {
2949 					bus_dmamap_sync(sc->sc_dmat,
2950 					    bf->bf_dmamap,
2951 					    BUS_DMASYNC_POSTREAD);
2952 					ieee80211_notify_michael_failure(ic,
2953 					    mtod(m, struct ieee80211_frame *),
2954 					    sc->sc_splitmic ?
2955 					        ds->ds_rxstat.rs_keyix-32 :
2956 					        ds->ds_rxstat.rs_keyix
2957 					);
2958 				}
2959 			}
2960 			ifp->if_ierrors++;
2961 			/*
2962 			 * When a tap is present pass error frames
2963 			 * that have been requested.  By default we
2964 			 * pass decrypt+mic errors but others may be
2965 			 * interesting (e.g. crc).
2966 			 */
2967 			if (bpf_peers_present(sc->sc_drvbpf) &&
2968 			    (ds->ds_rxstat.rs_status & sc->sc_monpass)) {
2969 				bus_dmamap_sync(sc->sc_dmat, bf->bf_dmamap,
2970 				    BUS_DMASYNC_POSTREAD);
2971 				/* NB: bpf needs the mbuf length setup */
2972 				len = ds->ds_rxstat.rs_datalen;
2973 				m->m_pkthdr.len = m->m_len = len;
2974 				(void) ath_rx_tap(sc, m, ds, tsf, nf);
2975 			}
2976 			/* XXX pass MIC errors up for s/w reclaculation */
2977 			goto rx_next;
2978 		}
2979 rx_accept:
2980 		/*
2981 		 * Sync and unmap the frame.  At this point we're
2982 		 * committed to passing the mbuf somewhere so clear
2983 		 * bf_m; this means a new mbuf must be allocated
2984 		 * when the rx descriptor is setup again to receive
2985 		 * another frame.
2986 		 */
2987 		bus_dmamap_sync(sc->sc_dmat, bf->bf_dmamap,
2988 		    BUS_DMASYNC_POSTREAD);
2989 		bus_dmamap_unload(sc->sc_dmat, bf->bf_dmamap);
2990 		bf->bf_m = NULL;
2991 
2992 		m->m_pkthdr.rcvif = ifp;
2993 		len = ds->ds_rxstat.rs_datalen;
2994 		m->m_pkthdr.len = m->m_len = len;
2995 
2996 		sc->sc_stats.ast_ant_rx[ds->ds_rxstat.rs_antenna]++;
2997 
2998 		if (bpf_peers_present(sc->sc_drvbpf) &&
2999 		    !ath_rx_tap(sc, m, ds, tsf, nf)) {
3000 			m_freem(m);		/* XXX reclaim */
3001 			goto rx_next;
3002 		}
3003 
3004 		/*
3005 		 * From this point on we assume the frame is at least
3006 		 * as large as ieee80211_frame_min; verify that.
3007 		 */
3008 		if (len < IEEE80211_MIN_LEN) {
3009 			DPRINTF(sc, ATH_DEBUG_RECV, "%s: short packet %d\n",
3010 				__func__, len);
3011 			sc->sc_stats.ast_rx_tooshort++;
3012 			m_freem(m);
3013 			goto rx_next;
3014 		}
3015 
3016 		if (IFF_DUMPPKTS(sc, ATH_DEBUG_RECV)) {
3017 			ieee80211_dump_pkt(mtod(m, caddr_t), len,
3018 				   sc->sc_hwmap[ds->ds_rxstat.rs_rate].ieeerate,
3019 				   ds->ds_rxstat.rs_rssi);
3020 		}
3021 
3022 		m_adj(m, -IEEE80211_CRC_LEN);
3023 
3024 		/*
3025 		 * Locate the node for sender, track state, and then
3026 		 * pass the (referenced) node up to the 802.11 layer
3027 		 * for its use.
3028 		 */
3029 		ni = ieee80211_find_rxnode_withkey(ic,
3030 			mtod(m, const struct ieee80211_frame_min *),
3031 			ds->ds_rxstat.rs_keyix == HAL_RXKEYIX_INVALID ?
3032 				IEEE80211_KEYIX_NONE : ds->ds_rxstat.rs_keyix);
3033 		/*
3034 		 * Track rx rssi and do any rx antenna management.
3035 		 */
3036 		an = ATH_NODE(ni);
3037 		ATH_RSSI_LPF(an->an_avgrssi, ds->ds_rxstat.rs_rssi);
3038 		ATH_RSSI_LPF(sc->sc_halstats.ns_avgrssi, ds->ds_rxstat.rs_rssi);
3039 		/*
3040 		 * Send frame up for processing.
3041 		 */
3042 		type = ieee80211_input(ic, m, ni,
3043 			ds->ds_rxstat.rs_rssi, ds->ds_rxstat.rs_tstamp);
3044 		ieee80211_free_node(ni);
3045 		if (sc->sc_diversity) {
3046 			/*
3047 			 * When using fast diversity, change the default rx
3048 			 * antenna if diversity chooses the other antenna 3
3049 			 * times in a row.
3050 			 */
3051 			if (sc->sc_defant != ds->ds_rxstat.rs_antenna) {
3052 				if (++sc->sc_rxotherant >= 3)
3053 					ath_setdefantenna(sc,
3054 						ds->ds_rxstat.rs_antenna);
3055 			} else
3056 				sc->sc_rxotherant = 0;
3057 		}
3058 		if (sc->sc_softled) {
3059 			/*
3060 			 * Blink for any data frame.  Otherwise do a
3061 			 * heartbeat-style blink when idle.  The latter
3062 			 * is mainly for station mode where we depend on
3063 			 * periodic beacon frames to trigger the poll event.
3064 			 */
3065 			if (type == IEEE80211_FC0_TYPE_DATA) {
3066 				sc->sc_rxrate = ds->ds_rxstat.rs_rate;
3067 				ath_led_event(sc, ATH_LED_RX);
3068 			} else if (ticks - sc->sc_ledevent >= sc->sc_ledidle)
3069 				ath_led_event(sc, ATH_LED_POLL);
3070 		}
3071 		/*
3072 		 * Arrange to update the last rx timestamp only for
3073 		 * frames from our ap when operating in station mode.
3074 		 * This assumes the rx key is always setup when associated.
3075 		 */
3076 		if (ic->ic_opmode == IEEE80211_M_STA &&
3077 		    ds->ds_rxstat.rs_keyix != HAL_RXKEYIX_INVALID)
3078 			ngood++;
3079 rx_next:
3080 		STAILQ_INSERT_TAIL(&sc->sc_rxbuf, bf, bf_list);
3081 	} while (ath_rxbuf_init(sc, bf) == 0);
3082 
3083 	/* rx signal state monitoring */
3084 	ath_hal_rxmonitor(ah, &sc->sc_halstats, &sc->sc_curchan);
3085 	if (ath_hal_radar_event(ah))
3086 		taskqueue_enqueue(sc->sc_tq, &sc->sc_radartask);
3087 	if (ngood)
3088 		sc->sc_lastrx = tsf;
3089 
3090 	NET_UNLOCK_GIANT();		/* XXX */
3091 #undef PA2DESC
3092 }
3093 
3094 static void
3095 ath_txq_init(struct ath_softc *sc, struct ath_txq *txq, int qnum)
3096 {
3097 	txq->axq_qnum = qnum;
3098 	txq->axq_depth = 0;
3099 	txq->axq_intrcnt = 0;
3100 	txq->axq_link = NULL;
3101 	STAILQ_INIT(&txq->axq_q);
3102 	ATH_TXQ_LOCK_INIT(sc, txq);
3103 }
3104 
3105 /*
3106  * Setup a h/w transmit queue.
3107  */
3108 static struct ath_txq *
3109 ath_txq_setup(struct ath_softc *sc, int qtype, int subtype)
3110 {
3111 #define	N(a)	(sizeof(a)/sizeof(a[0]))
3112 	struct ath_hal *ah = sc->sc_ah;
3113 	HAL_TXQ_INFO qi;
3114 	int qnum;
3115 
3116 	memset(&qi, 0, sizeof(qi));
3117 	qi.tqi_subtype = subtype;
3118 	qi.tqi_aifs = HAL_TXQ_USEDEFAULT;
3119 	qi.tqi_cwmin = HAL_TXQ_USEDEFAULT;
3120 	qi.tqi_cwmax = HAL_TXQ_USEDEFAULT;
3121 	/*
3122 	 * Enable interrupts only for EOL and DESC conditions.
3123 	 * We mark tx descriptors to receive a DESC interrupt
3124 	 * when a tx queue gets deep; otherwise waiting for the
3125 	 * EOL to reap descriptors.  Note that this is done to
3126 	 * reduce interrupt load and this only defers reaping
3127 	 * descriptors, never transmitting frames.  Aside from
3128 	 * reducing interrupts this also permits more concurrency.
3129 	 * The only potential downside is if the tx queue backs
3130 	 * up in which case the top half of the kernel may backup
3131 	 * due to a lack of tx descriptors.
3132 	 */
3133 	qi.tqi_qflags = HAL_TXQ_TXEOLINT_ENABLE | HAL_TXQ_TXDESCINT_ENABLE;
3134 	qnum = ath_hal_setuptxqueue(ah, qtype, &qi);
3135 	if (qnum == -1) {
3136 		/*
3137 		 * NB: don't print a message, this happens
3138 		 * normally on parts with too few tx queues
3139 		 */
3140 		return NULL;
3141 	}
3142 	if (qnum >= N(sc->sc_txq)) {
3143 		device_printf(sc->sc_dev,
3144 			"hal qnum %u out of range, max %zu!\n",
3145 			qnum, N(sc->sc_txq));
3146 		ath_hal_releasetxqueue(ah, qnum);
3147 		return NULL;
3148 	}
3149 	if (!ATH_TXQ_SETUP(sc, qnum)) {
3150 		ath_txq_init(sc, &sc->sc_txq[qnum], qnum);
3151 		sc->sc_txqsetup |= 1<<qnum;
3152 	}
3153 	return &sc->sc_txq[qnum];
3154 #undef N
3155 }
3156 
3157 /*
3158  * Setup a hardware data transmit queue for the specified
3159  * access control.  The hal may not support all requested
3160  * queues in which case it will return a reference to a
3161  * previously setup queue.  We record the mapping from ac's
3162  * to h/w queues for use by ath_tx_start and also track
3163  * the set of h/w queues being used to optimize work in the
3164  * transmit interrupt handler and related routines.
3165  */
3166 static int
3167 ath_tx_setup(struct ath_softc *sc, int ac, int haltype)
3168 {
3169 #define	N(a)	(sizeof(a)/sizeof(a[0]))
3170 	struct ath_txq *txq;
3171 
3172 	if (ac >= N(sc->sc_ac2q)) {
3173 		device_printf(sc->sc_dev, "AC %u out of range, max %zu!\n",
3174 			ac, N(sc->sc_ac2q));
3175 		return 0;
3176 	}
3177 	txq = ath_txq_setup(sc, HAL_TX_QUEUE_DATA, haltype);
3178 	if (txq != NULL) {
3179 		sc->sc_ac2q[ac] = txq;
3180 		return 1;
3181 	} else
3182 		return 0;
3183 #undef N
3184 }
3185 
3186 /*
3187  * Update WME parameters for a transmit queue.
3188  */
3189 static int
3190 ath_txq_update(struct ath_softc *sc, int ac)
3191 {
3192 #define	ATH_EXPONENT_TO_VALUE(v)	((1<<v)-1)
3193 #define	ATH_TXOP_TO_US(v)		(v<<5)
3194 	struct ieee80211com *ic = &sc->sc_ic;
3195 	struct ath_txq *txq = sc->sc_ac2q[ac];
3196 	struct wmeParams *wmep = &ic->ic_wme.wme_chanParams.cap_wmeParams[ac];
3197 	struct ath_hal *ah = sc->sc_ah;
3198 	HAL_TXQ_INFO qi;
3199 
3200 	ath_hal_gettxqueueprops(ah, txq->axq_qnum, &qi);
3201 	qi.tqi_aifs = wmep->wmep_aifsn;
3202 	qi.tqi_cwmin = ATH_EXPONENT_TO_VALUE(wmep->wmep_logcwmin);
3203 	qi.tqi_cwmax = ATH_EXPONENT_TO_VALUE(wmep->wmep_logcwmax);
3204 	qi.tqi_burstTime = ATH_TXOP_TO_US(wmep->wmep_txopLimit);
3205 
3206 	if (!ath_hal_settxqueueprops(ah, txq->axq_qnum, &qi)) {
3207 		device_printf(sc->sc_dev, "unable to update hardware queue "
3208 			"parameters for %s traffic!\n",
3209 			ieee80211_wme_acnames[ac]);
3210 		return 0;
3211 	} else {
3212 		ath_hal_resettxqueue(ah, txq->axq_qnum); /* push to h/w */
3213 		return 1;
3214 	}
3215 #undef ATH_TXOP_TO_US
3216 #undef ATH_EXPONENT_TO_VALUE
3217 }
3218 
3219 /*
3220  * Callback from the 802.11 layer to update WME parameters.
3221  */
3222 static int
3223 ath_wme_update(struct ieee80211com *ic)
3224 {
3225 	struct ath_softc *sc = ic->ic_ifp->if_softc;
3226 
3227 	return !ath_txq_update(sc, WME_AC_BE) ||
3228 	    !ath_txq_update(sc, WME_AC_BK) ||
3229 	    !ath_txq_update(sc, WME_AC_VI) ||
3230 	    !ath_txq_update(sc, WME_AC_VO) ? EIO : 0;
3231 }
3232 
3233 /*
3234  * Reclaim resources for a setup queue.
3235  */
3236 static void
3237 ath_tx_cleanupq(struct ath_softc *sc, struct ath_txq *txq)
3238 {
3239 
3240 	ath_hal_releasetxqueue(sc->sc_ah, txq->axq_qnum);
3241 	ATH_TXQ_LOCK_DESTROY(txq);
3242 	sc->sc_txqsetup &= ~(1<<txq->axq_qnum);
3243 }
3244 
3245 /*
3246  * Reclaim all tx queue resources.
3247  */
3248 static void
3249 ath_tx_cleanup(struct ath_softc *sc)
3250 {
3251 	int i;
3252 
3253 	ATH_TXBUF_LOCK_DESTROY(sc);
3254 	for (i = 0; i < HAL_NUM_TX_QUEUES; i++)
3255 		if (ATH_TXQ_SETUP(sc, i))
3256 			ath_tx_cleanupq(sc, &sc->sc_txq[i]);
3257 	ATH_TXQ_LOCK_DESTROY(&sc->sc_mcastq);
3258 }
3259 
3260 /*
3261  * Defragment an mbuf chain, returning at most maxfrags separate
3262  * mbufs+clusters.  If this is not possible NULL is returned and
3263  * the original mbuf chain is left in it's present (potentially
3264  * modified) state.  We use two techniques: collapsing consecutive
3265  * mbufs and replacing consecutive mbufs by a cluster.
3266  */
3267 static struct mbuf *
3268 ath_defrag(struct mbuf *m0, int how, int maxfrags)
3269 {
3270 	struct mbuf *m, *n, *n2, **prev;
3271 	u_int curfrags;
3272 
3273 	/*
3274 	 * Calculate the current number of frags.
3275 	 */
3276 	curfrags = 0;
3277 	for (m = m0; m != NULL; m = m->m_next)
3278 		curfrags++;
3279 	/*
3280 	 * First, try to collapse mbufs.  Note that we always collapse
3281 	 * towards the front so we don't need to deal with moving the
3282 	 * pkthdr.  This may be suboptimal if the first mbuf has much
3283 	 * less data than the following.
3284 	 */
3285 	m = m0;
3286 again:
3287 	for (;;) {
3288 		n = m->m_next;
3289 		if (n == NULL)
3290 			break;
3291 		if ((m->m_flags & M_RDONLY) == 0 &&
3292 		    n->m_len < M_TRAILINGSPACE(m)) {
3293 			bcopy(mtod(n, void *), mtod(m, char *) + m->m_len,
3294 				n->m_len);
3295 			m->m_len += n->m_len;
3296 			m->m_next = n->m_next;
3297 			m_free(n);
3298 			if (--curfrags <= maxfrags)
3299 				return m0;
3300 		} else
3301 			m = n;
3302 	}
3303 	KASSERT(maxfrags > 1,
3304 		("maxfrags %u, but normal collapse failed", maxfrags));
3305 	/*
3306 	 * Collapse consecutive mbufs to a cluster.
3307 	 */
3308 	prev = &m0->m_next;		/* NB: not the first mbuf */
3309 	while ((n = *prev) != NULL) {
3310 		if ((n2 = n->m_next) != NULL &&
3311 		    n->m_len + n2->m_len < MCLBYTES) {
3312 			m = m_getcl(how, MT_DATA, 0);
3313 			if (m == NULL)
3314 				goto bad;
3315 			bcopy(mtod(n, void *), mtod(m, void *), n->m_len);
3316 			bcopy(mtod(n2, void *), mtod(m, char *) + n->m_len,
3317 				n2->m_len);
3318 			m->m_len = n->m_len + n2->m_len;
3319 			m->m_next = n2->m_next;
3320 			*prev = m;
3321 			m_free(n);
3322 			m_free(n2);
3323 			if (--curfrags <= maxfrags)	/* +1 cl -2 mbufs */
3324 				return m0;
3325 			/*
3326 			 * Still not there, try the normal collapse
3327 			 * again before we allocate another cluster.
3328 			 */
3329 			goto again;
3330 		}
3331 		prev = &n->m_next;
3332 	}
3333 	/*
3334 	 * No place where we can collapse to a cluster; punt.
3335 	 * This can occur if, for example, you request 2 frags
3336 	 * but the packet requires that both be clusters (we
3337 	 * never reallocate the first mbuf to avoid moving the
3338 	 * packet header).
3339 	 */
3340 bad:
3341 	return NULL;
3342 }
3343 
3344 /*
3345  * Return h/w rate index for an IEEE rate (w/o basic rate bit).
3346  */
3347 static int
3348 ath_tx_findrix(const HAL_RATE_TABLE *rt, int rate)
3349 {
3350 	int i;
3351 
3352 	for (i = 0; i < rt->rateCount; i++)
3353 		if ((rt->info[i].dot11Rate & IEEE80211_RATE_VAL) == rate)
3354 			return i;
3355 	return 0;		/* NB: lowest rate */
3356 }
3357 
3358 static int
3359 ath_tx_dmasetup(struct ath_softc *sc, struct ath_buf *bf, struct mbuf *m0)
3360 {
3361 	struct mbuf *m;
3362 	int error;
3363 
3364 	/*
3365 	 * Load the DMA map so any coalescing is done.  This
3366 	 * also calculates the number of descriptors we need.
3367 	 */
3368 	error = bus_dmamap_load_mbuf_sg(sc->sc_dmat, bf->bf_dmamap, m0,
3369 				     bf->bf_segs, &bf->bf_nseg,
3370 				     BUS_DMA_NOWAIT);
3371 	if (error == EFBIG) {
3372 		/* XXX packet requires too many descriptors */
3373 		bf->bf_nseg = ATH_TXDESC+1;
3374 	} else if (error != 0) {
3375 		sc->sc_stats.ast_tx_busdma++;
3376 		m_freem(m0);
3377 		return error;
3378 	}
3379 	/*
3380 	 * Discard null packets and check for packets that
3381 	 * require too many TX descriptors.  We try to convert
3382 	 * the latter to a cluster.
3383 	 */
3384 	if (bf->bf_nseg > ATH_TXDESC) {		/* too many desc's, linearize */
3385 		sc->sc_stats.ast_tx_linear++;
3386 		m = ath_defrag(m0, M_DONTWAIT, ATH_TXDESC);
3387 		if (m == NULL) {
3388 			m_freem(m0);
3389 			sc->sc_stats.ast_tx_nombuf++;
3390 			return ENOMEM;
3391 		}
3392 		m0 = m;
3393 		error = bus_dmamap_load_mbuf_sg(sc->sc_dmat, bf->bf_dmamap, m0,
3394 					     bf->bf_segs, &bf->bf_nseg,
3395 					     BUS_DMA_NOWAIT);
3396 		if (error != 0) {
3397 			sc->sc_stats.ast_tx_busdma++;
3398 			m_freem(m0);
3399 			return error;
3400 		}
3401 		KASSERT(bf->bf_nseg <= ATH_TXDESC,
3402 		    ("too many segments after defrag; nseg %u", bf->bf_nseg));
3403 	} else if (bf->bf_nseg == 0) {		/* null packet, discard */
3404 		sc->sc_stats.ast_tx_nodata++;
3405 		m_freem(m0);
3406 		return EIO;
3407 	}
3408 	DPRINTF(sc, ATH_DEBUG_XMIT, "%s: m %p len %u\n",
3409 		__func__, m0, m0->m_pkthdr.len);
3410 	bus_dmamap_sync(sc->sc_dmat, bf->bf_dmamap, BUS_DMASYNC_PREWRITE);
3411 	bf->bf_m = m0;
3412 
3413 	return 0;
3414 }
3415 
3416 static void
3417 ath_tx_handoff(struct ath_softc *sc, struct ath_txq *txq, struct ath_buf *bf)
3418 {
3419 	struct ath_hal *ah = sc->sc_ah;
3420 	struct ath_desc *ds, *ds0;
3421 	int i;
3422 
3423 	/*
3424 	 * Fillin the remainder of the descriptor info.
3425 	 */
3426 	ds0 = ds = bf->bf_desc;
3427 	for (i = 0; i < bf->bf_nseg; i++, ds++) {
3428 		ds->ds_data = bf->bf_segs[i].ds_addr;
3429 		if (i == bf->bf_nseg - 1)
3430 			ds->ds_link = 0;
3431 		else
3432 			ds->ds_link = bf->bf_daddr + sizeof(*ds) * (i + 1);
3433 		ath_hal_filltxdesc(ah, ds
3434 			, bf->bf_segs[i].ds_len	/* segment length */
3435 			, i == 0		/* first segment */
3436 			, i == bf->bf_nseg - 1	/* last segment */
3437 			, ds0			/* first descriptor */
3438 		);
3439 		DPRINTF(sc, ATH_DEBUG_XMIT,
3440 			"%s: %d: %08x %08x %08x %08x %08x %08x\n",
3441 			__func__, i, ds->ds_link, ds->ds_data,
3442 			ds->ds_ctl0, ds->ds_ctl1, ds->ds_hw[0], ds->ds_hw[1]);
3443 	}
3444 	/*
3445 	 * Insert the frame on the outbound list and pass it on
3446 	 * to the hardware.  Multicast frames buffered for power
3447 	 * save stations and transmit from the CAB queue are stored
3448 	 * on a s/w only queue and loaded on to the CAB queue in
3449 	 * the SWBA handler since frames only go out on DTIM and
3450 	 * to avoid possible races.
3451 	 */
3452 	ATH_TXQ_LOCK(txq);
3453 	ATH_TXQ_INSERT_TAIL(txq, bf, bf_list);
3454 	if (txq != &sc->sc_mcastq) {
3455 		if (txq->axq_link == NULL) {
3456 			ath_hal_puttxbuf(ah, txq->axq_qnum, bf->bf_daddr);
3457 			DPRINTF(sc, ATH_DEBUG_XMIT,
3458 			    "%s: TXDP[%u] = %p (%p) depth %d\n", __func__,
3459 			    txq->axq_qnum, (caddr_t)bf->bf_daddr, bf->bf_desc,
3460 			    txq->axq_depth);
3461 		} else {
3462 			*txq->axq_link = bf->bf_daddr;
3463 			DPRINTF(sc, ATH_DEBUG_XMIT,
3464 			    "%s: link[%u](%p)=%p (%p) depth %d\n", __func__,
3465 			    txq->axq_qnum, txq->axq_link,
3466 			    (caddr_t)bf->bf_daddr, bf->bf_desc, txq->axq_depth);
3467 		}
3468 		txq->axq_link = &bf->bf_desc[bf->bf_nseg - 1].ds_link;
3469 		ath_hal_txstart(ah, txq->axq_qnum);
3470 	} else {
3471 		if (txq->axq_link != NULL)
3472 			*txq->axq_link = bf->bf_daddr;
3473 		txq->axq_link = &bf->bf_desc[bf->bf_nseg - 1].ds_link;
3474 	}
3475 	ATH_TXQ_UNLOCK(txq);
3476 }
3477 
3478 static int
3479 ath_tx_start(struct ath_softc *sc, struct ieee80211_node *ni, struct ath_buf *bf,
3480     struct mbuf *m0)
3481 {
3482 	struct ieee80211com *ic = &sc->sc_ic;
3483 	struct ath_hal *ah = sc->sc_ah;
3484 	struct ifnet *ifp = sc->sc_ifp;
3485 	const struct chanAccParams *cap = &ic->ic_wme.wme_chanParams;
3486 	int error, iswep, ismcast, ismrr;
3487 	int keyix, hdrlen, pktlen, try0;
3488 	u_int8_t rix, txrate, ctsrate;
3489 	u_int8_t cix = 0xff;		/* NB: silence compiler */
3490 	struct ath_desc *ds;
3491 	struct ath_txq *txq;
3492 	struct ieee80211_frame *wh;
3493 	u_int subtype, flags, ctsduration;
3494 	HAL_PKT_TYPE atype;
3495 	const HAL_RATE_TABLE *rt;
3496 	HAL_BOOL shortPreamble;
3497 	struct ath_node *an;
3498 	u_int pri;
3499 
3500 	wh = mtod(m0, struct ieee80211_frame *);
3501 	iswep = wh->i_fc[1] & IEEE80211_FC1_WEP;
3502 	ismcast = IEEE80211_IS_MULTICAST(wh->i_addr1);
3503 	hdrlen = ieee80211_anyhdrsize(wh);
3504 	/*
3505 	 * Packet length must not include any
3506 	 * pad bytes; deduct them here.
3507 	 */
3508 	pktlen = m0->m_pkthdr.len - (hdrlen & 3);
3509 
3510 	if (iswep) {
3511 		const struct ieee80211_cipher *cip;
3512 		struct ieee80211_key *k;
3513 
3514 		/*
3515 		 * Construct the 802.11 header+trailer for an encrypted
3516 		 * frame. The only reason this can fail is because of an
3517 		 * unknown or unsupported cipher/key type.
3518 		 */
3519 		k = ieee80211_crypto_encap(ic, ni, m0);
3520 		if (k == NULL) {
3521 			/*
3522 			 * This can happen when the key is yanked after the
3523 			 * frame was queued.  Just discard the frame; the
3524 			 * 802.11 layer counts failures and provides
3525 			 * debugging/diagnostics.
3526 			 */
3527 			m_freem(m0);
3528 			return EIO;
3529 		}
3530 		/*
3531 		 * Adjust the packet + header lengths for the crypto
3532 		 * additions and calculate the h/w key index.  When
3533 		 * a s/w mic is done the frame will have had any mic
3534 		 * added to it prior to entry so m0->m_pkthdr.len above will
3535 		 * account for it. Otherwise we need to add it to the
3536 		 * packet length.
3537 		 */
3538 		cip = k->wk_cipher;
3539 		hdrlen += cip->ic_header;
3540 		pktlen += cip->ic_header + cip->ic_trailer;
3541 		if ((k->wk_flags & IEEE80211_KEY_SWMIC) == 0)
3542 			pktlen += cip->ic_miclen;
3543 		keyix = k->wk_keyix;
3544 
3545 		/* packet header may have moved, reset our local pointer */
3546 		wh = mtod(m0, struct ieee80211_frame *);
3547 	} else if (ni->ni_ucastkey.wk_cipher == &ieee80211_cipher_none) {
3548 		/*
3549 		 * Use station key cache slot, if assigned.
3550 		 */
3551 		keyix = ni->ni_ucastkey.wk_keyix;
3552 		if (keyix == IEEE80211_KEYIX_NONE)
3553 			keyix = HAL_TXKEYIX_INVALID;
3554 	} else
3555 		keyix = HAL_TXKEYIX_INVALID;
3556 
3557 	pktlen += IEEE80211_CRC_LEN;
3558 
3559 	/*
3560 	 * Load the DMA map so any coalescing is done.  This
3561 	 * also calculates the number of descriptors we need.
3562 	 */
3563 	error = ath_tx_dmasetup(sc, bf, m0);
3564 	if (error != 0)
3565 		return error;
3566 	bf->bf_node = ni;			/* NB: held reference */
3567 	m0 = bf->bf_m;				/* NB: may have changed */
3568 	wh = mtod(m0, struct ieee80211_frame *);
3569 
3570 	/* setup descriptors */
3571 	ds = bf->bf_desc;
3572 	rt = sc->sc_currates;
3573 	KASSERT(rt != NULL, ("no rate table, mode %u", sc->sc_curmode));
3574 
3575 	/*
3576 	 * NB: the 802.11 layer marks whether or not we should
3577 	 * use short preamble based on the current mode and
3578 	 * negotiated parameters.
3579 	 */
3580 	if ((ic->ic_flags & IEEE80211_F_SHPREAMBLE) &&
3581 	    (ni->ni_capinfo & IEEE80211_CAPINFO_SHORT_PREAMBLE)) {
3582 		shortPreamble = AH_TRUE;
3583 		sc->sc_stats.ast_tx_shortpre++;
3584 	} else {
3585 		shortPreamble = AH_FALSE;
3586 	}
3587 
3588 	an = ATH_NODE(ni);
3589 	flags = HAL_TXDESC_CLRDMASK;		/* XXX needed for crypto errs */
3590 	ismrr = 0;				/* default no multi-rate retry*/
3591 	/*
3592 	 * Calculate Atheros packet type from IEEE80211 packet header,
3593 	 * setup for rate calculations, and select h/w transmit queue.
3594 	 */
3595 	switch (wh->i_fc[0] & IEEE80211_FC0_TYPE_MASK) {
3596 	case IEEE80211_FC0_TYPE_MGT:
3597 		subtype = wh->i_fc[0] & IEEE80211_FC0_SUBTYPE_MASK;
3598 		if (subtype == IEEE80211_FC0_SUBTYPE_BEACON)
3599 			atype = HAL_PKT_TYPE_BEACON;
3600 		else if (subtype == IEEE80211_FC0_SUBTYPE_PROBE_RESP)
3601 			atype = HAL_PKT_TYPE_PROBE_RESP;
3602 		else if (subtype == IEEE80211_FC0_SUBTYPE_ATIM)
3603 			atype = HAL_PKT_TYPE_ATIM;
3604 		else
3605 			atype = HAL_PKT_TYPE_NORMAL;	/* XXX */
3606 		rix = sc->sc_minrateix;
3607 		txrate = rt->info[rix].rateCode;
3608 		if (shortPreamble)
3609 			txrate |= rt->info[rix].shortPreamble;
3610 		try0 = ATH_TXMGTTRY;
3611 		/* NB: force all management frames to highest queue */
3612 		if (ni->ni_flags & IEEE80211_NODE_QOS) {
3613 			/* NB: force all management frames to highest queue */
3614 			pri = WME_AC_VO;
3615 		} else
3616 			pri = WME_AC_BE;
3617 		flags |= HAL_TXDESC_INTREQ;	/* force interrupt */
3618 		break;
3619 	case IEEE80211_FC0_TYPE_CTL:
3620 		atype = HAL_PKT_TYPE_PSPOLL;	/* stop setting of duration */
3621 		rix = sc->sc_minrateix;
3622 		txrate = rt->info[rix].rateCode;
3623 		if (shortPreamble)
3624 			txrate |= rt->info[rix].shortPreamble;
3625 		try0 = ATH_TXMGTTRY;
3626 		/* NB: force all ctl frames to highest queue */
3627 		if (ni->ni_flags & IEEE80211_NODE_QOS) {
3628 			/* NB: force all ctl frames to highest queue */
3629 			pri = WME_AC_VO;
3630 		} else
3631 			pri = WME_AC_BE;
3632 		flags |= HAL_TXDESC_INTREQ;	/* force interrupt */
3633 		break;
3634 	case IEEE80211_FC0_TYPE_DATA:
3635 		atype = HAL_PKT_TYPE_NORMAL;		/* default */
3636 		/*
3637 		 * Data frames: multicast frames go out at a fixed rate,
3638 		 * otherwise consult the rate control module for the
3639 		 * rate to use.
3640 		 */
3641 		if (ismcast) {
3642 			/*
3643 			 * Check mcast rate setting in case it's changed.
3644 			 * XXX move out of fastpath
3645 			 */
3646 			if (ic->ic_mcast_rate != sc->sc_mcastrate) {
3647 				sc->sc_mcastrix =
3648 					ath_tx_findrix(rt, ic->ic_mcast_rate);
3649 				sc->sc_mcastrate = ic->ic_mcast_rate;
3650 			}
3651 			rix = sc->sc_mcastrix;
3652 			txrate = rt->info[rix].rateCode;
3653 			if (shortPreamble)
3654 				txrate |= rt->info[rix].shortPreamble;
3655 			try0 = 1;
3656 		} else {
3657 			ath_rate_findrate(sc, an, shortPreamble, pktlen,
3658 				&rix, &try0, &txrate);
3659 			sc->sc_txrate = txrate;		/* for LED blinking */
3660 			if (try0 != ATH_TXMAXTRY)
3661 				ismrr = 1;
3662 		}
3663 		pri = M_WME_GETAC(m0);
3664 		if (cap->cap_wmeParams[pri].wmep_noackPolicy)
3665 			flags |= HAL_TXDESC_NOACK;
3666 		break;
3667 	default:
3668 		if_printf(ifp, "bogus frame type 0x%x (%s)\n",
3669 			wh->i_fc[0] & IEEE80211_FC0_TYPE_MASK, __func__);
3670 		/* XXX statistic */
3671 		m_freem(m0);
3672 		return EIO;
3673 	}
3674 	txq = sc->sc_ac2q[pri];
3675 
3676 	/*
3677 	 * When servicing one or more stations in power-save mode
3678 	 * (or) if there is some mcast data waiting on the mcast
3679 	 * queue (to prevent out of order delivery) multicast
3680 	 * frames must be buffered until after the beacon.
3681 	 */
3682 	if (ismcast && (ic->ic_ps_sta || sc->sc_mcastq.axq_depth)) {
3683 		txq = &sc->sc_mcastq;
3684 		/* XXX? more bit in 802.11 frame header */
3685 	}
3686 
3687 	/*
3688 	 * Calculate miscellaneous flags.
3689 	 */
3690 	if (ismcast) {
3691 		flags |= HAL_TXDESC_NOACK;	/* no ack on broad/multicast */
3692 	} else if (pktlen > ic->ic_rtsthreshold) {
3693 		flags |= HAL_TXDESC_RTSENA;	/* RTS based on frame length */
3694 		cix = rt->info[rix].controlRate;
3695 		sc->sc_stats.ast_tx_rts++;
3696 	}
3697 	if (flags & HAL_TXDESC_NOACK)		/* NB: avoid double counting */
3698 		sc->sc_stats.ast_tx_noack++;
3699 
3700 	/*
3701 	 * If 802.11g protection is enabled, determine whether
3702 	 * to use RTS/CTS or just CTS.  Note that this is only
3703 	 * done for OFDM unicast frames.
3704 	 */
3705 	if ((ic->ic_flags & IEEE80211_F_USEPROT) &&
3706 	    rt->info[rix].phy == IEEE80211_T_OFDM &&
3707 	    (flags & HAL_TXDESC_NOACK) == 0) {
3708 		/* XXX fragments must use CCK rates w/ protection */
3709 		if (ic->ic_protmode == IEEE80211_PROT_RTSCTS)
3710 			flags |= HAL_TXDESC_RTSENA;
3711 		else if (ic->ic_protmode == IEEE80211_PROT_CTSONLY)
3712 			flags |= HAL_TXDESC_CTSENA;
3713 		cix = rt->info[sc->sc_protrix].controlRate;
3714 		sc->sc_stats.ast_tx_protect++;
3715 	}
3716 
3717 	/*
3718 	 * Calculate duration.  This logically belongs in the 802.11
3719 	 * layer but it lacks sufficient information to calculate it.
3720 	 */
3721 	if ((flags & HAL_TXDESC_NOACK) == 0 &&
3722 	    (wh->i_fc[0] & IEEE80211_FC0_TYPE_MASK) != IEEE80211_FC0_TYPE_CTL) {
3723 		u_int16_t dur;
3724 		/*
3725 		 * XXX not right with fragmentation.
3726 		 */
3727 		if (shortPreamble)
3728 			dur = rt->info[rix].spAckDuration;
3729 		else
3730 			dur = rt->info[rix].lpAckDuration;
3731 		*(u_int16_t *)wh->i_dur = htole16(dur);
3732 	}
3733 
3734 	/*
3735 	 * Calculate RTS/CTS rate and duration if needed.
3736 	 */
3737 	ctsduration = 0;
3738 	if (flags & (HAL_TXDESC_RTSENA|HAL_TXDESC_CTSENA)) {
3739 		/*
3740 		 * CTS transmit rate is derived from the transmit rate
3741 		 * by looking in the h/w rate table.  We must also factor
3742 		 * in whether or not a short preamble is to be used.
3743 		 */
3744 		/* NB: cix is set above where RTS/CTS is enabled */
3745 		KASSERT(cix != 0xff, ("cix not setup"));
3746 		ctsrate = rt->info[cix].rateCode;
3747 		/*
3748 		 * Compute the transmit duration based on the frame
3749 		 * size and the size of an ACK frame.  We call into the
3750 		 * HAL to do the computation since it depends on the
3751 		 * characteristics of the actual PHY being used.
3752 		 *
3753 		 * NB: CTS is assumed the same size as an ACK so we can
3754 		 *     use the precalculated ACK durations.
3755 		 */
3756 		if (shortPreamble) {
3757 			ctsrate |= rt->info[cix].shortPreamble;
3758 			if (flags & HAL_TXDESC_RTSENA)		/* SIFS + CTS */
3759 				ctsduration += rt->info[cix].spAckDuration;
3760 			ctsduration += ath_hal_computetxtime(ah,
3761 				rt, pktlen, rix, AH_TRUE);
3762 			if ((flags & HAL_TXDESC_NOACK) == 0)	/* SIFS + ACK */
3763 				ctsduration += rt->info[rix].spAckDuration;
3764 		} else {
3765 			if (flags & HAL_TXDESC_RTSENA)		/* SIFS + CTS */
3766 				ctsduration += rt->info[cix].lpAckDuration;
3767 			ctsduration += ath_hal_computetxtime(ah,
3768 				rt, pktlen, rix, AH_FALSE);
3769 			if ((flags & HAL_TXDESC_NOACK) == 0)	/* SIFS + ACK */
3770 				ctsduration += rt->info[rix].lpAckDuration;
3771 		}
3772 		/*
3773 		 * Must disable multi-rate retry when using RTS/CTS.
3774 		 */
3775 		ismrr = 0;
3776 		try0 = ATH_TXMGTTRY;		/* XXX */
3777 	} else
3778 		ctsrate = 0;
3779 
3780 	if (IFF_DUMPPKTS(sc, ATH_DEBUG_XMIT))
3781 		ieee80211_dump_pkt(mtod(m0, caddr_t), m0->m_len,
3782 			sc->sc_hwmap[txrate].ieeerate, -1);
3783 
3784 	if (bpf_peers_present(ic->ic_rawbpf))
3785 		bpf_mtap(ic->ic_rawbpf, m0);
3786 	if (bpf_peers_present(sc->sc_drvbpf)) {
3787 		u_int64_t tsf = ath_hal_gettsf64(ah);
3788 
3789 		sc->sc_tx_th.wt_tsf = htole64(tsf);
3790 		sc->sc_tx_th.wt_flags = sc->sc_hwmap[txrate].txflags;
3791 		if (iswep)
3792 			sc->sc_tx_th.wt_flags |= IEEE80211_RADIOTAP_F_WEP;
3793 		sc->sc_tx_th.wt_rate = sc->sc_hwmap[txrate].ieeerate;
3794 		sc->sc_tx_th.wt_txpower = ni->ni_txpower;
3795 		sc->sc_tx_th.wt_antenna = sc->sc_txantenna;
3796 
3797 		bpf_mtap2(sc->sc_drvbpf,
3798 			&sc->sc_tx_th, sc->sc_tx_th_len, m0);
3799 	}
3800 
3801 	/*
3802 	 * Determine if a tx interrupt should be generated for
3803 	 * this descriptor.  We take a tx interrupt to reap
3804 	 * descriptors when the h/w hits an EOL condition or
3805 	 * when the descriptor is specifically marked to generate
3806 	 * an interrupt.  We periodically mark descriptors in this
3807 	 * way to insure timely replenishing of the supply needed
3808 	 * for sending frames.  Defering interrupts reduces system
3809 	 * load and potentially allows more concurrent work to be
3810 	 * done but if done to aggressively can cause senders to
3811 	 * backup.
3812 	 *
3813 	 * NB: use >= to deal with sc_txintrperiod changing
3814 	 *     dynamically through sysctl.
3815 	 */
3816 	if (flags & HAL_TXDESC_INTREQ) {
3817 		txq->axq_intrcnt = 0;
3818 	} else if (++txq->axq_intrcnt >= sc->sc_txintrperiod) {
3819 		flags |= HAL_TXDESC_INTREQ;
3820 		txq->axq_intrcnt = 0;
3821 	}
3822 
3823 	/*
3824 	 * Formulate first tx descriptor with tx controls.
3825 	 */
3826 	/* XXX check return value? */
3827 	ath_hal_setuptxdesc(ah, ds
3828 		, pktlen		/* packet length */
3829 		, hdrlen		/* header length */
3830 		, atype			/* Atheros packet type */
3831 		, ni->ni_txpower	/* txpower */
3832 		, txrate, try0		/* series 0 rate/tries */
3833 		, keyix			/* key cache index */
3834 		, sc->sc_txantenna	/* antenna mode */
3835 		, flags			/* flags */
3836 		, ctsrate		/* rts/cts rate */
3837 		, ctsduration		/* rts/cts duration */
3838 	);
3839 	bf->bf_flags = flags;
3840 	/*
3841 	 * Setup the multi-rate retry state only when we're
3842 	 * going to use it.  This assumes ath_hal_setuptxdesc
3843 	 * initializes the descriptors (so we don't have to)
3844 	 * when the hardware supports multi-rate retry and
3845 	 * we don't use it.
3846 	 */
3847 	if (ismrr)
3848 		ath_rate_setupxtxdesc(sc, an, ds, shortPreamble, rix);
3849 
3850 	ath_tx_handoff(sc, txq, bf);
3851 	return 0;
3852 }
3853 
3854 /*
3855  * Process completed xmit descriptors from the specified queue.
3856  */
3857 static int
3858 ath_tx_processq(struct ath_softc *sc, struct ath_txq *txq)
3859 {
3860 	struct ath_hal *ah = sc->sc_ah;
3861 	struct ieee80211com *ic = &sc->sc_ic;
3862 	struct ath_buf *bf;
3863 	struct ath_desc *ds, *ds0;
3864 	struct ieee80211_node *ni;
3865 	struct ath_node *an;
3866 	int sr, lr, pri, nacked;
3867 	HAL_STATUS status;
3868 
3869 	DPRINTF(sc, ATH_DEBUG_TX_PROC, "%s: tx queue %u head %p link %p\n",
3870 		__func__, txq->axq_qnum,
3871 		(caddr_t)(uintptr_t) ath_hal_gettxbuf(sc->sc_ah, txq->axq_qnum),
3872 		txq->axq_link);
3873 	nacked = 0;
3874 	for (;;) {
3875 		ATH_TXQ_LOCK(txq);
3876 		txq->axq_intrcnt = 0;	/* reset periodic desc intr count */
3877 		bf = STAILQ_FIRST(&txq->axq_q);
3878 		if (bf == NULL) {
3879 			ATH_TXQ_UNLOCK(txq);
3880 			break;
3881 		}
3882 		ds0 = &bf->bf_desc[0];
3883 		ds = &bf->bf_desc[bf->bf_nseg - 1];
3884 		status = ath_hal_txprocdesc(ah, ds);
3885 #ifdef ATH_DEBUG
3886 		if (sc->sc_debug & ATH_DEBUG_XMIT_DESC)
3887 			ath_printtxbuf(bf, txq->axq_qnum, 0, status == HAL_OK);
3888 #endif
3889 		if (status == HAL_EINPROGRESS) {
3890 			ATH_TXQ_UNLOCK(txq);
3891 			break;
3892 		}
3893 		ATH_TXQ_REMOVE_HEAD(txq, bf_list);
3894 		if (txq->axq_depth == 0)
3895 			txq->axq_link = NULL;
3896 		ATH_TXQ_UNLOCK(txq);
3897 
3898 		ni = bf->bf_node;
3899 		if (ni != NULL) {
3900 			an = ATH_NODE(ni);
3901 			if (ds->ds_txstat.ts_status == 0) {
3902 				u_int8_t txant = ds->ds_txstat.ts_antenna;
3903 				sc->sc_stats.ast_ant_tx[txant]++;
3904 				sc->sc_ant_tx[txant]++;
3905 				if (ds->ds_txstat.ts_rate & HAL_TXSTAT_ALTRATE)
3906 					sc->sc_stats.ast_tx_altrate++;
3907 				sc->sc_stats.ast_tx_rssi =
3908 					ds->ds_txstat.ts_rssi;
3909 				ATH_RSSI_LPF(sc->sc_halstats.ns_avgtxrssi,
3910 					ds->ds_txstat.ts_rssi);
3911 				pri = M_WME_GETAC(bf->bf_m);
3912 				if (pri >= WME_AC_VO)
3913 					ic->ic_wme.wme_hipri_traffic++;
3914 				ni->ni_inact = ni->ni_inact_reload;
3915 			} else {
3916 				if (ds->ds_txstat.ts_status & HAL_TXERR_XRETRY)
3917 					sc->sc_stats.ast_tx_xretries++;
3918 				if (ds->ds_txstat.ts_status & HAL_TXERR_FIFO)
3919 					sc->sc_stats.ast_tx_fifoerr++;
3920 				if (ds->ds_txstat.ts_status & HAL_TXERR_FILT)
3921 					sc->sc_stats.ast_tx_filtered++;
3922 			}
3923 			sr = ds->ds_txstat.ts_shortretry;
3924 			lr = ds->ds_txstat.ts_longretry;
3925 			sc->sc_stats.ast_tx_shortretry += sr;
3926 			sc->sc_stats.ast_tx_longretry += lr;
3927 			/*
3928 			 * Hand the descriptor to the rate control algorithm.
3929 			 */
3930 			if ((ds->ds_txstat.ts_status & HAL_TXERR_FILT) == 0 &&
3931 			    (bf->bf_flags & HAL_TXDESC_NOACK) == 0) {
3932 				/*
3933 				 * If frame was ack'd update the last rx time
3934 				 * used to workaround phantom bmiss interrupts.
3935 				 */
3936 				if (ds->ds_txstat.ts_status == 0)
3937 					nacked++;
3938 				ath_rate_tx_complete(sc, an, ds, ds0);
3939 			}
3940 			/*
3941 			 * Reclaim reference to node.
3942 			 *
3943 			 * NB: the node may be reclaimed here if, for example
3944 			 *     this is a DEAUTH message that was sent and the
3945 			 *     node was timed out due to inactivity.
3946 			 */
3947 			ieee80211_free_node(ni);
3948 		}
3949 		bus_dmamap_sync(sc->sc_dmat, bf->bf_dmamap,
3950 		    BUS_DMASYNC_POSTWRITE);
3951 		bus_dmamap_unload(sc->sc_dmat, bf->bf_dmamap);
3952 		m_freem(bf->bf_m);
3953 		bf->bf_m = NULL;
3954 		bf->bf_node = NULL;
3955 
3956 		ATH_TXBUF_LOCK(sc);
3957 		STAILQ_INSERT_TAIL(&sc->sc_txbuf, bf, bf_list);
3958 		ATH_TXBUF_UNLOCK(sc);
3959 	}
3960 	return nacked;
3961 }
3962 
3963 static __inline int
3964 txqactive(struct ath_hal *ah, int qnum)
3965 {
3966 	u_int32_t txqs = 1<<qnum;
3967 	ath_hal_gettxintrtxqs(ah, &txqs);
3968 	return (txqs & (1<<qnum));
3969 }
3970 
3971 /*
3972  * Deferred processing of transmit interrupt; special-cased
3973  * for a single hardware transmit queue (e.g. 5210 and 5211).
3974  */
3975 static void
3976 ath_tx_proc_q0(void *arg, int npending)
3977 {
3978 	struct ath_softc *sc = arg;
3979 	struct ifnet *ifp = sc->sc_ifp;
3980 
3981 	if (txqactive(sc->sc_ah, 0) && ath_tx_processq(sc, &sc->sc_txq[0]))
3982 		sc->sc_lastrx = ath_hal_gettsf64(sc->sc_ah);
3983 	if (txqactive(sc->sc_ah, sc->sc_cabq->axq_qnum))
3984 		ath_tx_processq(sc, sc->sc_cabq);
3985 	ifp->if_drv_flags &= ~IFF_DRV_OACTIVE;
3986 	sc->sc_tx_timer = 0;
3987 
3988 	if (sc->sc_softled)
3989 		ath_led_event(sc, ATH_LED_TX);
3990 
3991 	ath_start(ifp);
3992 }
3993 
3994 /*
3995  * Deferred processing of transmit interrupt; special-cased
3996  * for four hardware queues, 0-3 (e.g. 5212 w/ WME support).
3997  */
3998 static void
3999 ath_tx_proc_q0123(void *arg, int npending)
4000 {
4001 	struct ath_softc *sc = arg;
4002 	struct ifnet *ifp = sc->sc_ifp;
4003 	int nacked;
4004 
4005 	/*
4006 	 * Process each active queue.
4007 	 */
4008 	nacked = 0;
4009 	if (txqactive(sc->sc_ah, 0))
4010 		nacked += ath_tx_processq(sc, &sc->sc_txq[0]);
4011 	if (txqactive(sc->sc_ah, 1))
4012 		nacked += ath_tx_processq(sc, &sc->sc_txq[1]);
4013 	if (txqactive(sc->sc_ah, 2))
4014 		nacked += ath_tx_processq(sc, &sc->sc_txq[2]);
4015 	if (txqactive(sc->sc_ah, 3))
4016 		nacked += ath_tx_processq(sc, &sc->sc_txq[3]);
4017 	if (txqactive(sc->sc_ah, sc->sc_cabq->axq_qnum))
4018 		ath_tx_processq(sc, sc->sc_cabq);
4019 	if (nacked)
4020 		sc->sc_lastrx = ath_hal_gettsf64(sc->sc_ah);
4021 
4022 	ifp->if_drv_flags &= ~IFF_DRV_OACTIVE;
4023 	sc->sc_tx_timer = 0;
4024 
4025 	if (sc->sc_softled)
4026 		ath_led_event(sc, ATH_LED_TX);
4027 
4028 	ath_start(ifp);
4029 }
4030 
4031 /*
4032  * Deferred processing of transmit interrupt.
4033  */
4034 static void
4035 ath_tx_proc(void *arg, int npending)
4036 {
4037 	struct ath_softc *sc = arg;
4038 	struct ifnet *ifp = sc->sc_ifp;
4039 	int i, nacked;
4040 
4041 	/*
4042 	 * Process each active queue.
4043 	 */
4044 	nacked = 0;
4045 	for (i = 0; i < HAL_NUM_TX_QUEUES; i++)
4046 		if (ATH_TXQ_SETUP(sc, i) && txqactive(sc->sc_ah, i))
4047 			nacked += ath_tx_processq(sc, &sc->sc_txq[i]);
4048 	if (nacked)
4049 		sc->sc_lastrx = ath_hal_gettsf64(sc->sc_ah);
4050 
4051 	ifp->if_drv_flags &= ~IFF_DRV_OACTIVE;
4052 	sc->sc_tx_timer = 0;
4053 
4054 	if (sc->sc_softled)
4055 		ath_led_event(sc, ATH_LED_TX);
4056 
4057 	ath_start(ifp);
4058 }
4059 
4060 static void
4061 ath_tx_draintxq(struct ath_softc *sc, struct ath_txq *txq)
4062 {
4063 #ifdef ATH_DEBUG
4064 	struct ath_hal *ah = sc->sc_ah;
4065 #endif
4066 	struct ieee80211_node *ni;
4067 	struct ath_buf *bf;
4068 	u_int ix;
4069 
4070 	/*
4071 	 * NB: this assumes output has been stopped and
4072 	 *     we do not need to block ath_tx_tasklet
4073 	 */
4074 	for (ix = 0;; ix++) {
4075 		ATH_TXQ_LOCK(txq);
4076 		bf = STAILQ_FIRST(&txq->axq_q);
4077 		if (bf == NULL) {
4078 			txq->axq_link = NULL;
4079 			ATH_TXQ_UNLOCK(txq);
4080 			break;
4081 		}
4082 		ATH_TXQ_REMOVE_HEAD(txq, bf_list);
4083 		ATH_TXQ_UNLOCK(txq);
4084 #ifdef ATH_DEBUG
4085 		if (sc->sc_debug & ATH_DEBUG_RESET) {
4086 			ath_printtxbuf(bf, txq->axq_qnum, ix,
4087 				ath_hal_txprocdesc(ah, bf->bf_desc) == HAL_OK);
4088 			ieee80211_dump_pkt(mtod(bf->bf_m, caddr_t),
4089 				bf->bf_m->m_len, 0, -1);
4090 		}
4091 #endif /* ATH_DEBUG */
4092 		bus_dmamap_unload(sc->sc_dmat, bf->bf_dmamap);
4093 		m_freem(bf->bf_m);
4094 		bf->bf_m = NULL;
4095 		ni = bf->bf_node;
4096 		bf->bf_node = NULL;
4097 		if (ni != NULL) {
4098 			/*
4099 			 * Reclaim node reference.
4100 			 */
4101 			ieee80211_free_node(ni);
4102 		}
4103 		ATH_TXBUF_LOCK(sc);
4104 		STAILQ_INSERT_TAIL(&sc->sc_txbuf, bf, bf_list);
4105 		ATH_TXBUF_UNLOCK(sc);
4106 	}
4107 }
4108 
4109 static void
4110 ath_tx_stopdma(struct ath_softc *sc, struct ath_txq *txq)
4111 {
4112 	struct ath_hal *ah = sc->sc_ah;
4113 
4114 	DPRINTF(sc, ATH_DEBUG_RESET, "%s: tx queue [%u] %p, link %p\n",
4115 	    __func__, txq->axq_qnum,
4116 	    (caddr_t)(uintptr_t) ath_hal_gettxbuf(ah, txq->axq_qnum),
4117 	    txq->axq_link);
4118 	(void) ath_hal_stoptxdma(ah, txq->axq_qnum);
4119 }
4120 
4121 /*
4122  * Drain the transmit queues and reclaim resources.
4123  */
4124 static void
4125 ath_draintxq(struct ath_softc *sc)
4126 {
4127 	struct ath_hal *ah = sc->sc_ah;
4128 	struct ifnet *ifp = sc->sc_ifp;
4129 	int i;
4130 
4131 	/* XXX return value */
4132 	if (!sc->sc_invalid) {
4133 		/* don't touch the hardware if marked invalid */
4134 		DPRINTF(sc, ATH_DEBUG_RESET, "%s: tx queue [%u] %p, link %p\n",
4135 		    __func__, sc->sc_bhalq,
4136 		    (caddr_t)(uintptr_t) ath_hal_gettxbuf(ah, sc->sc_bhalq),
4137 		    NULL);
4138 		(void) ath_hal_stoptxdma(ah, sc->sc_bhalq);
4139 		for (i = 0; i < HAL_NUM_TX_QUEUES; i++)
4140 			if (ATH_TXQ_SETUP(sc, i))
4141 				ath_tx_stopdma(sc, &sc->sc_txq[i]);
4142 	}
4143 	for (i = 0; i < HAL_NUM_TX_QUEUES; i++)
4144 		if (ATH_TXQ_SETUP(sc, i))
4145 			ath_tx_draintxq(sc, &sc->sc_txq[i]);
4146 	ath_tx_draintxq(sc, &sc->sc_mcastq);
4147 #ifdef ATH_DEBUG
4148 	if (sc->sc_debug & ATH_DEBUG_RESET) {
4149 		struct ath_buf *bf = STAILQ_FIRST(&sc->sc_bbuf);
4150 		if (bf != NULL && bf->bf_m != NULL) {
4151 			ath_printtxbuf(bf, sc->sc_bhalq, 0,
4152 				ath_hal_txprocdesc(ah, bf->bf_desc) == HAL_OK);
4153 			ieee80211_dump_pkt(mtod(bf->bf_m, caddr_t),
4154 				bf->bf_m->m_len, 0, -1);
4155 		}
4156 	}
4157 #endif /* ATH_DEBUG */
4158 	ifp->if_drv_flags &= ~IFF_DRV_OACTIVE;
4159 	sc->sc_tx_timer = 0;
4160 }
4161 
4162 /*
4163  * Disable the receive h/w in preparation for a reset.
4164  */
4165 static void
4166 ath_stoprecv(struct ath_softc *sc)
4167 {
4168 #define	PA2DESC(_sc, _pa) \
4169 	((struct ath_desc *)((caddr_t)(_sc)->sc_rxdma.dd_desc + \
4170 		((_pa) - (_sc)->sc_rxdma.dd_desc_paddr)))
4171 	struct ath_hal *ah = sc->sc_ah;
4172 
4173 	ath_hal_stoppcurecv(ah);	/* disable PCU */
4174 	ath_hal_setrxfilter(ah, 0);	/* clear recv filter */
4175 	ath_hal_stopdmarecv(ah);	/* disable DMA engine */
4176 	DELAY(3000);			/* 3ms is long enough for 1 frame */
4177 #ifdef ATH_DEBUG
4178 	if (sc->sc_debug & (ATH_DEBUG_RESET | ATH_DEBUG_FATAL)) {
4179 		struct ath_buf *bf;
4180 		u_int ix;
4181 
4182 		printf("%s: rx queue %p, link %p\n", __func__,
4183 			(caddr_t)(uintptr_t) ath_hal_getrxbuf(ah), sc->sc_rxlink);
4184 		ix = 0;
4185 		STAILQ_FOREACH(bf, &sc->sc_rxbuf, bf_list) {
4186 			struct ath_desc *ds = bf->bf_desc;
4187 			HAL_STATUS status = ath_hal_rxprocdesc(ah, ds,
4188 				bf->bf_daddr, PA2DESC(sc, ds->ds_link));
4189 			if (status == HAL_OK || (sc->sc_debug & ATH_DEBUG_FATAL))
4190 				ath_printrxbuf(bf, ix, status == HAL_OK);
4191 			ix++;
4192 		}
4193 	}
4194 #endif
4195 	sc->sc_rxlink = NULL;		/* just in case */
4196 #undef PA2DESC
4197 }
4198 
4199 /*
4200  * Enable the receive h/w following a reset.
4201  */
4202 static int
4203 ath_startrecv(struct ath_softc *sc)
4204 {
4205 	struct ath_hal *ah = sc->sc_ah;
4206 	struct ath_buf *bf;
4207 
4208 	sc->sc_rxlink = NULL;
4209 	STAILQ_FOREACH(bf, &sc->sc_rxbuf, bf_list) {
4210 		int error = ath_rxbuf_init(sc, bf);
4211 		if (error != 0) {
4212 			DPRINTF(sc, ATH_DEBUG_RECV,
4213 				"%s: ath_rxbuf_init failed %d\n",
4214 				__func__, error);
4215 			return error;
4216 		}
4217 	}
4218 
4219 	bf = STAILQ_FIRST(&sc->sc_rxbuf);
4220 	ath_hal_putrxbuf(ah, bf->bf_daddr);
4221 	ath_hal_rxena(ah);		/* enable recv descriptors */
4222 	ath_mode_init(sc);		/* set filters, etc. */
4223 	ath_hal_startpcurecv(ah);	/* re-enable PCU/DMA engine */
4224 	return 0;
4225 }
4226 
4227 /*
4228  * Update internal state after a channel change.
4229  */
4230 static void
4231 ath_chan_change(struct ath_softc *sc, struct ieee80211_channel *chan)
4232 {
4233 	struct ieee80211com *ic = &sc->sc_ic;
4234 	enum ieee80211_phymode mode;
4235 	u_int16_t flags;
4236 
4237 	/*
4238 	 * Change channels and update the h/w rate map
4239 	 * if we're switching; e.g. 11a to 11b/g.
4240 	 */
4241 	mode = ieee80211_chan2mode(ic, chan);
4242 	if (mode != sc->sc_curmode)
4243 		ath_setcurmode(sc, mode);
4244 	/*
4245 	 * Update BPF state.  NB: ethereal et. al. don't handle
4246 	 * merged flags well so pick a unique mode for their use.
4247 	 */
4248 	if (IEEE80211_IS_CHAN_A(chan))
4249 		flags = IEEE80211_CHAN_A;
4250 	/* XXX 11g schizophrenia */
4251 	else if (IEEE80211_IS_CHAN_G(chan) ||
4252 	    IEEE80211_IS_CHAN_PUREG(chan))
4253 		flags = IEEE80211_CHAN_G;
4254 	else
4255 		flags = IEEE80211_CHAN_B;
4256 	if (IEEE80211_IS_CHAN_T(chan))
4257 		flags |= IEEE80211_CHAN_TURBO;
4258 	sc->sc_tx_th.wt_chan_freq = sc->sc_rx_th.wr_chan_freq =
4259 		htole16(chan->ic_freq);
4260 	sc->sc_tx_th.wt_chan_flags = sc->sc_rx_th.wr_chan_flags =
4261 		htole16(flags);
4262 }
4263 
4264 /*
4265  * Poll for a channel clear indication; this is required
4266  * for channels requiring DFS and not previously visited
4267  * and/or with a recent radar detection.
4268  */
4269 static void
4270 ath_dfswait(void *arg)
4271 {
4272 	struct ath_softc *sc = arg;
4273 	struct ath_hal *ah = sc->sc_ah;
4274 	HAL_CHANNEL hchan;
4275 
4276 	ath_hal_radar_wait(ah, &hchan);
4277 	DPRINTF(sc, ATH_DEBUG_DFS, "%s: radar_wait %u/%x/%x\n",
4278 	    __func__, hchan.channel, hchan.channelFlags, hchan.privFlags);
4279 
4280 	if (hchan.privFlags & CHANNEL_INTERFERENCE) {
4281 		if_printf(sc->sc_ifp,
4282 		    "channel %u/0x%x/0x%x has interference\n",
4283 		    hchan.channel, hchan.channelFlags, hchan.privFlags);
4284 		return;
4285 	}
4286 	if ((hchan.privFlags & CHANNEL_DFS) == 0) {
4287 		/* XXX should not happen */
4288 		return;
4289 	}
4290 	if (hchan.privFlags & CHANNEL_DFS_CLEAR) {
4291 		sc->sc_curchan.privFlags |= CHANNEL_DFS_CLEAR;
4292 		sc->sc_ifp->if_drv_flags &= ~IFF_DRV_OACTIVE;
4293 		if_printf(sc->sc_ifp,
4294 		    "channel %u/0x%x/0x%x marked clear\n",
4295 		    hchan.channel, hchan.channelFlags, hchan.privFlags);
4296 	} else
4297 		callout_reset(&sc->sc_dfs_ch, 2 * hz, ath_dfswait, sc);
4298 }
4299 
4300 /*
4301  * Set/change channels.  If the channel is really being changed,
4302  * it's done by reseting the chip.  To accomplish this we must
4303  * first cleanup any pending DMA, then restart stuff after a la
4304  * ath_init.
4305  */
4306 static int
4307 ath_chan_set(struct ath_softc *sc, struct ieee80211_channel *chan)
4308 {
4309 	struct ath_hal *ah = sc->sc_ah;
4310 	struct ieee80211com *ic = &sc->sc_ic;
4311 	HAL_CHANNEL hchan;
4312 
4313 	/*
4314 	 * Convert to a HAL channel description with
4315 	 * the flags constrained to reflect the current
4316 	 * operating mode.
4317 	 */
4318 	hchan.channel = chan->ic_freq;
4319 	hchan.channelFlags = ath_chan2flags(ic, chan);
4320 
4321 	DPRINTF(sc, ATH_DEBUG_RESET,
4322 	    "%s: %u (%u MHz, hal flags 0x%x) -> %u (%u MHz, hal flags 0x%x)\n",
4323 	    __func__,
4324 	    ath_hal_mhz2ieee(ah, sc->sc_curchan.channel,
4325 		sc->sc_curchan.channelFlags),
4326 	    	sc->sc_curchan.channel, sc->sc_curchan.channelFlags,
4327 	    ath_hal_mhz2ieee(ah, hchan.channel, hchan.channelFlags),
4328 	        hchan.channel, hchan.channelFlags);
4329 	if (hchan.channel != sc->sc_curchan.channel ||
4330 	    hchan.channelFlags != sc->sc_curchan.channelFlags) {
4331 		HAL_STATUS status;
4332 
4333 		/*
4334 		 * To switch channels clear any pending DMA operations;
4335 		 * wait long enough for the RX fifo to drain, reset the
4336 		 * hardware at the new frequency, and then re-enable
4337 		 * the relevant bits of the h/w.
4338 		 */
4339 		ath_hal_intrset(ah, 0);		/* disable interrupts */
4340 		ath_draintxq(sc);		/* clear pending tx frames */
4341 		ath_stoprecv(sc);		/* turn off frame recv */
4342 		if (!ath_hal_reset(ah, sc->sc_opmode, &hchan, AH_TRUE, &status)) {
4343 			if_printf(ic->ic_ifp, "%s: unable to reset "
4344 			    "channel %u (%u Mhz, flags 0x%x hal flags 0x%x)\n",
4345 			    __func__, ieee80211_chan2ieee(ic, chan),
4346 			    chan->ic_freq, chan->ic_flags, hchan.channelFlags);
4347 			return EIO;
4348 		}
4349 		sc->sc_curchan = hchan;
4350 		ath_update_txpow(sc);		/* update tx power state */
4351 		sc->sc_diversity = ath_hal_getdiversity(ah);
4352 		sc->sc_calinterval = 1;
4353 		sc->sc_caltries = 0;
4354 
4355 		/*
4356 		 * Re-enable rx framework.
4357 		 */
4358 		if (ath_startrecv(sc) != 0) {
4359 			if_printf(ic->ic_ifp,
4360 				"%s: unable to restart recv logic\n", __func__);
4361 			return EIO;
4362 		}
4363 
4364 		/*
4365 		 * Change channels and update the h/w rate map
4366 		 * if we're switching; e.g. 11a to 11b/g.
4367 		 */
4368 		ic->ic_ibss_chan = chan;
4369 		ath_chan_change(sc, chan);
4370 
4371 		/*
4372 		 * Handle DFS required waiting period to determine
4373 		 * if channel is clear of radar traffic.
4374 		 */
4375 		if (ic->ic_opmode == IEEE80211_M_HOSTAP) {
4376 #define	DFS_AND_NOT_CLEAR(_c) \
4377 	(((_c)->privFlags & (CHANNEL_DFS | CHANNEL_DFS_CLEAR)) == CHANNEL_DFS)
4378 			if (DFS_AND_NOT_CLEAR(&sc->sc_curchan)) {
4379 				if_printf(sc->sc_ifp,
4380 					"wait for DFS clear channel signal\n");
4381 				/* XXX stop sndq */
4382 				sc->sc_ifp->if_drv_flags |= IFF_DRV_OACTIVE;
4383 				callout_reset(&sc->sc_dfs_ch,
4384 					2 * hz, ath_dfswait, sc);
4385 			} else
4386 				callout_stop(&sc->sc_dfs_ch);
4387 #undef DFS_NOT_CLEAR
4388 		}
4389 
4390 		/*
4391 		 * Re-enable interrupts.
4392 		 */
4393 		ath_hal_intrset(ah, sc->sc_imask);
4394 	}
4395 	return 0;
4396 }
4397 
4398 static void
4399 ath_next_scan(void *arg)
4400 {
4401 	struct ath_softc *sc = arg;
4402 	struct ieee80211com *ic = &sc->sc_ic;
4403 
4404 	if (ic->ic_state == IEEE80211_S_SCAN)
4405 		ieee80211_next_scan(ic);
4406 }
4407 
4408 /*
4409  * Periodically recalibrate the PHY to account
4410  * for temperature/environment changes.
4411  */
4412 static void
4413 ath_calibrate(void *arg)
4414 {
4415 	struct ath_softc *sc = arg;
4416 	struct ath_hal *ah = sc->sc_ah;
4417 	HAL_BOOL iqCalDone;
4418 
4419 	sc->sc_stats.ast_per_cal++;
4420 
4421 	if (ath_hal_getrfgain(ah) == HAL_RFGAIN_NEED_CHANGE) {
4422 		/*
4423 		 * Rfgain is out of bounds, reset the chip
4424 		 * to load new gain values.
4425 		 */
4426 		DPRINTF(sc, ATH_DEBUG_CALIBRATE,
4427 			"%s: rfgain change\n", __func__);
4428 		sc->sc_stats.ast_per_rfgain++;
4429 		ath_reset(sc->sc_ifp);
4430 	}
4431 	if (!ath_hal_calibrate(ah, &sc->sc_curchan, &iqCalDone)) {
4432 		DPRINTF(sc, ATH_DEBUG_ANY,
4433 			"%s: calibration of channel %u failed\n",
4434 			__func__, sc->sc_curchan.channel);
4435 		sc->sc_stats.ast_per_calfail++;
4436 	}
4437 	/*
4438 	 * Calibrate noise floor data again in case of change.
4439 	 */
4440 	ath_hal_process_noisefloor(ah);
4441 	/*
4442 	 * Poll more frequently when the IQ calibration is in
4443 	 * progress to speedup loading the final settings.
4444 	 * We temper this aggressive polling with an exponential
4445 	 * back off after 4 tries up to ath_calinterval.
4446 	 */
4447 	if (iqCalDone || sc->sc_calinterval >= ath_calinterval) {
4448 		sc->sc_caltries = 0;
4449 		sc->sc_calinterval = ath_calinterval;
4450 	} else if (sc->sc_caltries > 4) {
4451 		sc->sc_caltries = 0;
4452 		sc->sc_calinterval <<= 1;
4453 		if (sc->sc_calinterval > ath_calinterval)
4454 			sc->sc_calinterval = ath_calinterval;
4455 	}
4456 	KASSERT(0 < sc->sc_calinterval && sc->sc_calinterval <= ath_calinterval,
4457 		("bad calibration interval %u", sc->sc_calinterval));
4458 
4459 	DPRINTF(sc, ATH_DEBUG_CALIBRATE,
4460 		"%s: next +%u (%siqCalDone tries %u)\n", __func__,
4461 		sc->sc_calinterval, iqCalDone ? "" : "!", sc->sc_caltries);
4462 	sc->sc_caltries++;
4463 	callout_reset(&sc->sc_cal_ch, sc->sc_calinterval * hz,
4464 		ath_calibrate, sc);
4465 }
4466 
4467 static int
4468 ath_newstate(struct ieee80211com *ic, enum ieee80211_state nstate, int arg)
4469 {
4470 	struct ifnet *ifp = ic->ic_ifp;
4471 	struct ath_softc *sc = ifp->if_softc;
4472 	struct ath_hal *ah = sc->sc_ah;
4473 	struct ieee80211_node *ni;
4474 	int i, error;
4475 	const u_int8_t *bssid;
4476 	u_int32_t rfilt;
4477 	static const HAL_LED_STATE leds[] = {
4478 	    HAL_LED_INIT,	/* IEEE80211_S_INIT */
4479 	    HAL_LED_SCAN,	/* IEEE80211_S_SCAN */
4480 	    HAL_LED_AUTH,	/* IEEE80211_S_AUTH */
4481 	    HAL_LED_ASSOC, 	/* IEEE80211_S_ASSOC */
4482 	    HAL_LED_RUN, 	/* IEEE80211_S_RUN */
4483 	};
4484 
4485 	DPRINTF(sc, ATH_DEBUG_STATE, "%s: %s -> %s\n", __func__,
4486 		ieee80211_state_name[ic->ic_state],
4487 		ieee80211_state_name[nstate]);
4488 
4489 	callout_stop(&sc->sc_scan_ch);
4490 	callout_stop(&sc->sc_cal_ch);
4491 	callout_stop(&sc->sc_dfs_ch);
4492 	ath_hal_setledstate(ah, leds[nstate]);	/* set LED */
4493 
4494 	if (nstate == IEEE80211_S_INIT) {
4495 		sc->sc_imask &= ~(HAL_INT_SWBA | HAL_INT_BMISS);
4496 		/*
4497 		 * NB: disable interrupts so we don't rx frames.
4498 		 */
4499 		ath_hal_intrset(ah, sc->sc_imask &~ HAL_INT_GLOBAL);
4500 		/*
4501 		 * Notify the rate control algorithm.
4502 		 */
4503 		ath_rate_newstate(sc, nstate);
4504 		goto done;
4505 	}
4506 	ni = ic->ic_bss;
4507 	error = ath_chan_set(sc, ic->ic_curchan);
4508 	if (error != 0)
4509 		goto bad;
4510 	rfilt = ath_calcrxfilter(sc, nstate);
4511 	if (nstate == IEEE80211_S_SCAN)
4512 		bssid = ifp->if_broadcastaddr;
4513 	else
4514 		bssid = ni->ni_bssid;
4515 	ath_hal_setrxfilter(ah, rfilt);
4516 	DPRINTF(sc, ATH_DEBUG_STATE, "%s: RX filter 0x%x bssid %s\n",
4517 		 __func__, rfilt, ether_sprintf(bssid));
4518 
4519 	if (nstate == IEEE80211_S_RUN && ic->ic_opmode == IEEE80211_M_STA)
4520 		ath_hal_setassocid(ah, bssid, ni->ni_associd);
4521 	else
4522 		ath_hal_setassocid(ah, bssid, 0);
4523 	if (ic->ic_flags & IEEE80211_F_PRIVACY) {
4524 		for (i = 0; i < IEEE80211_WEP_NKID; i++)
4525 			if (ath_hal_keyisvalid(ah, i))
4526 				ath_hal_keysetmac(ah, i, bssid);
4527 	}
4528 
4529 	/*
4530 	 * Notify the rate control algorithm so rates
4531 	 * are setup should ath_beacon_alloc be called.
4532 	 */
4533 	ath_rate_newstate(sc, nstate);
4534 
4535 	if (ic->ic_opmode == IEEE80211_M_MONITOR) {
4536 		/* nothing to do */;
4537 	} else if (nstate == IEEE80211_S_RUN) {
4538 		DPRINTF(sc, ATH_DEBUG_STATE,
4539 			"%s(RUN): ic_flags=0x%08x iv=%d bssid=%s "
4540 			"capinfo=0x%04x chan=%d\n"
4541 			 , __func__
4542 			 , ic->ic_flags
4543 			 , ni->ni_intval
4544 			 , ether_sprintf(ni->ni_bssid)
4545 			 , ni->ni_capinfo
4546 			 , ieee80211_chan2ieee(ic, ic->ic_curchan));
4547 
4548 		switch (ic->ic_opmode) {
4549 		case IEEE80211_M_HOSTAP:
4550 		case IEEE80211_M_IBSS:
4551 			/*
4552 			 * Allocate and setup the beacon frame.
4553 			 *
4554 			 * Stop any previous beacon DMA.  This may be
4555 			 * necessary, for example, when an ibss merge
4556 			 * causes reconfiguration; there will be a state
4557 			 * transition from RUN->RUN that means we may
4558 			 * be called with beacon transmission active.
4559 			 */
4560 			ath_hal_stoptxdma(ah, sc->sc_bhalq);
4561 			ath_beacon_free(sc);
4562 			error = ath_beacon_alloc(sc, ni);
4563 			if (error != 0)
4564 				goto bad;
4565 			/*
4566 			 * If joining an adhoc network defer beacon timer
4567 			 * configuration to the next beacon frame so we
4568 			 * have a current TSF to use.  Otherwise we're
4569 			 * starting an ibss/bss so there's no need to delay.
4570 			 */
4571 			if (ic->ic_opmode == IEEE80211_M_IBSS &&
4572 			    ic->ic_bss->ni_tstamp.tsf != 0)
4573 				sc->sc_syncbeacon = 1;
4574 			else
4575 				ath_beacon_config(sc);
4576 			break;
4577 		case IEEE80211_M_STA:
4578 			/*
4579 			 * Allocate a key cache slot to the station.
4580 			 */
4581 			if ((ic->ic_flags & IEEE80211_F_PRIVACY) == 0 &&
4582 			    sc->sc_hasclrkey &&
4583 			    ni->ni_ucastkey.wk_keyix == IEEE80211_KEYIX_NONE)
4584 				ath_setup_stationkey(ni);
4585 			/*
4586 			 * Defer beacon timer configuration to the next
4587 			 * beacon frame so we have a current TSF to use
4588 			 * (any TSF collected when scanning is likely old).
4589 			 */
4590 			sc->sc_syncbeacon = 1;
4591 			break;
4592 		default:
4593 			break;
4594 		}
4595 
4596 		/*
4597 		 * Let the hal process statistics collected during a
4598 		 * scan so it can provide calibrated noise floor data.
4599 		 */
4600 		ath_hal_process_noisefloor(ah);
4601 		/*
4602 		 * Reset rssi stats; maybe not the best place...
4603 		 */
4604 		sc->sc_halstats.ns_avgbrssi = ATH_RSSI_DUMMY_MARKER;
4605 		sc->sc_halstats.ns_avgrssi = ATH_RSSI_DUMMY_MARKER;
4606 		sc->sc_halstats.ns_avgtxrssi = ATH_RSSI_DUMMY_MARKER;
4607 	} else {
4608 		ath_hal_intrset(ah,
4609 			sc->sc_imask &~ (HAL_INT_SWBA | HAL_INT_BMISS));
4610 		sc->sc_imask &= ~(HAL_INT_SWBA | HAL_INT_BMISS);
4611 	}
4612 done:
4613 	/*
4614 	 * Invoke the parent method to complete the work.
4615 	 */
4616 	error = sc->sc_newstate(ic, nstate, arg);
4617 	/*
4618 	 * Finally, start any timers.
4619 	 */
4620 	if (nstate == IEEE80211_S_RUN) {
4621 		/* start periodic recalibration timer */
4622 		callout_reset(&sc->sc_cal_ch, sc->sc_calinterval * hz,
4623 			ath_calibrate, sc);
4624 	} else if (nstate == IEEE80211_S_SCAN) {
4625 		/* start ap/neighbor scan timer */
4626 		callout_reset(&sc->sc_scan_ch, (ath_dwelltime * hz) / 1000,
4627 			ath_next_scan, sc);
4628 	}
4629 bad:
4630 	return error;
4631 }
4632 
4633 /*
4634  * Allocate a key cache slot to the station so we can
4635  * setup a mapping from key index to node. The key cache
4636  * slot is needed for managing antenna state and for
4637  * compression when stations do not use crypto.  We do
4638  * it uniliaterally here; if crypto is employed this slot
4639  * will be reassigned.
4640  */
4641 static void
4642 ath_setup_stationkey(struct ieee80211_node *ni)
4643 {
4644 	struct ieee80211com *ic = ni->ni_ic;
4645 	struct ath_softc *sc = ic->ic_ifp->if_softc;
4646 	ieee80211_keyix keyix, rxkeyix;
4647 
4648 	if (!ath_key_alloc(ic, &ni->ni_ucastkey, &keyix, &rxkeyix)) {
4649 		/*
4650 		 * Key cache is full; we'll fall back to doing
4651 		 * the more expensive lookup in software.  Note
4652 		 * this also means no h/w compression.
4653 		 */
4654 		/* XXX msg+statistic */
4655 	} else {
4656 		/* XXX locking? */
4657 		ni->ni_ucastkey.wk_keyix = keyix;
4658 		ni->ni_ucastkey.wk_rxkeyix = rxkeyix;
4659 		/* NB: this will create a pass-thru key entry */
4660 		ath_keyset(sc, &ni->ni_ucastkey, ni->ni_macaddr, ic->ic_bss);
4661 	}
4662 }
4663 
4664 /*
4665  * Setup driver-specific state for a newly associated node.
4666  * Note that we're called also on a re-associate, the isnew
4667  * param tells us if this is the first time or not.
4668  */
4669 static void
4670 ath_newassoc(struct ieee80211_node *ni, int isnew)
4671 {
4672 	struct ieee80211com *ic = ni->ni_ic;
4673 	struct ath_softc *sc = ic->ic_ifp->if_softc;
4674 
4675 	ath_rate_newassoc(sc, ATH_NODE(ni), isnew);
4676 	if (isnew &&
4677 	    (ic->ic_flags & IEEE80211_F_PRIVACY) == 0 && sc->sc_hasclrkey) {
4678 		KASSERT(ni->ni_ucastkey.wk_keyix == IEEE80211_KEYIX_NONE,
4679 		    ("new assoc with a unicast key already setup (keyix %u)",
4680 		    ni->ni_ucastkey.wk_keyix));
4681 		ath_setup_stationkey(ni);
4682 	}
4683 }
4684 
4685 static int
4686 ath_getchannels(struct ath_softc *sc, u_int cc,
4687 	HAL_BOOL outdoor, HAL_BOOL xchanmode)
4688 {
4689 #define	COMPAT	(CHANNEL_ALL_NOTURBO|CHANNEL_PASSIVE)
4690 #define IS_CHAN_PUBLIC_SAFETY(_c) \
4691 	(((_c)->channelFlags & CHANNEL_5GHZ) && \
4692 	 ((_c)->channel > 4940 && (_c)->channel < 4990))
4693 	struct ieee80211com *ic = &sc->sc_ic;
4694 	struct ifnet *ifp = sc->sc_ifp;
4695 	struct ath_hal *ah = sc->sc_ah;
4696 	HAL_CHANNEL *chans;
4697 	int i, ix, nchan;
4698 
4699 	chans = malloc(IEEE80211_CHAN_MAX * sizeof(HAL_CHANNEL),
4700 			M_TEMP, M_NOWAIT);
4701 	if (chans == NULL) {
4702 		if_printf(ifp, "unable to allocate channel table\n");
4703 		return ENOMEM;
4704 	}
4705 	if (!ath_hal_init_channels(ah, chans, IEEE80211_CHAN_MAX, &nchan,
4706 	    NULL, 0, NULL,
4707 	    cc, HAL_MODE_ALL, outdoor, xchanmode)) {
4708 		u_int32_t rd;
4709 
4710 		ath_hal_getregdomain(ah, &rd);
4711 		if_printf(ifp, "unable to collect channel list from hal; "
4712 			"regdomain likely %u country code %u\n", rd, cc);
4713 		free(chans, M_TEMP);
4714 		return EINVAL;
4715 	}
4716 
4717 	/*
4718 	 * Convert HAL channels to ieee80211 ones and insert
4719 	 * them in the table according to their channel number.
4720 	 */
4721 	for (i = 0; i < nchan; i++) {
4722 		HAL_CHANNEL *c = &chans[i];
4723 		u_int16_t flags;
4724 
4725 		/*
4726 		 * XXX we're not ready to handle the ieee number mapping
4727 		 * for public safety channels as they overlap with any
4728 		 * 2GHz channels; for now use the non-public safety
4729 		 * numbering which is non-overlapping.
4730 		 */
4731 		if (IS_CHAN_PUBLIC_SAFETY(c))
4732 			ix = (c->channel - 4000) / 5;
4733 		else
4734 			ix = ath_hal_mhz2ieee(ah, c->channel, c->channelFlags);
4735 		if (ix > IEEE80211_CHAN_MAX) {
4736 			if_printf(ifp, "bad hal channel %d (%u/%x) ignored\n",
4737 				ix, c->channel, c->channelFlags);
4738 			continue;
4739 		}
4740 		if (ix < 0) {
4741 			/* XXX can't handle stuff <2400 right now */
4742 			if (bootverbose)
4743 				if_printf(ifp, "hal channel %d (%u/%x) "
4744 				    "cannot be handled; ignored\n",
4745 				    ix, c->channel, c->channelFlags);
4746 			continue;
4747 		}
4748 		/*
4749 		 * Calculate net80211 flags; most are compatible
4750 		 * but some need massaging.  Note the static turbo
4751 		 * conversion can be removed once net80211 is updated
4752 		 * to understand static vs. dynamic turbo.
4753 		 */
4754 		flags = c->channelFlags & COMPAT;
4755 		if (c->channelFlags & CHANNEL_STURBO)
4756 			flags |= IEEE80211_CHAN_TURBO;
4757 		if (ic->ic_channels[ix].ic_freq == 0) {
4758 			ic->ic_channels[ix].ic_freq = c->channel;
4759 			ic->ic_channels[ix].ic_flags = flags;
4760 		} else {
4761 			/* channels overlap; e.g. 11g and 11b */
4762 			ic->ic_channels[ix].ic_flags |= flags;
4763 		}
4764 	}
4765 	free(chans, M_TEMP);
4766 	return 0;
4767 #undef IS_CHAN_PUBLIC_SAFETY
4768 #undef COMPAT
4769 }
4770 
4771 static void
4772 ath_led_done(void *arg)
4773 {
4774 	struct ath_softc *sc = arg;
4775 
4776 	sc->sc_blinking = 0;
4777 }
4778 
4779 /*
4780  * Turn the LED off: flip the pin and then set a timer so no
4781  * update will happen for the specified duration.
4782  */
4783 static void
4784 ath_led_off(void *arg)
4785 {
4786 	struct ath_softc *sc = arg;
4787 
4788 	ath_hal_gpioset(sc->sc_ah, sc->sc_ledpin, !sc->sc_ledon);
4789 	callout_reset(&sc->sc_ledtimer, sc->sc_ledoff, ath_led_done, sc);
4790 }
4791 
4792 /*
4793  * Blink the LED according to the specified on/off times.
4794  */
4795 static void
4796 ath_led_blink(struct ath_softc *sc, int on, int off)
4797 {
4798 	DPRINTF(sc, ATH_DEBUG_LED, "%s: on %u off %u\n", __func__, on, off);
4799 	ath_hal_gpioset(sc->sc_ah, sc->sc_ledpin, sc->sc_ledon);
4800 	sc->sc_blinking = 1;
4801 	sc->sc_ledoff = off;
4802 	callout_reset(&sc->sc_ledtimer, on, ath_led_off, sc);
4803 }
4804 
4805 static void
4806 ath_led_event(struct ath_softc *sc, int event)
4807 {
4808 
4809 	sc->sc_ledevent = ticks;	/* time of last event */
4810 	if (sc->sc_blinking)		/* don't interrupt active blink */
4811 		return;
4812 	switch (event) {
4813 	case ATH_LED_POLL:
4814 		ath_led_blink(sc, sc->sc_hwmap[0].ledon,
4815 			sc->sc_hwmap[0].ledoff);
4816 		break;
4817 	case ATH_LED_TX:
4818 		ath_led_blink(sc, sc->sc_hwmap[sc->sc_txrate].ledon,
4819 			sc->sc_hwmap[sc->sc_txrate].ledoff);
4820 		break;
4821 	case ATH_LED_RX:
4822 		ath_led_blink(sc, sc->sc_hwmap[sc->sc_rxrate].ledon,
4823 			sc->sc_hwmap[sc->sc_rxrate].ledoff);
4824 		break;
4825 	}
4826 }
4827 
4828 static void
4829 ath_update_txpow(struct ath_softc *sc)
4830 {
4831 	struct ieee80211com *ic = &sc->sc_ic;
4832 	struct ath_hal *ah = sc->sc_ah;
4833 	u_int32_t txpow;
4834 
4835 	if (sc->sc_curtxpow != ic->ic_txpowlimit) {
4836 		ath_hal_settxpowlimit(ah, ic->ic_txpowlimit);
4837 		/* read back in case value is clamped */
4838 		ath_hal_gettxpowlimit(ah, &txpow);
4839 		ic->ic_txpowlimit = sc->sc_curtxpow = txpow;
4840 	}
4841 	/*
4842 	 * Fetch max tx power level for status requests.
4843 	 */
4844 	ath_hal_getmaxtxpow(sc->sc_ah, &txpow);
4845 	ic->ic_bss->ni_txpower = txpow;
4846 }
4847 
4848 static void
4849 rate_setup(struct ath_softc *sc,
4850 	const HAL_RATE_TABLE *rt, struct ieee80211_rateset *rs)
4851 {
4852 	int i, maxrates;
4853 
4854 	if (rt->rateCount > IEEE80211_RATE_MAXSIZE) {
4855 		DPRINTF(sc, ATH_DEBUG_ANY,
4856 			"%s: rate table too small (%u > %u)\n",
4857 		       __func__, rt->rateCount, IEEE80211_RATE_MAXSIZE);
4858 		maxrates = IEEE80211_RATE_MAXSIZE;
4859 	} else
4860 		maxrates = rt->rateCount;
4861 	for (i = 0; i < maxrates; i++)
4862 		rs->rs_rates[i] = rt->info[i].dot11Rate;
4863 	rs->rs_nrates = maxrates;
4864 }
4865 
4866 static int
4867 ath_rate_setup(struct ath_softc *sc, u_int mode)
4868 {
4869 	struct ath_hal *ah = sc->sc_ah;
4870 	struct ieee80211com *ic = &sc->sc_ic;
4871 	const HAL_RATE_TABLE *rt;
4872 
4873 	switch (mode) {
4874 	case IEEE80211_MODE_11A:
4875 		rt = ath_hal_getratetable(ah, HAL_MODE_11A);
4876 		break;
4877 	case IEEE80211_MODE_11B:
4878 		rt = ath_hal_getratetable(ah, HAL_MODE_11B);
4879 		break;
4880 	case IEEE80211_MODE_11G:
4881 		rt = ath_hal_getratetable(ah, HAL_MODE_11G);
4882 		break;
4883 	case IEEE80211_MODE_TURBO_A:
4884 		/* XXX until static/dynamic turbo is fixed */
4885 		rt = ath_hal_getratetable(ah, HAL_MODE_TURBO);
4886 		break;
4887 	case IEEE80211_MODE_TURBO_G:
4888 		rt = ath_hal_getratetable(ah, HAL_MODE_108G);
4889 		break;
4890 	default:
4891 		DPRINTF(sc, ATH_DEBUG_ANY, "%s: invalid mode %u\n",
4892 			__func__, mode);
4893 		return 0;
4894 	}
4895 	sc->sc_rates[mode] = rt;
4896 	if (rt != NULL) {
4897 		rate_setup(sc, rt, &ic->ic_sup_rates[mode]);
4898 		return 1;
4899 	} else
4900 		return 0;
4901 }
4902 
4903 static void
4904 ath_setcurmode(struct ath_softc *sc, enum ieee80211_phymode mode)
4905 {
4906 #define	N(a)	(sizeof(a)/sizeof(a[0]))
4907 	/* NB: on/off times from the Atheros NDIS driver, w/ permission */
4908 	static const struct {
4909 		u_int		rate;		/* tx/rx 802.11 rate */
4910 		u_int16_t	timeOn;		/* LED on time (ms) */
4911 		u_int16_t	timeOff;	/* LED off time (ms) */
4912 	} blinkrates[] = {
4913 		{ 108,  40,  10 },
4914 		{  96,  44,  11 },
4915 		{  72,  50,  13 },
4916 		{  48,  57,  14 },
4917 		{  36,  67,  16 },
4918 		{  24,  80,  20 },
4919 		{  22, 100,  25 },
4920 		{  18, 133,  34 },
4921 		{  12, 160,  40 },
4922 		{  10, 200,  50 },
4923 		{   6, 240,  58 },
4924 		{   4, 267,  66 },
4925 		{   2, 400, 100 },
4926 		{   0, 500, 130 },
4927 	};
4928 	const HAL_RATE_TABLE *rt;
4929 	int i, j;
4930 
4931 	memset(sc->sc_rixmap, 0xff, sizeof(sc->sc_rixmap));
4932 	rt = sc->sc_rates[mode];
4933 	KASSERT(rt != NULL, ("no h/w rate set for phy mode %u", mode));
4934 	for (i = 0; i < rt->rateCount; i++)
4935 		sc->sc_rixmap[rt->info[i].dot11Rate & IEEE80211_RATE_VAL] = i;
4936 	memset(sc->sc_hwmap, 0, sizeof(sc->sc_hwmap));
4937 	for (i = 0; i < 32; i++) {
4938 		u_int8_t ix = rt->rateCodeToIndex[i];
4939 		if (ix == 0xff) {
4940 			sc->sc_hwmap[i].ledon = (500 * hz) / 1000;
4941 			sc->sc_hwmap[i].ledoff = (130 * hz) / 1000;
4942 			continue;
4943 		}
4944 		sc->sc_hwmap[i].ieeerate =
4945 			rt->info[ix].dot11Rate & IEEE80211_RATE_VAL;
4946 		sc->sc_hwmap[i].txflags = IEEE80211_RADIOTAP_F_DATAPAD;
4947 		if (rt->info[ix].shortPreamble ||
4948 		    rt->info[ix].phy == IEEE80211_T_OFDM)
4949 			sc->sc_hwmap[i].txflags |= IEEE80211_RADIOTAP_F_SHORTPRE;
4950 		/* NB: receive frames include FCS */
4951 		sc->sc_hwmap[i].rxflags = sc->sc_hwmap[i].txflags |
4952 			IEEE80211_RADIOTAP_F_FCS;
4953 		/* setup blink rate table to avoid per-packet lookup */
4954 		for (j = 0; j < N(blinkrates)-1; j++)
4955 			if (blinkrates[j].rate == sc->sc_hwmap[i].ieeerate)
4956 				break;
4957 		/* NB: this uses the last entry if the rate isn't found */
4958 		/* XXX beware of overlow */
4959 		sc->sc_hwmap[i].ledon = (blinkrates[j].timeOn * hz) / 1000;
4960 		sc->sc_hwmap[i].ledoff = (blinkrates[j].timeOff * hz) / 1000;
4961 	}
4962 	sc->sc_currates = rt;
4963 	sc->sc_curmode = mode;
4964 	/*
4965 	 * All protection frames are transmited at 2Mb/s for
4966 	 * 11g, otherwise at 1Mb/s.
4967 	 */
4968 	if (mode == IEEE80211_MODE_11G)
4969 		sc->sc_protrix = ath_tx_findrix(rt, 2*2);
4970 	else
4971 		sc->sc_protrix = ath_tx_findrix(rt, 2*1);
4972 	/* rate index used to send management frames */
4973 	sc->sc_minrateix = 0;
4974 	/*
4975 	 * Setup multicast rate state.
4976 	 */
4977 	/* XXX layering violation */
4978 	sc->sc_mcastrix = ath_tx_findrix(rt, sc->sc_ic.ic_mcast_rate);
4979 	sc->sc_mcastrate = sc->sc_ic.ic_mcast_rate;
4980 	/* NB: caller is responsible for reseting rate control state */
4981 #undef N
4982 }
4983 
4984 #ifdef ATH_DEBUG
4985 static void
4986 ath_printrxbuf(struct ath_buf *bf, u_int ix, int done)
4987 {
4988 	struct ath_desc *ds;
4989 	int i;
4990 
4991 	for (i = 0, ds = bf->bf_desc; i < bf->bf_nseg; i++, ds++) {
4992 		printf("R[%2u] (DS.V:%p DS.P:%p) L:%08x D:%08x%s\n"
4993 		       "      %08x %08x %08x %08x\n",
4994 		    ix, ds, (struct ath_desc *)bf->bf_daddr + i,
4995 		    ds->ds_link, ds->ds_data,
4996 		    !done ? "" : (ds->ds_rxstat.rs_status == 0) ? " *" : " !",
4997 		    ds->ds_ctl0, ds->ds_ctl1,
4998 		    ds->ds_hw[0], ds->ds_hw[1]);
4999 	}
5000 }
5001 
5002 static void
5003 ath_printtxbuf(struct ath_buf *bf, u_int qnum, u_int ix, int done)
5004 {
5005 	struct ath_desc *ds;
5006 	int i;
5007 
5008 	printf("Q%u[%3u]", qnum, ix);
5009 	for (i = 0, ds = bf->bf_desc; i < bf->bf_nseg; i++, ds++) {
5010 		printf(" (DS.V:%p DS.P:%p) L:%08x D:%08x F:04%x%s\n"
5011 		       "        %08x %08x %08x %08x %08x %08x\n",
5012 		    ds, (struct ath_desc *)bf->bf_daddr + i,
5013 		    ds->ds_link, ds->ds_data, bf->bf_flags,
5014 		    !done ? "" : (ds->ds_txstat.ts_status == 0) ? " *" : " !",
5015 		    ds->ds_ctl0, ds->ds_ctl1,
5016 		    ds->ds_hw[0], ds->ds_hw[1], ds->ds_hw[2], ds->ds_hw[3]);
5017 	}
5018 }
5019 #endif /* ATH_DEBUG */
5020 
5021 static void
5022 ath_watchdog(struct ifnet *ifp)
5023 {
5024 	struct ath_softc *sc = ifp->if_softc;
5025 	struct ieee80211com *ic = &sc->sc_ic;
5026 
5027 	ifp->if_timer = 0;
5028 	if ((ifp->if_drv_flags & IFF_DRV_RUNNING) == 0 || sc->sc_invalid)
5029 		return;
5030 	if (sc->sc_tx_timer) {
5031 		if (--sc->sc_tx_timer == 0) {
5032 			if_printf(ifp, "device timeout\n");
5033 			ath_reset(ifp);
5034 			ifp->if_oerrors++;
5035 			sc->sc_stats.ast_watchdog++;
5036 		} else
5037 			ifp->if_timer = 1;
5038 	}
5039 	ieee80211_watchdog(ic);
5040 }
5041 
5042 #ifdef ATH_DIAGAPI
5043 /*
5044  * Diagnostic interface to the HAL.  This is used by various
5045  * tools to do things like retrieve register contents for
5046  * debugging.  The mechanism is intentionally opaque so that
5047  * it can change frequently w/o concern for compatiblity.
5048  */
5049 static int
5050 ath_ioctl_diag(struct ath_softc *sc, struct ath_diag *ad)
5051 {
5052 	struct ath_hal *ah = sc->sc_ah;
5053 	u_int id = ad->ad_id & ATH_DIAG_ID;
5054 	void *indata = NULL;
5055 	void *outdata = NULL;
5056 	u_int32_t insize = ad->ad_in_size;
5057 	u_int32_t outsize = ad->ad_out_size;
5058 	int error = 0;
5059 
5060 	if (ad->ad_id & ATH_DIAG_IN) {
5061 		/*
5062 		 * Copy in data.
5063 		 */
5064 		indata = malloc(insize, M_TEMP, M_NOWAIT);
5065 		if (indata == NULL) {
5066 			error = ENOMEM;
5067 			goto bad;
5068 		}
5069 		error = copyin(ad->ad_in_data, indata, insize);
5070 		if (error)
5071 			goto bad;
5072 	}
5073 	if (ad->ad_id & ATH_DIAG_DYN) {
5074 		/*
5075 		 * Allocate a buffer for the results (otherwise the HAL
5076 		 * returns a pointer to a buffer where we can read the
5077 		 * results).  Note that we depend on the HAL leaving this
5078 		 * pointer for us to use below in reclaiming the buffer;
5079 		 * may want to be more defensive.
5080 		 */
5081 		outdata = malloc(outsize, M_TEMP, M_NOWAIT);
5082 		if (outdata == NULL) {
5083 			error = ENOMEM;
5084 			goto bad;
5085 		}
5086 	}
5087 	if (ath_hal_getdiagstate(ah, id, indata, insize, &outdata, &outsize)) {
5088 		if (outsize < ad->ad_out_size)
5089 			ad->ad_out_size = outsize;
5090 		if (outdata != NULL)
5091 			error = copyout(outdata, ad->ad_out_data,
5092 					ad->ad_out_size);
5093 	} else {
5094 		error = EINVAL;
5095 	}
5096 bad:
5097 	if ((ad->ad_id & ATH_DIAG_IN) && indata != NULL)
5098 		free(indata, M_TEMP);
5099 	if ((ad->ad_id & ATH_DIAG_DYN) && outdata != NULL)
5100 		free(outdata, M_TEMP);
5101 	return error;
5102 }
5103 #endif /* ATH_DIAGAPI */
5104 
5105 static int
5106 ath_ioctl(struct ifnet *ifp, u_long cmd, caddr_t data)
5107 {
5108 #define	IS_RUNNING(ifp) \
5109 	((ifp->if_flags & IFF_UP) && (ifp->if_drv_flags & IFF_DRV_RUNNING))
5110 	struct ath_softc *sc = ifp->if_softc;
5111 	struct ieee80211com *ic = &sc->sc_ic;
5112 	struct ifreq *ifr = (struct ifreq *)data;
5113 	int error = 0;
5114 
5115 	ATH_LOCK(sc);
5116 	switch (cmd) {
5117 	case SIOCSIFFLAGS:
5118 		if (IS_RUNNING(ifp)) {
5119 			/*
5120 			 * To avoid rescanning another access point,
5121 			 * do not call ath_init() here.  Instead,
5122 			 * only reflect promisc mode settings.
5123 			 */
5124 			ath_mode_init(sc);
5125 		} else if (ifp->if_flags & IFF_UP) {
5126 			/*
5127 			 * Beware of being called during attach/detach
5128 			 * to reset promiscuous mode.  In that case we
5129 			 * will still be marked UP but not RUNNING.
5130 			 * However trying to re-init the interface
5131 			 * is the wrong thing to do as we've already
5132 			 * torn down much of our state.  There's
5133 			 * probably a better way to deal with this.
5134 			 */
5135 			if (!sc->sc_invalid && ic->ic_bss != NULL)
5136 				ath_init(sc);	/* XXX lose error */
5137 		} else
5138 			ath_stop_locked(ifp);
5139 		break;
5140 	case SIOCADDMULTI:
5141 	case SIOCDELMULTI:
5142 		/*
5143 		 * The upper layer has already installed/removed
5144 		 * the multicast address(es), just recalculate the
5145 		 * multicast filter for the card.
5146 		 */
5147 		if (ifp->if_drv_flags & IFF_DRV_RUNNING)
5148 			ath_mode_init(sc);
5149 		break;
5150 	case SIOCGATHSTATS:
5151 		/* NB: embed these numbers to get a consistent view */
5152 		sc->sc_stats.ast_tx_packets = ifp->if_opackets;
5153 		sc->sc_stats.ast_rx_packets = ifp->if_ipackets;
5154 		sc->sc_stats.ast_rx_rssi = ieee80211_getrssi(ic);
5155 		sc->sc_stats.ast_rx_noise =
5156 			ath_hal_getchannoise(sc->sc_ah, &sc->sc_curchan);
5157 		sc->sc_stats.ast_tx_rate = sc->sc_hwmap[sc->sc_txrate].ieeerate;
5158 		ATH_UNLOCK(sc);
5159 		/*
5160 		 * NB: Drop the softc lock in case of a page fault;
5161 		 * we'll accept any potential inconsisentcy in the
5162 		 * statistics.  The alternative is to copy the data
5163 		 * to a local structure.
5164 		 */
5165 		return copyout(&sc->sc_stats,
5166 				ifr->ifr_data, sizeof (sc->sc_stats));
5167 #ifdef ATH_DIAGAPI
5168 	case SIOCGATHDIAG:
5169 		ATH_UNLOCK(sc);
5170 		error = ath_ioctl_diag(sc, (struct ath_diag *) ifr);
5171 		ATH_LOCK(sc);
5172 		break;
5173 #endif
5174 	default:
5175 		error = ieee80211_ioctl(ic, cmd, data);
5176 		if (error == ENETRESET) {
5177 			if (IS_RUNNING(ifp) &&
5178 			    ic->ic_roaming != IEEE80211_ROAMING_MANUAL)
5179 				ath_init(sc);	/* XXX lose error */
5180 			error = 0;
5181 		}
5182 		if (error == ERESTART)
5183 			error = IS_RUNNING(ifp) ? ath_reset(ifp) : 0;
5184 		break;
5185 	}
5186 	ATH_UNLOCK(sc);
5187 	return error;
5188 #undef IS_RUNNING
5189 }
5190 
5191 static int
5192 ath_sysctl_slottime(SYSCTL_HANDLER_ARGS)
5193 {
5194 	struct ath_softc *sc = arg1;
5195 	u_int slottime = ath_hal_getslottime(sc->sc_ah);
5196 	int error;
5197 
5198 	error = sysctl_handle_int(oidp, &slottime, 0, req);
5199 	if (error || !req->newptr)
5200 		return error;
5201 	return !ath_hal_setslottime(sc->sc_ah, slottime) ? EINVAL : 0;
5202 }
5203 
5204 static int
5205 ath_sysctl_acktimeout(SYSCTL_HANDLER_ARGS)
5206 {
5207 	struct ath_softc *sc = arg1;
5208 	u_int acktimeout = ath_hal_getacktimeout(sc->sc_ah);
5209 	int error;
5210 
5211 	error = sysctl_handle_int(oidp, &acktimeout, 0, req);
5212 	if (error || !req->newptr)
5213 		return error;
5214 	return !ath_hal_setacktimeout(sc->sc_ah, acktimeout) ? EINVAL : 0;
5215 }
5216 
5217 static int
5218 ath_sysctl_ctstimeout(SYSCTL_HANDLER_ARGS)
5219 {
5220 	struct ath_softc *sc = arg1;
5221 	u_int ctstimeout = ath_hal_getctstimeout(sc->sc_ah);
5222 	int error;
5223 
5224 	error = sysctl_handle_int(oidp, &ctstimeout, 0, req);
5225 	if (error || !req->newptr)
5226 		return error;
5227 	return !ath_hal_setctstimeout(sc->sc_ah, ctstimeout) ? EINVAL : 0;
5228 }
5229 
5230 static int
5231 ath_sysctl_softled(SYSCTL_HANDLER_ARGS)
5232 {
5233 	struct ath_softc *sc = arg1;
5234 	int softled = sc->sc_softled;
5235 	int error;
5236 
5237 	error = sysctl_handle_int(oidp, &softled, 0, req);
5238 	if (error || !req->newptr)
5239 		return error;
5240 	softled = (softled != 0);
5241 	if (softled != sc->sc_softled) {
5242 		if (softled) {
5243 			/* NB: handle any sc_ledpin change */
5244 			ath_hal_gpioCfgOutput(sc->sc_ah, sc->sc_ledpin);
5245 			ath_hal_gpioset(sc->sc_ah, sc->sc_ledpin,
5246 				!sc->sc_ledon);
5247 		}
5248 		sc->sc_softled = softled;
5249 	}
5250 	return 0;
5251 }
5252 
5253 static int
5254 ath_sysctl_rxantenna(SYSCTL_HANDLER_ARGS)
5255 {
5256 	struct ath_softc *sc = arg1;
5257 	u_int defantenna = ath_hal_getdefantenna(sc->sc_ah);
5258 	int error;
5259 
5260 	error = sysctl_handle_int(oidp, &defantenna, 0, req);
5261 	if (!error && req->newptr)
5262 		ath_hal_setdefantenna(sc->sc_ah, defantenna);
5263 	return error;
5264 }
5265 
5266 static int
5267 ath_sysctl_diversity(SYSCTL_HANDLER_ARGS)
5268 {
5269 	struct ath_softc *sc = arg1;
5270 	u_int diversity = ath_hal_getdiversity(sc->sc_ah);
5271 	int error;
5272 
5273 	error = sysctl_handle_int(oidp, &diversity, 0, req);
5274 	if (error || !req->newptr)
5275 		return error;
5276 	if (!ath_hal_setdiversity(sc->sc_ah, diversity))
5277 		return EINVAL;
5278 	sc->sc_diversity = diversity;
5279 	return 0;
5280 }
5281 
5282 static int
5283 ath_sysctl_diag(SYSCTL_HANDLER_ARGS)
5284 {
5285 	struct ath_softc *sc = arg1;
5286 	u_int32_t diag;
5287 	int error;
5288 
5289 	if (!ath_hal_getdiag(sc->sc_ah, &diag))
5290 		return EINVAL;
5291 	error = sysctl_handle_int(oidp, &diag, 0, req);
5292 	if (error || !req->newptr)
5293 		return error;
5294 	return !ath_hal_setdiag(sc->sc_ah, diag) ? EINVAL : 0;
5295 }
5296 
5297 static int
5298 ath_sysctl_tpscale(SYSCTL_HANDLER_ARGS)
5299 {
5300 	struct ath_softc *sc = arg1;
5301 	struct ifnet *ifp = sc->sc_ifp;
5302 	u_int32_t scale;
5303 	int error;
5304 
5305 	ath_hal_gettpscale(sc->sc_ah, &scale);
5306 	error = sysctl_handle_int(oidp, &scale, 0, req);
5307 	if (error || !req->newptr)
5308 		return error;
5309 	return !ath_hal_settpscale(sc->sc_ah, scale) ? EINVAL : ath_reset(ifp);
5310 }
5311 
5312 static int
5313 ath_sysctl_tpc(SYSCTL_HANDLER_ARGS)
5314 {
5315 	struct ath_softc *sc = arg1;
5316 	u_int tpc = ath_hal_gettpc(sc->sc_ah);
5317 	int error;
5318 
5319 	error = sysctl_handle_int(oidp, &tpc, 0, req);
5320 	if (error || !req->newptr)
5321 		return error;
5322 	return !ath_hal_settpc(sc->sc_ah, tpc) ? EINVAL : 0;
5323 }
5324 
5325 static int
5326 ath_sysctl_rfkill(SYSCTL_HANDLER_ARGS)
5327 {
5328 	struct ath_softc *sc = arg1;
5329 	struct ath_hal *ah = sc->sc_ah;
5330 	u_int rfkill = ath_hal_getrfkill(ah);
5331 	int error;
5332 
5333 	error = sysctl_handle_int(oidp, &rfkill, 0, req);
5334 	if (error || !req->newptr)
5335 		return error;
5336 	if (rfkill == ath_hal_getrfkill(ah))	/* unchanged */
5337 		return 0;
5338 	if (!ath_hal_setrfkill(ah, rfkill) || ath_reset(sc->sc_ifp) != 0)
5339 		return EINVAL;
5340 	else
5341 		return 0;
5342 }
5343 
5344 static int
5345 ath_sysctl_rfsilent(SYSCTL_HANDLER_ARGS)
5346 {
5347 	struct ath_softc *sc = arg1;
5348 	u_int rfsilent;
5349 	int error;
5350 
5351 	ath_hal_getrfsilent(sc->sc_ah, &rfsilent);
5352 	error = sysctl_handle_int(oidp, &rfsilent, 0, req);
5353 	if (error || !req->newptr)
5354 		return error;
5355 	if (!ath_hal_setrfsilent(sc->sc_ah, rfsilent))
5356 		return EINVAL;
5357 	sc->sc_rfsilentpin = rfsilent & 0x1c;
5358 	sc->sc_rfsilentpol = (rfsilent & 0x2) != 0;
5359 	return 0;
5360 }
5361 
5362 static int
5363 ath_sysctl_regdomain(SYSCTL_HANDLER_ARGS)
5364 {
5365 	struct ath_softc *sc = arg1;
5366 	u_int32_t rd;
5367 	int error;
5368 
5369 	if (!ath_hal_getregdomain(sc->sc_ah, &rd))
5370 		return EINVAL;
5371 	error = sysctl_handle_int(oidp, &rd, 0, req);
5372 	if (error || !req->newptr)
5373 		return error;
5374 	return !ath_hal_setregdomain(sc->sc_ah, rd) ? EINVAL : 0;
5375 }
5376 
5377 static int
5378 ath_sysctl_tpack(SYSCTL_HANDLER_ARGS)
5379 {
5380 	struct ath_softc *sc = arg1;
5381 	u_int32_t tpack;
5382 	int error;
5383 
5384 	ath_hal_gettpack(sc->sc_ah, &tpack);
5385 	error = sysctl_handle_int(oidp, &tpack, 0, req);
5386 	if (error || !req->newptr)
5387 		return error;
5388 	return !ath_hal_settpack(sc->sc_ah, tpack) ? EINVAL : 0;
5389 }
5390 
5391 static int
5392 ath_sysctl_tpcts(SYSCTL_HANDLER_ARGS)
5393 {
5394 	struct ath_softc *sc = arg1;
5395 	u_int32_t tpcts;
5396 	int error;
5397 
5398 	ath_hal_gettpcts(sc->sc_ah, &tpcts);
5399 	error = sysctl_handle_int(oidp, &tpcts, 0, req);
5400 	if (error || !req->newptr)
5401 		return error;
5402 	return !ath_hal_settpcts(sc->sc_ah, tpcts) ? EINVAL : 0;
5403 }
5404 
5405 static void
5406 ath_sysctlattach(struct ath_softc *sc)
5407 {
5408 	struct sysctl_ctx_list *ctx = device_get_sysctl_ctx(sc->sc_dev);
5409 	struct sysctl_oid *tree = device_get_sysctl_tree(sc->sc_dev);
5410 	struct ath_hal *ah = sc->sc_ah;
5411 
5412 	ath_hal_getcountrycode(sc->sc_ah, &sc->sc_countrycode);
5413 	SYSCTL_ADD_INT(ctx, SYSCTL_CHILDREN(tree), OID_AUTO,
5414 		"countrycode", CTLFLAG_RD, &sc->sc_countrycode, 0,
5415 		"EEPROM country code");
5416 	SYSCTL_ADD_PROC(ctx, SYSCTL_CHILDREN(tree), OID_AUTO,
5417 		"regdomain", CTLTYPE_INT | CTLFLAG_RW, sc, 0,
5418 		ath_sysctl_regdomain, "I", "EEPROM regdomain code");
5419 #ifdef	ATH_DEBUG
5420 	sc->sc_debug = ath_debug;
5421 	SYSCTL_ADD_INT(ctx, SYSCTL_CHILDREN(tree), OID_AUTO,
5422 		"debug", CTLFLAG_RW, &sc->sc_debug, 0,
5423 		"control debugging printfs");
5424 #endif
5425 	SYSCTL_ADD_PROC(ctx, SYSCTL_CHILDREN(tree), OID_AUTO,
5426 		"slottime", CTLTYPE_INT | CTLFLAG_RW, sc, 0,
5427 		ath_sysctl_slottime, "I", "802.11 slot time (us)");
5428 	SYSCTL_ADD_PROC(ctx, SYSCTL_CHILDREN(tree), OID_AUTO,
5429 		"acktimeout", CTLTYPE_INT | CTLFLAG_RW, sc, 0,
5430 		ath_sysctl_acktimeout, "I", "802.11 ACK timeout (us)");
5431 	SYSCTL_ADD_PROC(ctx, SYSCTL_CHILDREN(tree), OID_AUTO,
5432 		"ctstimeout", CTLTYPE_INT | CTLFLAG_RW, sc, 0,
5433 		ath_sysctl_ctstimeout, "I", "802.11 CTS timeout (us)");
5434 	SYSCTL_ADD_PROC(ctx, SYSCTL_CHILDREN(tree), OID_AUTO,
5435 		"softled", CTLTYPE_INT | CTLFLAG_RW, sc, 0,
5436 		ath_sysctl_softled, "I", "enable/disable software LED support");
5437 	SYSCTL_ADD_INT(ctx, SYSCTL_CHILDREN(tree), OID_AUTO,
5438 		"ledpin", CTLFLAG_RW, &sc->sc_ledpin, 0,
5439 		"GPIO pin connected to LED");
5440 	SYSCTL_ADD_INT(ctx, SYSCTL_CHILDREN(tree), OID_AUTO,
5441 		"ledon", CTLFLAG_RW, &sc->sc_ledon, 0,
5442 		"setting to turn LED on");
5443 	SYSCTL_ADD_INT(ctx, SYSCTL_CHILDREN(tree), OID_AUTO,
5444 		"ledidle", CTLFLAG_RW, &sc->sc_ledidle, 0,
5445 		"idle time for inactivity LED (ticks)");
5446 	SYSCTL_ADD_INT(ctx, SYSCTL_CHILDREN(tree), OID_AUTO,
5447 		"txantenna", CTLFLAG_RW, &sc->sc_txantenna, 0,
5448 		"tx antenna (0=auto)");
5449 	SYSCTL_ADD_PROC(ctx, SYSCTL_CHILDREN(tree), OID_AUTO,
5450 		"rxantenna", CTLTYPE_INT | CTLFLAG_RW, sc, 0,
5451 		ath_sysctl_rxantenna, "I", "default/rx antenna");
5452 	if (ath_hal_hasdiversity(ah))
5453 		SYSCTL_ADD_PROC(ctx, SYSCTL_CHILDREN(tree), OID_AUTO,
5454 			"diversity", CTLTYPE_INT | CTLFLAG_RW, sc, 0,
5455 			ath_sysctl_diversity, "I", "antenna diversity");
5456 	sc->sc_txintrperiod = ATH_TXINTR_PERIOD;
5457 	SYSCTL_ADD_INT(ctx, SYSCTL_CHILDREN(tree), OID_AUTO,
5458 		"txintrperiod", CTLFLAG_RW, &sc->sc_txintrperiod, 0,
5459 		"tx descriptor batching");
5460 	SYSCTL_ADD_PROC(ctx, SYSCTL_CHILDREN(tree), OID_AUTO,
5461 		"diag", CTLTYPE_INT | CTLFLAG_RW, sc, 0,
5462 		ath_sysctl_diag, "I", "h/w diagnostic control");
5463 	SYSCTL_ADD_PROC(ctx, SYSCTL_CHILDREN(tree), OID_AUTO,
5464 		"tpscale", CTLTYPE_INT | CTLFLAG_RW, sc, 0,
5465 		ath_sysctl_tpscale, "I", "tx power scaling");
5466 	if (ath_hal_hastpc(ah)) {
5467 		SYSCTL_ADD_PROC(ctx, SYSCTL_CHILDREN(tree), OID_AUTO,
5468 			"tpc", CTLTYPE_INT | CTLFLAG_RW, sc, 0,
5469 			ath_sysctl_tpc, "I", "enable/disable per-packet TPC");
5470 		SYSCTL_ADD_PROC(ctx, SYSCTL_CHILDREN(tree), OID_AUTO,
5471 			"tpack", CTLTYPE_INT | CTLFLAG_RW, sc, 0,
5472 			ath_sysctl_tpack, "I", "tx power for ack frames");
5473 		SYSCTL_ADD_PROC(ctx, SYSCTL_CHILDREN(tree), OID_AUTO,
5474 			"tpcts", CTLTYPE_INT | CTLFLAG_RW, sc, 0,
5475 			ath_sysctl_tpcts, "I", "tx power for cts frames");
5476 	}
5477 	if (ath_hal_hasrfsilent(ah)) {
5478 		SYSCTL_ADD_PROC(ctx, SYSCTL_CHILDREN(tree), OID_AUTO,
5479 			"rfsilent", CTLTYPE_INT | CTLFLAG_RW, sc, 0,
5480 			ath_sysctl_rfsilent, "I", "h/w RF silent config");
5481 		SYSCTL_ADD_PROC(ctx, SYSCTL_CHILDREN(tree), OID_AUTO,
5482 			"rfkill", CTLTYPE_INT | CTLFLAG_RW, sc, 0,
5483 			ath_sysctl_rfkill, "I", "enable/disable RF kill switch");
5484 	}
5485 	sc->sc_monpass = HAL_RXERR_DECRYPT | HAL_RXERR_MIC;
5486 	SYSCTL_ADD_INT(ctx, SYSCTL_CHILDREN(tree), OID_AUTO,
5487 		"monpass", CTLFLAG_RW, &sc->sc_monpass, 0,
5488 		"mask of error frames to pass when monitoring");
5489 }
5490 
5491 static void
5492 ath_bpfattach(struct ath_softc *sc)
5493 {
5494 	struct ifnet *ifp = sc->sc_ifp;
5495 
5496 	bpfattach2(ifp, DLT_IEEE802_11_RADIO,
5497 		sizeof(struct ieee80211_frame) + sizeof(sc->sc_tx_th),
5498 		&sc->sc_drvbpf);
5499 	/*
5500 	 * Initialize constant fields.
5501 	 * XXX make header lengths a multiple of 32-bits so subsequent
5502 	 *     headers are properly aligned; this is a kludge to keep
5503 	 *     certain applications happy.
5504 	 *
5505 	 * NB: the channel is setup each time we transition to the
5506 	 *     RUN state to avoid filling it in for each frame.
5507 	 */
5508 	sc->sc_tx_th_len = roundup(sizeof(sc->sc_tx_th), sizeof(u_int32_t));
5509 	sc->sc_tx_th.wt_ihdr.it_len = htole16(sc->sc_tx_th_len);
5510 	sc->sc_tx_th.wt_ihdr.it_present = htole32(ATH_TX_RADIOTAP_PRESENT);
5511 
5512 	sc->sc_rx_th_len = roundup(sizeof(sc->sc_rx_th), sizeof(u_int32_t));
5513 	sc->sc_rx_th.wr_ihdr.it_len = htole16(sc->sc_rx_th_len);
5514 	sc->sc_rx_th.wr_ihdr.it_present = htole32(ATH_RX_RADIOTAP_PRESENT);
5515 }
5516 
5517 static int
5518 ath_tx_raw_start(struct ath_softc *sc, struct ieee80211_node *ni,
5519 	struct ath_buf *bf, struct mbuf *m0,
5520 	const struct ieee80211_bpf_params *params)
5521 {
5522 	struct ieee80211com *ic = &sc->sc_ic;
5523 	struct ath_hal *ah = sc->sc_ah;
5524 	int error, ismcast, ismrr;
5525 	int hdrlen, pktlen, try0, txantenna;
5526 	u_int8_t rix, cix, txrate, ctsrate, rate1, rate2, rate3;
5527 	struct ath_txq *txq;
5528 	struct ieee80211_frame *wh;
5529 	u_int flags, ctsduration;
5530 	HAL_PKT_TYPE atype;
5531 	const HAL_RATE_TABLE *rt;
5532 	struct ath_desc *ds;
5533 	u_int pri;
5534 
5535 	wh = mtod(m0, struct ieee80211_frame *);
5536 	ismcast = IEEE80211_IS_MULTICAST(wh->i_addr1);
5537 	hdrlen = ieee80211_anyhdrsize(wh);
5538 	/*
5539 	 * Packet length must not include any
5540 	 * pad bytes; deduct them here.
5541 	 */
5542 	/* XXX honor IEEE80211_BPF_DATAPAD */
5543 	pktlen = m0->m_pkthdr.len - (hdrlen & 3) + IEEE80211_CRC_LEN;
5544 
5545 	error = ath_tx_dmasetup(sc, bf, m0);
5546 	if (error != 0)
5547 		return error;
5548 	m0 = bf->bf_m;				/* NB: may have changed */
5549 	wh = mtod(m0, struct ieee80211_frame *);
5550 	bf->bf_node = ni;			/* NB: held reference */
5551 
5552 	flags = HAL_TXDESC_CLRDMASK;		/* XXX needed for crypto errs */
5553 	flags |= HAL_TXDESC_INTREQ;		/* force interrupt */
5554 	if (params->ibp_flags & IEEE80211_BPF_RTS)
5555 		flags |= HAL_TXDESC_RTSENA;
5556 	else if (params->ibp_flags & IEEE80211_BPF_CTS)
5557 		flags |= HAL_TXDESC_CTSENA;
5558 	/* XXX leave ismcast to injector? */
5559 	if ((params->ibp_flags & IEEE80211_BPF_NOACK) || ismcast)
5560 		flags |= HAL_TXDESC_NOACK;
5561 
5562 	rt = sc->sc_currates;
5563 	KASSERT(rt != NULL, ("no rate table, mode %u", sc->sc_curmode));
5564 	rix = ath_tx_findrix(rt, params->ibp_rate0);
5565 	txrate = rt->info[rix].rateCode;
5566 	if (params->ibp_flags & IEEE80211_BPF_SHORTPRE)
5567 		txrate |= rt->info[rix].shortPreamble;
5568 	sc->sc_txrate = txrate;
5569 	try0 = params->ibp_try0;
5570 	ismrr = (params->ibp_try1 != 0);
5571 	txantenna = params->ibp_pri >> 2;
5572 	if (txantenna == 0)			/* XXX? */
5573 		txantenna = sc->sc_txantenna;
5574 	ctsduration = 0;
5575 	if (flags & (HAL_TXDESC_CTSENA | HAL_TXDESC_RTSENA)) {
5576 		cix = ath_tx_findrix(rt, params->ibp_ctsrate);
5577 		ctsrate = rt->info[cix].rateCode;
5578 		if (params->ibp_flags & IEEE80211_BPF_SHORTPRE) {
5579 			ctsrate |= rt->info[cix].shortPreamble;
5580 			if (flags & HAL_TXDESC_RTSENA)		/* SIFS + CTS */
5581 				ctsduration += rt->info[cix].spAckDuration;
5582 			ctsduration += ath_hal_computetxtime(ah,
5583 				rt, pktlen, rix, AH_TRUE);
5584 			if ((flags & HAL_TXDESC_NOACK) == 0)	/* SIFS + ACK */
5585 				ctsduration += rt->info[rix].spAckDuration;
5586 		} else {
5587 			if (flags & HAL_TXDESC_RTSENA)		/* SIFS + CTS */
5588 				ctsduration += rt->info[cix].lpAckDuration;
5589 			ctsduration += ath_hal_computetxtime(ah,
5590 				rt, pktlen, rix, AH_FALSE);
5591 			if ((flags & HAL_TXDESC_NOACK) == 0)	/* SIFS + ACK */
5592 				ctsduration += rt->info[rix].lpAckDuration;
5593 		}
5594 		ismrr = 0;			/* XXX */
5595 	} else
5596 		ctsrate = 0;
5597 	pri = params->ibp_pri & 3;
5598 	/*
5599 	 * NB: we mark all packets as type PSPOLL so the h/w won't
5600 	 * set the sequence number, duration, etc.
5601 	 */
5602 	atype = HAL_PKT_TYPE_PSPOLL;
5603 
5604 	if (IFF_DUMPPKTS(sc, ATH_DEBUG_XMIT))
5605 		ieee80211_dump_pkt(mtod(m0, caddr_t), m0->m_len,
5606 			sc->sc_hwmap[txrate].ieeerate, -1);
5607 
5608 	if (bpf_peers_present(ic->ic_rawbpf))
5609 		bpf_mtap(ic->ic_rawbpf, m0);
5610 	if (bpf_peers_present(sc->sc_drvbpf)) {
5611 		u_int64_t tsf = ath_hal_gettsf64(ah);
5612 
5613 		sc->sc_tx_th.wt_tsf = htole64(tsf);
5614 		sc->sc_tx_th.wt_flags = sc->sc_hwmap[txrate].txflags;
5615 		if (wh->i_fc[1] & IEEE80211_FC1_WEP)
5616 			sc->sc_tx_th.wt_flags |= IEEE80211_RADIOTAP_F_WEP;
5617 		sc->sc_tx_th.wt_rate = sc->sc_hwmap[txrate].ieeerate;
5618 		sc->sc_tx_th.wt_txpower = ni->ni_txpower;
5619 		sc->sc_tx_th.wt_antenna = sc->sc_txantenna;
5620 
5621 		bpf_mtap2(sc->sc_drvbpf,
5622 			&sc->sc_tx_th, sc->sc_tx_th_len, m0);
5623 	}
5624 
5625 	/*
5626 	 * Formulate first tx descriptor with tx controls.
5627 	 */
5628 	ds = bf->bf_desc;
5629 	/* XXX check return value? */
5630 	ath_hal_setuptxdesc(ah, ds
5631 		, pktlen		/* packet length */
5632 		, hdrlen		/* header length */
5633 		, atype			/* Atheros packet type */
5634 		, params->ibp_power	/* txpower */
5635 		, txrate, try0		/* series 0 rate/tries */
5636 		, HAL_TXKEYIX_INVALID	/* key cache index */
5637 		, txantenna		/* antenna mode */
5638 		, flags			/* flags */
5639 		, ctsrate		/* rts/cts rate */
5640 		, ctsduration		/* rts/cts duration */
5641 	);
5642 	bf->bf_flags = flags;
5643 
5644 	if (ismrr) {
5645 		rix = ath_tx_findrix(rt, params->ibp_rate1);
5646 		rate1 = rt->info[rix].rateCode;
5647 		if (params->ibp_flags & IEEE80211_BPF_SHORTPRE)
5648 			rate1 |= rt->info[rix].shortPreamble;
5649 		if (params->ibp_try2) {
5650 			rix = ath_tx_findrix(rt, params->ibp_rate2);
5651 			rate2 = rt->info[rix].rateCode;
5652 			if (params->ibp_flags & IEEE80211_BPF_SHORTPRE)
5653 				rate2 |= rt->info[rix].shortPreamble;
5654 		} else
5655 			rate2 = 0;
5656 		if (params->ibp_try3) {
5657 			rix = ath_tx_findrix(rt, params->ibp_rate3);
5658 			rate3 = rt->info[rix].rateCode;
5659 			if (params->ibp_flags & IEEE80211_BPF_SHORTPRE)
5660 				rate3 |= rt->info[rix].shortPreamble;
5661 		} else
5662 			rate3 = 0;
5663 		ath_hal_setupxtxdesc(ah, ds
5664 			, rate1, params->ibp_try1	/* series 1 */
5665 			, rate2, params->ibp_try2	/* series 2 */
5666 			, rate3, params->ibp_try3	/* series 3 */
5667 		);
5668 	}
5669 
5670 	/*
5671 	 * When servicing one or more stations in power-save mode
5672 	 * (or) if there is some mcast data waiting on the mcast
5673 	 * queue (to prevent out of order delivery) multicast
5674 	 * frames must be buffered until after the beacon.
5675 	 */
5676 	txq = sc->sc_ac2q[pri];
5677 	if (ismcast && (ic->ic_ps_sta || sc->sc_mcastq.axq_depth))
5678 		txq = &sc->sc_mcastq;
5679 	ath_tx_handoff(sc, txq, bf);
5680 	return 0;
5681 }
5682 
5683 static int
5684 ath_raw_xmit(struct ieee80211_node *ni, struct mbuf *m,
5685 	const struct ieee80211_bpf_params *params)
5686 {
5687 	struct ieee80211com *ic = ni->ni_ic;
5688 	struct ifnet *ifp = ic->ic_ifp;
5689 	struct ath_softc *sc = ifp->if_softc;
5690 	struct ath_buf *bf;
5691 
5692 	if ((ifp->if_drv_flags & IFF_DRV_RUNNING) == 0 || sc->sc_invalid) {
5693 		m_freem(m);
5694 		return ENETDOWN;
5695 	}
5696 	/*
5697 	 * Grab a TX buffer and associated resources.
5698 	 */
5699 	ATH_TXBUF_LOCK(sc);
5700 	bf = STAILQ_FIRST(&sc->sc_txbuf);
5701 	if (bf != NULL)
5702 		STAILQ_REMOVE_HEAD(&sc->sc_txbuf, bf_list);
5703 	ATH_TXBUF_UNLOCK(sc);
5704 	if (bf == NULL) {
5705 		DPRINTF(sc, ATH_DEBUG_XMIT, "%s: out of xmit buffers\n",
5706 			__func__);
5707 		sc->sc_stats.ast_tx_qstop++;
5708 		ifp->if_drv_flags |= IFF_DRV_OACTIVE;
5709 		m_freem(m);
5710 		return ENOBUFS;
5711 	}
5712 
5713 	ifp->if_opackets++;
5714 	sc->sc_stats.ast_tx_raw++;
5715 
5716 	if (params == NULL) {
5717 		/*
5718 		 * Legacy path; interpret frame contents to decide
5719 		 * precisely how to send the frame.
5720 		 */
5721 		if (ath_tx_start(sc, ni, bf, m))
5722 			goto bad;
5723 	} else {
5724 		/*
5725 		 * Caller supplied explicit parameters to use in
5726 		 * sending the frame.
5727 		 */
5728 		if (ath_tx_raw_start(sc, ni, bf, m, params))
5729 			goto bad;
5730 	}
5731 	sc->sc_tx_timer = 5;
5732 	ifp->if_timer = 1;
5733 
5734 	return 0;
5735 bad:
5736 	ifp->if_oerrors++;
5737 	ATH_TXBUF_LOCK(sc);
5738 	STAILQ_INSERT_TAIL(&sc->sc_txbuf, bf, bf_list);
5739 	ATH_TXBUF_UNLOCK(sc);
5740 	ieee80211_free_node(ni);
5741 	return EIO;		/* XXX */
5742 }
5743 
5744 /*
5745  * Announce various information on device/driver attach.
5746  */
5747 static void
5748 ath_announce(struct ath_softc *sc)
5749 {
5750 #define	HAL_MODE_DUALBAND	(HAL_MODE_11A|HAL_MODE_11B)
5751 	struct ifnet *ifp = sc->sc_ifp;
5752 	struct ath_hal *ah = sc->sc_ah;
5753 	u_int modes, cc;
5754 
5755 	if_printf(ifp, "mac %d.%d phy %d.%d",
5756 		ah->ah_macVersion, ah->ah_macRev,
5757 		ah->ah_phyRev >> 4, ah->ah_phyRev & 0xf);
5758 	/*
5759 	 * Print radio revision(s).  We check the wireless modes
5760 	 * to avoid falsely printing revs for inoperable parts.
5761 	 * Dual-band radio revs are returned in the 5Ghz rev number.
5762 	 */
5763 	ath_hal_getcountrycode(ah, &cc);
5764 	modes = ath_hal_getwirelessmodes(ah, cc);
5765 	if ((modes & HAL_MODE_DUALBAND) == HAL_MODE_DUALBAND) {
5766 		if (ah->ah_analog5GhzRev && ah->ah_analog2GhzRev)
5767 			printf(" 5ghz radio %d.%d 2ghz radio %d.%d",
5768 				ah->ah_analog5GhzRev >> 4,
5769 				ah->ah_analog5GhzRev & 0xf,
5770 				ah->ah_analog2GhzRev >> 4,
5771 				ah->ah_analog2GhzRev & 0xf);
5772 		else
5773 			printf(" radio %d.%d", ah->ah_analog5GhzRev >> 4,
5774 				ah->ah_analog5GhzRev & 0xf);
5775 	} else
5776 		printf(" radio %d.%d", ah->ah_analog5GhzRev >> 4,
5777 			ah->ah_analog5GhzRev & 0xf);
5778 	printf("\n");
5779 	if (bootverbose) {
5780 		int i;
5781 		for (i = 0; i <= WME_AC_VO; i++) {
5782 			struct ath_txq *txq = sc->sc_ac2q[i];
5783 			if_printf(ifp, "Use hw queue %u for %s traffic\n",
5784 				txq->axq_qnum, ieee80211_wme_acnames[i]);
5785 		}
5786 		if_printf(ifp, "Use hw queue %u for CAB traffic\n",
5787 			sc->sc_cabq->axq_qnum);
5788 		if_printf(ifp, "Use hw queue %u for beacons\n", sc->sc_bhalq);
5789 	}
5790 	if (ath_rxbuf != ATH_RXBUF)
5791 		if_printf(ifp, "using %u rx buffers\n", ath_rxbuf);
5792 	if (ath_txbuf != ATH_TXBUF)
5793 		if_printf(ifp, "using %u tx buffers\n", ath_txbuf);
5794 #undef HAL_MODE_DUALBAND
5795 }
5796