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