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