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