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