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