xref: /freebsd/sys/dev/ath/if_ath.c (revision 0efd6615cd5f39b67cec82a7034e655f3b5801e3)
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(const struct ath_buf *bf, u_int ix, int);
262 static	void ath_printtxbuf(const struct ath_buf *bf, u_int qnum, u_int ix, int done);
263 #else
264 #define	IFF_DUMPPKTS(sc, m) \
265 	((sc->sc_ifp->if_flags & (IFF_DEBUG|IFF_LINK2)) == (IFF_DEBUG|IFF_LINK2))
266 #define	DPRINTF(sc, m, fmt, ...) do {				\
267 	(void) sc;						\
268 } while (0)
269 #define	KEYPRINTF(sc, k, ix, mac) do {				\
270 	(void) sc;						\
271 } while (0)
272 #endif
273 
274 MALLOC_DEFINE(M_ATHDEV, "athdev", "ath driver dma buffers");
275 
276 int
277 ath_attach(u_int16_t devid, struct ath_softc *sc)
278 {
279 	struct ifnet *ifp;
280 	struct ieee80211com *ic = &sc->sc_ic;
281 	struct ath_hal *ah = NULL;
282 	HAL_STATUS status;
283 	int error = 0, i;
284 
285 	DPRINTF(sc, ATH_DEBUG_ANY, "%s: devid 0x%x\n", __func__, devid);
286 
287 	ifp = sc->sc_ifp = if_alloc(IFT_ETHER);
288 	if (ifp == NULL) {
289 		device_printf(sc->sc_dev, "can not if_alloc()\n");
290 		error = ENOSPC;
291 		goto bad;
292 	}
293 
294 	/* set these up early for if_printf use */
295 	if_initname(ifp, device_get_name(sc->sc_dev),
296 		device_get_unit(sc->sc_dev));
297 
298 	ah = ath_hal_attach(devid, sc, sc->sc_st, sc->sc_sh, &status);
299 	if (ah == NULL) {
300 		if_printf(ifp, "unable to attach hardware; HAL status %u\n",
301 			status);
302 		error = ENXIO;
303 		goto bad;
304 	}
305 	if (ah->ah_abi != HAL_ABI_VERSION) {
306 		if_printf(ifp, "HAL ABI mismatch detected "
307 			"(HAL:0x%x != driver:0x%x)\n",
308 			ah->ah_abi, HAL_ABI_VERSION);
309 		error = ENXIO;
310 		goto bad;
311 	}
312 	sc->sc_ah = ah;
313 	sc->sc_invalid = 0;	/* ready to go, enable interrupt handling */
314 
315 	/*
316 	 * Check if the MAC has multi-rate retry support.
317 	 * We do this by trying to setup a fake extended
318 	 * descriptor.  MAC's that don't have support will
319 	 * return false w/o doing anything.  MAC's that do
320 	 * support it will return true w/o doing anything.
321 	 */
322 	sc->sc_mrretry = ath_hal_setupxtxdesc(ah, NULL, 0,0, 0,0, 0,0);
323 
324 	/*
325 	 * Check if the device has hardware counters for PHY
326 	 * errors.  If so we need to enable the MIB interrupt
327 	 * so we can act on stat triggers.
328 	 */
329 	if (ath_hal_hwphycounters(ah))
330 		sc->sc_needmib = 1;
331 
332 	/*
333 	 * Get the hardware key cache size.
334 	 */
335 	sc->sc_keymax = ath_hal_keycachesize(ah);
336 	if (sc->sc_keymax > ATH_KEYMAX) {
337 		if_printf(ifp, "Warning, using only %u of %u key cache slots\n",
338 			ATH_KEYMAX, sc->sc_keymax);
339 		sc->sc_keymax = ATH_KEYMAX;
340 	}
341 	/*
342 	 * Reset the key cache since some parts do not
343 	 * reset the contents on initial power up.
344 	 */
345 	for (i = 0; i < sc->sc_keymax; i++)
346 		ath_hal_keyreset(ah, i);
347 
348 	/*
349 	 * Collect the channel list using the default country
350 	 * code and including outdoor channels.  The 802.11 layer
351 	 * is resposible for filtering this list based on settings
352 	 * like the phy mode.
353 	 */
354 	error = ath_getchannels(sc, ath_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 | BUS_DMA_COHERENT,
2512 				 &dd->dd_dmamap);
2513 	if (error != 0) {
2514 		if_printf(ifp, "unable to alloc memory for %u %s descriptors, "
2515 			"error %u\n", nbuf * ndesc, dd->dd_name, error);
2516 		goto fail1;
2517 	}
2518 
2519 	error = bus_dmamap_load(dd->dd_dmat, dd->dd_dmamap,
2520 				dd->dd_desc, dd->dd_desc_len,
2521 				ath_load_cb, &dd->dd_desc_paddr,
2522 				BUS_DMA_NOWAIT);
2523 	if (error != 0) {
2524 		if_printf(ifp, "unable to map %s descriptors, error %u\n",
2525 			dd->dd_name, error);
2526 		goto fail2;
2527 	}
2528 
2529 	ds = dd->dd_desc;
2530 	DPRINTF(sc, ATH_DEBUG_RESET, "%s: %s DMA map: %p (%lu) -> %p (%lu)\n",
2531 	    __func__, dd->dd_name, ds, (u_long) dd->dd_desc_len,
2532 	    (caddr_t) dd->dd_desc_paddr, /*XXX*/ (u_long) dd->dd_desc_len);
2533 
2534 	/* allocate rx buffers */
2535 	bsize = sizeof(struct ath_buf) * nbuf;
2536 	bf = malloc(bsize, M_ATHDEV, M_NOWAIT | M_ZERO);
2537 	if (bf == NULL) {
2538 		if_printf(ifp, "malloc of %s buffers failed, size %u\n",
2539 			dd->dd_name, bsize);
2540 		goto fail3;
2541 	}
2542 	dd->dd_bufptr = bf;
2543 
2544 	STAILQ_INIT(head);
2545 	for (i = 0; i < nbuf; i++, bf++, ds += ndesc) {
2546 		bf->bf_desc = ds;
2547 		bf->bf_daddr = DS2PHYS(dd, ds);
2548 		error = bus_dmamap_create(sc->sc_dmat, BUS_DMA_NOWAIT,
2549 				&bf->bf_dmamap);
2550 		if (error != 0) {
2551 			if_printf(ifp, "unable to create dmamap for %s "
2552 				"buffer %u, error %u\n", dd->dd_name, i, error);
2553 			ath_descdma_cleanup(sc, dd, head);
2554 			return error;
2555 		}
2556 		STAILQ_INSERT_TAIL(head, bf, bf_list);
2557 	}
2558 	return 0;
2559 fail3:
2560 	bus_dmamap_unload(dd->dd_dmat, dd->dd_dmamap);
2561 fail2:
2562 	bus_dmamem_free(dd->dd_dmat, dd->dd_desc, dd->dd_dmamap);
2563 fail1:
2564 	bus_dmamap_destroy(dd->dd_dmat, dd->dd_dmamap);
2565 fail0:
2566 	bus_dma_tag_destroy(dd->dd_dmat);
2567 	memset(dd, 0, sizeof(*dd));
2568 	return error;
2569 #undef DS2PHYS
2570 }
2571 
2572 static void
2573 ath_descdma_cleanup(struct ath_softc *sc,
2574 	struct ath_descdma *dd, ath_bufhead *head)
2575 {
2576 	struct ath_buf *bf;
2577 	struct ieee80211_node *ni;
2578 
2579 	bus_dmamap_unload(dd->dd_dmat, dd->dd_dmamap);
2580 	bus_dmamem_free(dd->dd_dmat, dd->dd_desc, dd->dd_dmamap);
2581 	bus_dmamap_destroy(dd->dd_dmat, dd->dd_dmamap);
2582 	bus_dma_tag_destroy(dd->dd_dmat);
2583 
2584 	STAILQ_FOREACH(bf, head, bf_list) {
2585 		if (bf->bf_m) {
2586 			m_freem(bf->bf_m);
2587 			bf->bf_m = NULL;
2588 		}
2589 		if (bf->bf_dmamap != NULL) {
2590 			bus_dmamap_destroy(sc->sc_dmat, bf->bf_dmamap);
2591 			bf->bf_dmamap = NULL;
2592 		}
2593 		ni = bf->bf_node;
2594 		bf->bf_node = NULL;
2595 		if (ni != NULL) {
2596 			/*
2597 			 * Reclaim node reference.
2598 			 */
2599 			ieee80211_free_node(ni);
2600 		}
2601 	}
2602 
2603 	STAILQ_INIT(head);
2604 	free(dd->dd_bufptr, M_ATHDEV);
2605 	memset(dd, 0, sizeof(*dd));
2606 }
2607 
2608 static int
2609 ath_desc_alloc(struct ath_softc *sc)
2610 {
2611 	int error;
2612 
2613 	error = ath_descdma_setup(sc, &sc->sc_rxdma, &sc->sc_rxbuf,
2614 			"rx", ath_rxbuf, 1);
2615 	if (error != 0)
2616 		return error;
2617 
2618 	error = ath_descdma_setup(sc, &sc->sc_txdma, &sc->sc_txbuf,
2619 			"tx", ath_txbuf, ATH_TXDESC);
2620 	if (error != 0) {
2621 		ath_descdma_cleanup(sc, &sc->sc_rxdma, &sc->sc_rxbuf);
2622 		return error;
2623 	}
2624 
2625 	error = ath_descdma_setup(sc, &sc->sc_bdma, &sc->sc_bbuf,
2626 			"beacon", 1, 1);
2627 	if (error != 0) {
2628 		ath_descdma_cleanup(sc, &sc->sc_txdma, &sc->sc_txbuf);
2629 		ath_descdma_cleanup(sc, &sc->sc_rxdma, &sc->sc_rxbuf);
2630 		return error;
2631 	}
2632 	return 0;
2633 }
2634 
2635 static void
2636 ath_desc_free(struct ath_softc *sc)
2637 {
2638 
2639 	if (sc->sc_bdma.dd_desc_len != 0)
2640 		ath_descdma_cleanup(sc, &sc->sc_bdma, &sc->sc_bbuf);
2641 	if (sc->sc_txdma.dd_desc_len != 0)
2642 		ath_descdma_cleanup(sc, &sc->sc_txdma, &sc->sc_txbuf);
2643 	if (sc->sc_rxdma.dd_desc_len != 0)
2644 		ath_descdma_cleanup(sc, &sc->sc_rxdma, &sc->sc_rxbuf);
2645 }
2646 
2647 static struct ieee80211_node *
2648 ath_node_alloc(struct ieee80211_node_table *nt)
2649 {
2650 	struct ieee80211com *ic = nt->nt_ic;
2651 	struct ath_softc *sc = ic->ic_ifp->if_softc;
2652 	const size_t space = sizeof(struct ath_node) + sc->sc_rc->arc_space;
2653 	struct ath_node *an;
2654 
2655 	an = malloc(space, M_80211_NODE, M_NOWAIT|M_ZERO);
2656 	if (an == NULL) {
2657 		/* XXX stat+msg */
2658 		return NULL;
2659 	}
2660 	an->an_avgrssi = ATH_RSSI_DUMMY_MARKER;
2661 	ath_rate_node_init(sc, an);
2662 
2663 	DPRINTF(sc, ATH_DEBUG_NODE, "%s: an %p\n", __func__, an);
2664 	return &an->an_node;
2665 }
2666 
2667 static void
2668 ath_node_free(struct ieee80211_node *ni)
2669 {
2670 	struct ieee80211com *ic = ni->ni_ic;
2671         struct ath_softc *sc = ic->ic_ifp->if_softc;
2672 
2673 	DPRINTF(sc, ATH_DEBUG_NODE, "%s: ni %p\n", __func__, ni);
2674 
2675 	ath_rate_node_cleanup(sc, ATH_NODE(ni));
2676 	sc->sc_node_free(ni);
2677 }
2678 
2679 static u_int8_t
2680 ath_node_getrssi(const struct ieee80211_node *ni)
2681 {
2682 #define	HAL_EP_RND(x, mul) \
2683 	((((x)%(mul)) >= ((mul)/2)) ? ((x) + ((mul) - 1)) / (mul) : (x)/(mul))
2684 	u_int32_t avgrssi = ATH_NODE_CONST(ni)->an_avgrssi;
2685 	int32_t rssi;
2686 
2687 	/*
2688 	 * When only one frame is received there will be no state in
2689 	 * avgrssi so fallback on the value recorded by the 802.11 layer.
2690 	 */
2691 	if (avgrssi != ATH_RSSI_DUMMY_MARKER)
2692 		rssi = HAL_EP_RND(avgrssi, HAL_RSSI_EP_MULTIPLIER);
2693 	else
2694 		rssi = ni->ni_rssi;
2695 	return rssi < 0 ? 0 : rssi > 127 ? 127 : rssi;
2696 #undef HAL_EP_RND
2697 }
2698 
2699 static int
2700 ath_rxbuf_init(struct ath_softc *sc, struct ath_buf *bf)
2701 {
2702 	struct ath_hal *ah = sc->sc_ah;
2703 	int error;
2704 	struct mbuf *m;
2705 	struct ath_desc *ds;
2706 
2707 	m = bf->bf_m;
2708 	if (m == NULL) {
2709 		/*
2710 		 * NB: by assigning a page to the rx dma buffer we
2711 		 * implicitly satisfy the Atheros requirement that
2712 		 * this buffer be cache-line-aligned and sized to be
2713 		 * multiple of the cache line size.  Not doing this
2714 		 * causes weird stuff to happen (for the 5210 at least).
2715 		 */
2716 		m = m_getcl(M_DONTWAIT, MT_DATA, M_PKTHDR);
2717 		if (m == NULL) {
2718 			DPRINTF(sc, ATH_DEBUG_ANY,
2719 				"%s: no mbuf/cluster\n", __func__);
2720 			sc->sc_stats.ast_rx_nombuf++;
2721 			return ENOMEM;
2722 		}
2723 		m->m_pkthdr.len = m->m_len = m->m_ext.ext_size;
2724 
2725 		error = bus_dmamap_load_mbuf_sg(sc->sc_dmat,
2726 					     bf->bf_dmamap, m,
2727 					     bf->bf_segs, &bf->bf_nseg,
2728 					     BUS_DMA_NOWAIT);
2729 		if (error != 0) {
2730 			DPRINTF(sc, ATH_DEBUG_ANY,
2731 			    "%s: bus_dmamap_load_mbuf_sg failed; error %d\n",
2732 			    __func__, error);
2733 			sc->sc_stats.ast_rx_busdma++;
2734 			m_freem(m);
2735 			return error;
2736 		}
2737 		KASSERT(bf->bf_nseg == 1,
2738 			("multi-segment packet; nseg %u", bf->bf_nseg));
2739 		bf->bf_m = m;
2740 	}
2741 	bus_dmamap_sync(sc->sc_dmat, bf->bf_dmamap, BUS_DMASYNC_PREREAD);
2742 
2743 	/*
2744 	 * Setup descriptors.  For receive we always terminate
2745 	 * the descriptor list with a self-linked entry so we'll
2746 	 * not get overrun under high load (as can happen with a
2747 	 * 5212 when ANI processing enables PHY error frames).
2748 	 *
2749 	 * To insure the last descriptor is self-linked we create
2750 	 * each descriptor as self-linked and add it to the end.  As
2751 	 * each additional descriptor is added the previous self-linked
2752 	 * entry is ``fixed'' naturally.  This should be safe even
2753 	 * if DMA is happening.  When processing RX interrupts we
2754 	 * never remove/process the last, self-linked, entry on the
2755 	 * descriptor list.  This insures the hardware always has
2756 	 * someplace to write a new frame.
2757 	 */
2758 	ds = bf->bf_desc;
2759 	ds->ds_link = bf->bf_daddr;	/* link to self */
2760 	ds->ds_data = bf->bf_segs[0].ds_addr;
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_rx_status *rs, 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(ath_extend_tsf(rs->rs_tstamp, tsf));
2874 	rix = rs->rs_rate;
2875 	sc->sc_rx_th.wr_flags = sc->sc_hwmap[rix].rxflags;
2876 	if (rs->rs_status & HAL_RXERR_CRC)
2877 		sc->sc_rx_th.wr_flags |= IEEE80211_RADIOTAP_F_BADFCS;
2878 	/* XXX propagate other error flags from descriptor */
2879 	sc->sc_rx_th.wr_rate = sc->sc_hwmap[rix].ieeerate;
2880 	sc->sc_rx_th.wr_antsignal = rs->rs_rssi + nf;
2881 	sc->sc_rx_th.wr_antnoise = nf;
2882 	sc->sc_rx_th.wr_antenna = rs->rs_antenna;
2883 
2884 	bpf_mtap2(sc->sc_drvbpf, &sc->sc_rx_th, sc->sc_rx_th_len, m);
2885 
2886 	return 1;
2887 }
2888 
2889 static void
2890 ath_rx_proc(void *arg, int npending)
2891 {
2892 #define	PA2DESC(_sc, _pa) \
2893 	((struct ath_desc *)((caddr_t)(_sc)->sc_rxdma.dd_desc + \
2894 		((_pa) - (_sc)->sc_rxdma.dd_desc_paddr)))
2895 	struct ath_softc *sc = arg;
2896 	struct ath_buf *bf;
2897 	struct ieee80211com *ic = &sc->sc_ic;
2898 	struct ifnet *ifp = sc->sc_ifp;
2899 	struct ath_hal *ah = sc->sc_ah;
2900 	struct ath_desc *ds;
2901 	struct ath_rx_status *rs;
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 		rs = &bf->bf_status.ds_rxstat;
2952 		status = ath_hal_rxprocdesc(ah, ds,
2953 				bf->bf_daddr, PA2DESC(sc, ds->ds_link), rs);
2954 #ifdef ATH_DEBUG
2955 		if (sc->sc_debug & ATH_DEBUG_RECV_DESC)
2956 			ath_printrxbuf(bf, 0, status == HAL_OK);
2957 #endif
2958 		if (status == HAL_EINPROGRESS)
2959 			break;
2960 		STAILQ_REMOVE_HEAD(&sc->sc_rxbuf, bf_list);
2961 		if (rs->rs_more) {
2962 			/*
2963 			 * Frame spans multiple descriptors; this
2964 			 * cannot happen yet as we don't support
2965 			 * jumbograms.  If not in monitor mode,
2966 			 * discard the frame.
2967 			 */
2968 			if (ic->ic_opmode != IEEE80211_M_MONITOR) {
2969 				sc->sc_stats.ast_rx_toobig++;
2970 				goto rx_next;
2971 			}
2972 			/* fall thru for monitor mode handling... */
2973 		} else if (rs->rs_status != 0) {
2974 			if (rs->rs_status & HAL_RXERR_CRC)
2975 				sc->sc_stats.ast_rx_crcerr++;
2976 			if (rs->rs_status & HAL_RXERR_FIFO)
2977 				sc->sc_stats.ast_rx_fifoerr++;
2978 			if (rs->rs_status & HAL_RXERR_PHY) {
2979 				sc->sc_stats.ast_rx_phyerr++;
2980 				phyerr = rs->rs_phyerr & 0x1f;
2981 				sc->sc_stats.ast_rx_phy[phyerr]++;
2982 				goto rx_next;
2983 			}
2984 			if (rs->rs_status & HAL_RXERR_DECRYPT) {
2985 				/*
2986 				 * Decrypt error.  If the error occurred
2987 				 * because there was no hardware key, then
2988 				 * let the frame through so the upper layers
2989 				 * can process it.  This is necessary for 5210
2990 				 * parts which have no way to setup a ``clear''
2991 				 * key cache entry.
2992 				 *
2993 				 * XXX do key cache faulting
2994 				 */
2995 				if (rs->rs_keyix == HAL_RXKEYIX_INVALID)
2996 					goto rx_accept;
2997 				sc->sc_stats.ast_rx_badcrypt++;
2998 			}
2999 			if (rs->rs_status & HAL_RXERR_MIC) {
3000 				sc->sc_stats.ast_rx_badmic++;
3001 				/*
3002 				 * Do minimal work required to hand off
3003 				 * the 802.11 header for notifcation.
3004 				 */
3005 				/* XXX frag's and qos frames */
3006 				len = rs->rs_datalen;
3007 				if (len >= sizeof (struct ieee80211_frame)) {
3008 					bus_dmamap_sync(sc->sc_dmat,
3009 					    bf->bf_dmamap,
3010 					    BUS_DMASYNC_POSTREAD);
3011 					ieee80211_notify_michael_failure(ic,
3012 					    mtod(m, struct ieee80211_frame *),
3013 					    sc->sc_splitmic ?
3014 					        rs->rs_keyix-32 : rs->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 			    (rs->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 = rs->rs_datalen;
3031 				m->m_pkthdr.len = m->m_len = len;
3032 				(void) ath_rx_tap(sc, m, rs, 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 = rs->rs_datalen;
3052 		m->m_pkthdr.len = m->m_len = len;
3053 
3054 		sc->sc_stats.ast_ant_rx[rs->rs_antenna]++;
3055 
3056 		if (bpf_peers_present(sc->sc_drvbpf) &&
3057 		    !ath_rx_tap(sc, m, rs, 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[rs->rs_rate].ieeerate,
3077 				   rs->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 			rs->rs_keyix == HAL_RXKEYIX_INVALID ?
3090 				IEEE80211_KEYIX_NONE : rs->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, rs->rs_rssi);
3096 		ATH_RSSI_LPF(sc->sc_halstats.ns_avgrssi, rs->rs_rssi);
3097 		/*
3098 		 * Send frame up for processing.
3099 		 */
3100 		type = ieee80211_input(ic, m, ni, rs->rs_rssi, rs->rs_tstamp);
3101 		ieee80211_free_node(ni);
3102 		if (sc->sc_diversity) {
3103 			/*
3104 			 * When using fast diversity, change the default rx
3105 			 * antenna if diversity chooses the other antenna 3
3106 			 * times in a row.
3107 			 */
3108 			if (sc->sc_defant != rs->rs_antenna) {
3109 				if (++sc->sc_rxotherant >= 3)
3110 					ath_setdefantenna(sc, rs->rs_antenna);
3111 			} else
3112 				sc->sc_rxotherant = 0;
3113 		}
3114 		if (sc->sc_softled) {
3115 			/*
3116 			 * Blink for any data frame.  Otherwise do a
3117 			 * heartbeat-style blink when idle.  The latter
3118 			 * is mainly for station mode where we depend on
3119 			 * periodic beacon frames to trigger the poll event.
3120 			 */
3121 			if (type == IEEE80211_FC0_TYPE_DATA) {
3122 				sc->sc_rxrate = rs->rs_rate;
3123 				ath_led_event(sc, ATH_LED_RX);
3124 			} else if (ticks - sc->sc_ledevent >= sc->sc_ledidle)
3125 				ath_led_event(sc, ATH_LED_POLL);
3126 		}
3127 		/*
3128 		 * Arrange to update the last rx timestamp only for
3129 		 * frames from our ap when operating in station mode.
3130 		 * This assumes the rx key is always setup when associated.
3131 		 */
3132 		if (ic->ic_opmode == IEEE80211_M_STA &&
3133 		    rs->rs_keyix != HAL_RXKEYIX_INVALID)
3134 			ngood++;
3135 rx_next:
3136 		STAILQ_INSERT_TAIL(&sc->sc_rxbuf, bf, bf_list);
3137 	} while (ath_rxbuf_init(sc, bf) == 0);
3138 
3139 	/* rx signal state monitoring */
3140 	ath_hal_rxmonitor(ah, &sc->sc_halstats, &sc->sc_curchan);
3141 	if (ngood)
3142 		sc->sc_lastrx = tsf;
3143 
3144 	NET_UNLOCK_GIANT();		/* XXX */
3145 #undef PA2DESC
3146 }
3147 
3148 static void
3149 ath_txq_init(struct ath_softc *sc, struct ath_txq *txq, int qnum)
3150 {
3151 	txq->axq_qnum = qnum;
3152 	txq->axq_depth = 0;
3153 	txq->axq_intrcnt = 0;
3154 	txq->axq_link = NULL;
3155 	STAILQ_INIT(&txq->axq_q);
3156 	ATH_TXQ_LOCK_INIT(sc, txq);
3157 }
3158 
3159 /*
3160  * Setup a h/w transmit queue.
3161  */
3162 static struct ath_txq *
3163 ath_txq_setup(struct ath_softc *sc, int qtype, int subtype)
3164 {
3165 #define	N(a)	(sizeof(a)/sizeof(a[0]))
3166 	struct ath_hal *ah = sc->sc_ah;
3167 	HAL_TXQ_INFO qi;
3168 	int qnum;
3169 
3170 	memset(&qi, 0, sizeof(qi));
3171 	qi.tqi_subtype = subtype;
3172 	qi.tqi_aifs = HAL_TXQ_USEDEFAULT;
3173 	qi.tqi_cwmin = HAL_TXQ_USEDEFAULT;
3174 	qi.tqi_cwmax = HAL_TXQ_USEDEFAULT;
3175 	/*
3176 	 * Enable interrupts only for EOL and DESC conditions.
3177 	 * We mark tx descriptors to receive a DESC interrupt
3178 	 * when a tx queue gets deep; otherwise waiting for the
3179 	 * EOL to reap descriptors.  Note that this is done to
3180 	 * reduce interrupt load and this only defers reaping
3181 	 * descriptors, never transmitting frames.  Aside from
3182 	 * reducing interrupts this also permits more concurrency.
3183 	 * The only potential downside is if the tx queue backs
3184 	 * up in which case the top half of the kernel may backup
3185 	 * due to a lack of tx descriptors.
3186 	 */
3187 	qi.tqi_qflags = HAL_TXQ_TXEOLINT_ENABLE | HAL_TXQ_TXDESCINT_ENABLE;
3188 	qnum = ath_hal_setuptxqueue(ah, qtype, &qi);
3189 	if (qnum == -1) {
3190 		/*
3191 		 * NB: don't print a message, this happens
3192 		 * normally on parts with too few tx queues
3193 		 */
3194 		return NULL;
3195 	}
3196 	if (qnum >= N(sc->sc_txq)) {
3197 		device_printf(sc->sc_dev,
3198 			"hal qnum %u out of range, max %zu!\n",
3199 			qnum, N(sc->sc_txq));
3200 		ath_hal_releasetxqueue(ah, qnum);
3201 		return NULL;
3202 	}
3203 	if (!ATH_TXQ_SETUP(sc, qnum)) {
3204 		ath_txq_init(sc, &sc->sc_txq[qnum], qnum);
3205 		sc->sc_txqsetup |= 1<<qnum;
3206 	}
3207 	return &sc->sc_txq[qnum];
3208 #undef N
3209 }
3210 
3211 /*
3212  * Setup a hardware data transmit queue for the specified
3213  * access control.  The hal may not support all requested
3214  * queues in which case it will return a reference to a
3215  * previously setup queue.  We record the mapping from ac's
3216  * to h/w queues for use by ath_tx_start and also track
3217  * the set of h/w queues being used to optimize work in the
3218  * transmit interrupt handler and related routines.
3219  */
3220 static int
3221 ath_tx_setup(struct ath_softc *sc, int ac, int haltype)
3222 {
3223 #define	N(a)	(sizeof(a)/sizeof(a[0]))
3224 	struct ath_txq *txq;
3225 
3226 	if (ac >= N(sc->sc_ac2q)) {
3227 		device_printf(sc->sc_dev, "AC %u out of range, max %zu!\n",
3228 			ac, N(sc->sc_ac2q));
3229 		return 0;
3230 	}
3231 	txq = ath_txq_setup(sc, HAL_TX_QUEUE_DATA, haltype);
3232 	if (txq != NULL) {
3233 		sc->sc_ac2q[ac] = txq;
3234 		return 1;
3235 	} else
3236 		return 0;
3237 #undef N
3238 }
3239 
3240 /*
3241  * Update WME parameters for a transmit queue.
3242  */
3243 static int
3244 ath_txq_update(struct ath_softc *sc, int ac)
3245 {
3246 #define	ATH_EXPONENT_TO_VALUE(v)	((1<<v)-1)
3247 #define	ATH_TXOP_TO_US(v)		(v<<5)
3248 	struct ieee80211com *ic = &sc->sc_ic;
3249 	struct ath_txq *txq = sc->sc_ac2q[ac];
3250 	struct wmeParams *wmep = &ic->ic_wme.wme_chanParams.cap_wmeParams[ac];
3251 	struct ath_hal *ah = sc->sc_ah;
3252 	HAL_TXQ_INFO qi;
3253 
3254 	ath_hal_gettxqueueprops(ah, txq->axq_qnum, &qi);
3255 	qi.tqi_aifs = wmep->wmep_aifsn;
3256 	qi.tqi_cwmin = ATH_EXPONENT_TO_VALUE(wmep->wmep_logcwmin);
3257 	qi.tqi_cwmax = ATH_EXPONENT_TO_VALUE(wmep->wmep_logcwmax);
3258 	qi.tqi_burstTime = ATH_TXOP_TO_US(wmep->wmep_txopLimit);
3259 
3260 	if (!ath_hal_settxqueueprops(ah, txq->axq_qnum, &qi)) {
3261 		device_printf(sc->sc_dev, "unable to update hardware queue "
3262 			"parameters for %s traffic!\n",
3263 			ieee80211_wme_acnames[ac]);
3264 		return 0;
3265 	} else {
3266 		ath_hal_resettxqueue(ah, txq->axq_qnum); /* push to h/w */
3267 		return 1;
3268 	}
3269 #undef ATH_TXOP_TO_US
3270 #undef ATH_EXPONENT_TO_VALUE
3271 }
3272 
3273 /*
3274  * Callback from the 802.11 layer to update WME parameters.
3275  */
3276 static int
3277 ath_wme_update(struct ieee80211com *ic)
3278 {
3279 	struct ath_softc *sc = ic->ic_ifp->if_softc;
3280 
3281 	return !ath_txq_update(sc, WME_AC_BE) ||
3282 	    !ath_txq_update(sc, WME_AC_BK) ||
3283 	    !ath_txq_update(sc, WME_AC_VI) ||
3284 	    !ath_txq_update(sc, WME_AC_VO) ? EIO : 0;
3285 }
3286 
3287 /*
3288  * Reclaim resources for a setup queue.
3289  */
3290 static void
3291 ath_tx_cleanupq(struct ath_softc *sc, struct ath_txq *txq)
3292 {
3293 
3294 	ath_hal_releasetxqueue(sc->sc_ah, txq->axq_qnum);
3295 	ATH_TXQ_LOCK_DESTROY(txq);
3296 	sc->sc_txqsetup &= ~(1<<txq->axq_qnum);
3297 }
3298 
3299 /*
3300  * Reclaim all tx queue resources.
3301  */
3302 static void
3303 ath_tx_cleanup(struct ath_softc *sc)
3304 {
3305 	int i;
3306 
3307 	ATH_TXBUF_LOCK_DESTROY(sc);
3308 	for (i = 0; i < HAL_NUM_TX_QUEUES; i++)
3309 		if (ATH_TXQ_SETUP(sc, i))
3310 			ath_tx_cleanupq(sc, &sc->sc_txq[i]);
3311 	ATH_TXQ_LOCK_DESTROY(&sc->sc_mcastq);
3312 }
3313 
3314 /*
3315  * Defragment an mbuf chain, returning at most maxfrags separate
3316  * mbufs+clusters.  If this is not possible NULL is returned and
3317  * the original mbuf chain is left in it's present (potentially
3318  * modified) state.  We use two techniques: collapsing consecutive
3319  * mbufs and replacing consecutive mbufs by a cluster.
3320  */
3321 static struct mbuf *
3322 ath_defrag(struct mbuf *m0, int how, int maxfrags)
3323 {
3324 	struct mbuf *m, *n, *n2, **prev;
3325 	u_int curfrags;
3326 
3327 	/*
3328 	 * Calculate the current number of frags.
3329 	 */
3330 	curfrags = 0;
3331 	for (m = m0; m != NULL; m = m->m_next)
3332 		curfrags++;
3333 	/*
3334 	 * First, try to collapse mbufs.  Note that we always collapse
3335 	 * towards the front so we don't need to deal with moving the
3336 	 * pkthdr.  This may be suboptimal if the first mbuf has much
3337 	 * less data than the following.
3338 	 */
3339 	m = m0;
3340 again:
3341 	for (;;) {
3342 		n = m->m_next;
3343 		if (n == NULL)
3344 			break;
3345 		if ((m->m_flags & M_RDONLY) == 0 &&
3346 		    n->m_len < M_TRAILINGSPACE(m)) {
3347 			bcopy(mtod(n, void *), mtod(m, char *) + m->m_len,
3348 				n->m_len);
3349 			m->m_len += n->m_len;
3350 			m->m_next = n->m_next;
3351 			m_free(n);
3352 			if (--curfrags <= maxfrags)
3353 				return m0;
3354 		} else
3355 			m = n;
3356 	}
3357 	KASSERT(maxfrags > 1,
3358 		("maxfrags %u, but normal collapse failed", maxfrags));
3359 	/*
3360 	 * Collapse consecutive mbufs to a cluster.
3361 	 */
3362 	prev = &m0->m_next;		/* NB: not the first mbuf */
3363 	while ((n = *prev) != NULL) {
3364 		if ((n2 = n->m_next) != NULL &&
3365 		    n->m_len + n2->m_len < MCLBYTES) {
3366 			m = m_getcl(how, MT_DATA, 0);
3367 			if (m == NULL)
3368 				goto bad;
3369 			bcopy(mtod(n, void *), mtod(m, void *), n->m_len);
3370 			bcopy(mtod(n2, void *), mtod(m, char *) + n->m_len,
3371 				n2->m_len);
3372 			m->m_len = n->m_len + n2->m_len;
3373 			m->m_next = n2->m_next;
3374 			*prev = m;
3375 			m_free(n);
3376 			m_free(n2);
3377 			if (--curfrags <= maxfrags)	/* +1 cl -2 mbufs */
3378 				return m0;
3379 			/*
3380 			 * Still not there, try the normal collapse
3381 			 * again before we allocate another cluster.
3382 			 */
3383 			goto again;
3384 		}
3385 		prev = &n->m_next;
3386 	}
3387 	/*
3388 	 * No place where we can collapse to a cluster; punt.
3389 	 * This can occur if, for example, you request 2 frags
3390 	 * but the packet requires that both be clusters (we
3391 	 * never reallocate the first mbuf to avoid moving the
3392 	 * packet header).
3393 	 */
3394 bad:
3395 	return NULL;
3396 }
3397 
3398 /*
3399  * Return h/w rate index for an IEEE rate (w/o basic rate bit).
3400  */
3401 static int
3402 ath_tx_findrix(const HAL_RATE_TABLE *rt, int rate)
3403 {
3404 	int i;
3405 
3406 	for (i = 0; i < rt->rateCount; i++)
3407 		if ((rt->info[i].dot11Rate & IEEE80211_RATE_VAL) == rate)
3408 			return i;
3409 	return 0;		/* NB: lowest rate */
3410 }
3411 
3412 static int
3413 ath_tx_dmasetup(struct ath_softc *sc, struct ath_buf *bf, struct mbuf *m0)
3414 {
3415 	struct mbuf *m;
3416 	int error;
3417 
3418 	/*
3419 	 * Load the DMA map so any coalescing is done.  This
3420 	 * also calculates the number of descriptors we need.
3421 	 */
3422 	error = bus_dmamap_load_mbuf_sg(sc->sc_dmat, bf->bf_dmamap, m0,
3423 				     bf->bf_segs, &bf->bf_nseg,
3424 				     BUS_DMA_NOWAIT);
3425 	if (error == EFBIG) {
3426 		/* XXX packet requires too many descriptors */
3427 		bf->bf_nseg = ATH_TXDESC+1;
3428 	} else if (error != 0) {
3429 		sc->sc_stats.ast_tx_busdma++;
3430 		m_freem(m0);
3431 		return error;
3432 	}
3433 	/*
3434 	 * Discard null packets and check for packets that
3435 	 * require too many TX descriptors.  We try to convert
3436 	 * the latter to a cluster.
3437 	 */
3438 	if (bf->bf_nseg > ATH_TXDESC) {		/* too many desc's, linearize */
3439 		sc->sc_stats.ast_tx_linear++;
3440 		m = ath_defrag(m0, M_DONTWAIT, ATH_TXDESC);
3441 		if (m == NULL) {
3442 			m_freem(m0);
3443 			sc->sc_stats.ast_tx_nombuf++;
3444 			return ENOMEM;
3445 		}
3446 		m0 = m;
3447 		error = bus_dmamap_load_mbuf_sg(sc->sc_dmat, bf->bf_dmamap, m0,
3448 					     bf->bf_segs, &bf->bf_nseg,
3449 					     BUS_DMA_NOWAIT);
3450 		if (error != 0) {
3451 			sc->sc_stats.ast_tx_busdma++;
3452 			m_freem(m0);
3453 			return error;
3454 		}
3455 		KASSERT(bf->bf_nseg <= ATH_TXDESC,
3456 		    ("too many segments after defrag; nseg %u", bf->bf_nseg));
3457 	} else if (bf->bf_nseg == 0) {		/* null packet, discard */
3458 		sc->sc_stats.ast_tx_nodata++;
3459 		m_freem(m0);
3460 		return EIO;
3461 	}
3462 	DPRINTF(sc, ATH_DEBUG_XMIT, "%s: m %p len %u\n",
3463 		__func__, m0, m0->m_pkthdr.len);
3464 	bus_dmamap_sync(sc->sc_dmat, bf->bf_dmamap, BUS_DMASYNC_PREWRITE);
3465 	bf->bf_m = m0;
3466 
3467 	return 0;
3468 }
3469 
3470 static void
3471 ath_tx_handoff(struct ath_softc *sc, struct ath_txq *txq, struct ath_buf *bf)
3472 {
3473 	struct ath_hal *ah = sc->sc_ah;
3474 	struct ath_desc *ds, *ds0;
3475 	int i;
3476 
3477 	/*
3478 	 * Fillin the remainder of the descriptor info.
3479 	 */
3480 	ds0 = ds = bf->bf_desc;
3481 	for (i = 0; i < bf->bf_nseg; i++, ds++) {
3482 		ds->ds_data = bf->bf_segs[i].ds_addr;
3483 		if (i == bf->bf_nseg - 1)
3484 			ds->ds_link = 0;
3485 		else
3486 			ds->ds_link = bf->bf_daddr + sizeof(*ds) * (i + 1);
3487 		ath_hal_filltxdesc(ah, ds
3488 			, bf->bf_segs[i].ds_len	/* segment length */
3489 			, i == 0		/* first segment */
3490 			, i == bf->bf_nseg - 1	/* last segment */
3491 			, ds0			/* first descriptor */
3492 		);
3493 		DPRINTF(sc, ATH_DEBUG_XMIT,
3494 			"%s: %d: %08x %08x %08x %08x %08x %08x\n",
3495 			__func__, i, ds->ds_link, ds->ds_data,
3496 			ds->ds_ctl0, ds->ds_ctl1, ds->ds_hw[0], ds->ds_hw[1]);
3497 	}
3498 	/*
3499 	 * Insert the frame on the outbound list and pass it on
3500 	 * to the hardware.  Multicast frames buffered for power
3501 	 * save stations and transmit from the CAB queue are stored
3502 	 * on a s/w only queue and loaded on to the CAB queue in
3503 	 * the SWBA handler since frames only go out on DTIM and
3504 	 * to avoid possible races.
3505 	 */
3506 	ATH_TXQ_LOCK(txq);
3507 	ATH_TXQ_INSERT_TAIL(txq, bf, bf_list);
3508 	if (txq != &sc->sc_mcastq) {
3509 		if (txq->axq_link == NULL) {
3510 			ath_hal_puttxbuf(ah, txq->axq_qnum, bf->bf_daddr);
3511 			DPRINTF(sc, ATH_DEBUG_XMIT,
3512 			    "%s: TXDP[%u] = %p (%p) depth %d\n", __func__,
3513 			    txq->axq_qnum, (caddr_t)bf->bf_daddr, bf->bf_desc,
3514 			    txq->axq_depth);
3515 		} else {
3516 			*txq->axq_link = bf->bf_daddr;
3517 			DPRINTF(sc, ATH_DEBUG_XMIT,
3518 			    "%s: link[%u](%p)=%p (%p) depth %d\n", __func__,
3519 			    txq->axq_qnum, txq->axq_link,
3520 			    (caddr_t)bf->bf_daddr, bf->bf_desc, txq->axq_depth);
3521 		}
3522 		txq->axq_link = &bf->bf_desc[bf->bf_nseg - 1].ds_link;
3523 		ath_hal_txstart(ah, txq->axq_qnum);
3524 	} else {
3525 		if (txq->axq_link != NULL)
3526 			*txq->axq_link = bf->bf_daddr;
3527 		txq->axq_link = &bf->bf_desc[bf->bf_nseg - 1].ds_link;
3528 	}
3529 	ATH_TXQ_UNLOCK(txq);
3530 }
3531 
3532 static int
3533 ath_tx_start(struct ath_softc *sc, struct ieee80211_node *ni, struct ath_buf *bf,
3534     struct mbuf *m0)
3535 {
3536 	struct ieee80211com *ic = &sc->sc_ic;
3537 	struct ath_hal *ah = sc->sc_ah;
3538 	struct ifnet *ifp = sc->sc_ifp;
3539 	const struct chanAccParams *cap = &ic->ic_wme.wme_chanParams;
3540 	int error, iswep, ismcast, ismrr;
3541 	int keyix, hdrlen, pktlen, try0;
3542 	u_int8_t rix, txrate, ctsrate;
3543 	u_int8_t cix = 0xff;		/* NB: silence compiler */
3544 	struct ath_desc *ds;
3545 	struct ath_txq *txq;
3546 	struct ieee80211_frame *wh;
3547 	u_int subtype, flags, ctsduration;
3548 	HAL_PKT_TYPE atype;
3549 	const HAL_RATE_TABLE *rt;
3550 	HAL_BOOL shortPreamble;
3551 	struct ath_node *an;
3552 	u_int pri;
3553 
3554 	wh = mtod(m0, struct ieee80211_frame *);
3555 	iswep = wh->i_fc[1] & IEEE80211_FC1_WEP;
3556 	ismcast = IEEE80211_IS_MULTICAST(wh->i_addr1);
3557 	hdrlen = ieee80211_anyhdrsize(wh);
3558 	/*
3559 	 * Packet length must not include any
3560 	 * pad bytes; deduct them here.
3561 	 */
3562 	pktlen = m0->m_pkthdr.len - (hdrlen & 3);
3563 
3564 	if (iswep) {
3565 		const struct ieee80211_cipher *cip;
3566 		struct ieee80211_key *k;
3567 
3568 		/*
3569 		 * Construct the 802.11 header+trailer for an encrypted
3570 		 * frame. The only reason this can fail is because of an
3571 		 * unknown or unsupported cipher/key type.
3572 		 */
3573 		k = ieee80211_crypto_encap(ic, ni, m0);
3574 		if (k == NULL) {
3575 			/*
3576 			 * This can happen when the key is yanked after the
3577 			 * frame was queued.  Just discard the frame; the
3578 			 * 802.11 layer counts failures and provides
3579 			 * debugging/diagnostics.
3580 			 */
3581 			m_freem(m0);
3582 			return EIO;
3583 		}
3584 		/*
3585 		 * Adjust the packet + header lengths for the crypto
3586 		 * additions and calculate the h/w key index.  When
3587 		 * a s/w mic is done the frame will have had any mic
3588 		 * added to it prior to entry so m0->m_pkthdr.len above will
3589 		 * account for it. Otherwise we need to add it to the
3590 		 * packet length.
3591 		 */
3592 		cip = k->wk_cipher;
3593 		hdrlen += cip->ic_header;
3594 		pktlen += cip->ic_header + cip->ic_trailer;
3595 		if ((k->wk_flags & IEEE80211_KEY_SWMIC) == 0)
3596 			pktlen += cip->ic_miclen;
3597 		keyix = k->wk_keyix;
3598 
3599 		/* packet header may have moved, reset our local pointer */
3600 		wh = mtod(m0, struct ieee80211_frame *);
3601 	} else if (ni->ni_ucastkey.wk_cipher == &ieee80211_cipher_none) {
3602 		/*
3603 		 * Use station key cache slot, if assigned.
3604 		 */
3605 		keyix = ni->ni_ucastkey.wk_keyix;
3606 		if (keyix == IEEE80211_KEYIX_NONE)
3607 			keyix = HAL_TXKEYIX_INVALID;
3608 	} else
3609 		keyix = HAL_TXKEYIX_INVALID;
3610 
3611 	pktlen += IEEE80211_CRC_LEN;
3612 
3613 	/*
3614 	 * Load the DMA map so any coalescing is done.  This
3615 	 * also calculates the number of descriptors we need.
3616 	 */
3617 	error = ath_tx_dmasetup(sc, bf, m0);
3618 	if (error != 0)
3619 		return error;
3620 	bf->bf_node = ni;			/* NB: held reference */
3621 	m0 = bf->bf_m;				/* NB: may have changed */
3622 	wh = mtod(m0, struct ieee80211_frame *);
3623 
3624 	/* setup descriptors */
3625 	ds = bf->bf_desc;
3626 	rt = sc->sc_currates;
3627 	KASSERT(rt != NULL, ("no rate table, mode %u", sc->sc_curmode));
3628 
3629 	/*
3630 	 * NB: the 802.11 layer marks whether or not we should
3631 	 * use short preamble based on the current mode and
3632 	 * negotiated parameters.
3633 	 */
3634 	if ((ic->ic_flags & IEEE80211_F_SHPREAMBLE) &&
3635 	    (ni->ni_capinfo & IEEE80211_CAPINFO_SHORT_PREAMBLE)) {
3636 		shortPreamble = AH_TRUE;
3637 		sc->sc_stats.ast_tx_shortpre++;
3638 	} else {
3639 		shortPreamble = AH_FALSE;
3640 	}
3641 
3642 	an = ATH_NODE(ni);
3643 	flags = HAL_TXDESC_CLRDMASK;		/* XXX needed for crypto errs */
3644 	ismrr = 0;				/* default no multi-rate retry*/
3645 	/*
3646 	 * Calculate Atheros packet type from IEEE80211 packet header,
3647 	 * setup for rate calculations, and select h/w transmit queue.
3648 	 */
3649 	switch (wh->i_fc[0] & IEEE80211_FC0_TYPE_MASK) {
3650 	case IEEE80211_FC0_TYPE_MGT:
3651 		subtype = wh->i_fc[0] & IEEE80211_FC0_SUBTYPE_MASK;
3652 		if (subtype == IEEE80211_FC0_SUBTYPE_BEACON)
3653 			atype = HAL_PKT_TYPE_BEACON;
3654 		else if (subtype == IEEE80211_FC0_SUBTYPE_PROBE_RESP)
3655 			atype = HAL_PKT_TYPE_PROBE_RESP;
3656 		else if (subtype == IEEE80211_FC0_SUBTYPE_ATIM)
3657 			atype = HAL_PKT_TYPE_ATIM;
3658 		else
3659 			atype = HAL_PKT_TYPE_NORMAL;	/* XXX */
3660 		rix = sc->sc_minrateix;
3661 		txrate = rt->info[rix].rateCode;
3662 		if (shortPreamble)
3663 			txrate |= rt->info[rix].shortPreamble;
3664 		try0 = ATH_TXMGTTRY;
3665 		/* NB: force all management frames to highest queue */
3666 		if (ni->ni_flags & IEEE80211_NODE_QOS) {
3667 			/* NB: force all management frames to highest queue */
3668 			pri = WME_AC_VO;
3669 		} else
3670 			pri = WME_AC_BE;
3671 		flags |= HAL_TXDESC_INTREQ;	/* force interrupt */
3672 		break;
3673 	case IEEE80211_FC0_TYPE_CTL:
3674 		atype = HAL_PKT_TYPE_PSPOLL;	/* stop setting of duration */
3675 		rix = sc->sc_minrateix;
3676 		txrate = rt->info[rix].rateCode;
3677 		if (shortPreamble)
3678 			txrate |= rt->info[rix].shortPreamble;
3679 		try0 = ATH_TXMGTTRY;
3680 		/* NB: force all ctl frames to highest queue */
3681 		if (ni->ni_flags & IEEE80211_NODE_QOS) {
3682 			/* NB: force all ctl frames to highest queue */
3683 			pri = WME_AC_VO;
3684 		} else
3685 			pri = WME_AC_BE;
3686 		flags |= HAL_TXDESC_INTREQ;	/* force interrupt */
3687 		break;
3688 	case IEEE80211_FC0_TYPE_DATA:
3689 		atype = HAL_PKT_TYPE_NORMAL;		/* default */
3690 		/*
3691 		 * Data frames: multicast frames go out at a fixed rate,
3692 		 * otherwise consult the rate control module for the
3693 		 * rate to use.
3694 		 */
3695 		if (ismcast) {
3696 			/*
3697 			 * Check mcast rate setting in case it's changed.
3698 			 * XXX move out of fastpath
3699 			 */
3700 			if (ic->ic_mcast_rate != sc->sc_mcastrate) {
3701 				sc->sc_mcastrix =
3702 					ath_tx_findrix(rt, ic->ic_mcast_rate);
3703 				sc->sc_mcastrate = ic->ic_mcast_rate;
3704 			}
3705 			rix = sc->sc_mcastrix;
3706 			txrate = rt->info[rix].rateCode;
3707 			if (shortPreamble)
3708 				txrate |= rt->info[rix].shortPreamble;
3709 			try0 = 1;
3710 		} else {
3711 			ath_rate_findrate(sc, an, shortPreamble, pktlen,
3712 				&rix, &try0, &txrate);
3713 			sc->sc_txrate = txrate;		/* for LED blinking */
3714 			if (try0 != ATH_TXMAXTRY)
3715 				ismrr = 1;
3716 		}
3717 		pri = M_WME_GETAC(m0);
3718 		if (cap->cap_wmeParams[pri].wmep_noackPolicy)
3719 			flags |= HAL_TXDESC_NOACK;
3720 		break;
3721 	default:
3722 		if_printf(ifp, "bogus frame type 0x%x (%s)\n",
3723 			wh->i_fc[0] & IEEE80211_FC0_TYPE_MASK, __func__);
3724 		/* XXX statistic */
3725 		m_freem(m0);
3726 		return EIO;
3727 	}
3728 	txq = sc->sc_ac2q[pri];
3729 
3730 	/*
3731 	 * When servicing one or more stations in power-save mode
3732 	 * (or) if there is some mcast data waiting on the mcast
3733 	 * queue (to prevent out of order delivery) multicast
3734 	 * frames must be buffered until after the beacon.
3735 	 */
3736 	if (ismcast && (ic->ic_ps_sta || sc->sc_mcastq.axq_depth)) {
3737 		txq = &sc->sc_mcastq;
3738 		/* XXX? more bit in 802.11 frame header */
3739 	}
3740 
3741 	/*
3742 	 * Calculate miscellaneous flags.
3743 	 */
3744 	if (ismcast) {
3745 		flags |= HAL_TXDESC_NOACK;	/* no ack on broad/multicast */
3746 	} else if (pktlen > ic->ic_rtsthreshold) {
3747 		flags |= HAL_TXDESC_RTSENA;	/* RTS based on frame length */
3748 		cix = rt->info[rix].controlRate;
3749 		sc->sc_stats.ast_tx_rts++;
3750 	}
3751 	if (flags & HAL_TXDESC_NOACK)		/* NB: avoid double counting */
3752 		sc->sc_stats.ast_tx_noack++;
3753 
3754 	/*
3755 	 * If 802.11g protection is enabled, determine whether
3756 	 * to use RTS/CTS or just CTS.  Note that this is only
3757 	 * done for OFDM unicast frames.
3758 	 */
3759 	if ((ic->ic_flags & IEEE80211_F_USEPROT) &&
3760 	    rt->info[rix].phy == IEEE80211_T_OFDM &&
3761 	    (flags & HAL_TXDESC_NOACK) == 0) {
3762 		/* XXX fragments must use CCK rates w/ protection */
3763 		if (ic->ic_protmode == IEEE80211_PROT_RTSCTS)
3764 			flags |= HAL_TXDESC_RTSENA;
3765 		else if (ic->ic_protmode == IEEE80211_PROT_CTSONLY)
3766 			flags |= HAL_TXDESC_CTSENA;
3767 		cix = rt->info[sc->sc_protrix].controlRate;
3768 		sc->sc_stats.ast_tx_protect++;
3769 	}
3770 
3771 	/*
3772 	 * Calculate duration.  This logically belongs in the 802.11
3773 	 * layer but it lacks sufficient information to calculate it.
3774 	 */
3775 	if ((flags & HAL_TXDESC_NOACK) == 0 &&
3776 	    (wh->i_fc[0] & IEEE80211_FC0_TYPE_MASK) != IEEE80211_FC0_TYPE_CTL) {
3777 		u_int16_t dur;
3778 		/*
3779 		 * XXX not right with fragmentation.
3780 		 */
3781 		if (shortPreamble)
3782 			dur = rt->info[rix].spAckDuration;
3783 		else
3784 			dur = rt->info[rix].lpAckDuration;
3785 		*(u_int16_t *)wh->i_dur = htole16(dur);
3786 	}
3787 
3788 	/*
3789 	 * Calculate RTS/CTS rate and duration if needed.
3790 	 */
3791 	ctsduration = 0;
3792 	if (flags & (HAL_TXDESC_RTSENA|HAL_TXDESC_CTSENA)) {
3793 		/*
3794 		 * CTS transmit rate is derived from the transmit rate
3795 		 * by looking in the h/w rate table.  We must also factor
3796 		 * in whether or not a short preamble is to be used.
3797 		 */
3798 		/* NB: cix is set above where RTS/CTS is enabled */
3799 		KASSERT(cix != 0xff, ("cix not setup"));
3800 		ctsrate = rt->info[cix].rateCode;
3801 		/*
3802 		 * Compute the transmit duration based on the frame
3803 		 * size and the size of an ACK frame.  We call into the
3804 		 * HAL to do the computation since it depends on the
3805 		 * characteristics of the actual PHY being used.
3806 		 *
3807 		 * NB: CTS is assumed the same size as an ACK so we can
3808 		 *     use the precalculated ACK durations.
3809 		 */
3810 		if (shortPreamble) {
3811 			ctsrate |= rt->info[cix].shortPreamble;
3812 			if (flags & HAL_TXDESC_RTSENA)		/* SIFS + CTS */
3813 				ctsduration += rt->info[cix].spAckDuration;
3814 			ctsduration += ath_hal_computetxtime(ah,
3815 				rt, pktlen, rix, AH_TRUE);
3816 			if ((flags & HAL_TXDESC_NOACK) == 0)	/* SIFS + ACK */
3817 				ctsduration += rt->info[rix].spAckDuration;
3818 		} else {
3819 			if (flags & HAL_TXDESC_RTSENA)		/* SIFS + CTS */
3820 				ctsduration += rt->info[cix].lpAckDuration;
3821 			ctsduration += ath_hal_computetxtime(ah,
3822 				rt, pktlen, rix, AH_FALSE);
3823 			if ((flags & HAL_TXDESC_NOACK) == 0)	/* SIFS + ACK */
3824 				ctsduration += rt->info[rix].lpAckDuration;
3825 		}
3826 		/*
3827 		 * Must disable multi-rate retry when using RTS/CTS.
3828 		 */
3829 		ismrr = 0;
3830 		try0 = ATH_TXMGTTRY;		/* XXX */
3831 	} else
3832 		ctsrate = 0;
3833 
3834 	if (IFF_DUMPPKTS(sc, ATH_DEBUG_XMIT))
3835 		ieee80211_dump_pkt(mtod(m0, caddr_t), m0->m_len,
3836 			sc->sc_hwmap[txrate].ieeerate, -1);
3837 
3838 	if (bpf_peers_present(ic->ic_rawbpf))
3839 		bpf_mtap(ic->ic_rawbpf, m0);
3840 	if (bpf_peers_present(sc->sc_drvbpf)) {
3841 		u_int64_t tsf = ath_hal_gettsf64(ah);
3842 
3843 		sc->sc_tx_th.wt_tsf = htole64(tsf);
3844 		sc->sc_tx_th.wt_flags = sc->sc_hwmap[txrate].txflags;
3845 		if (iswep)
3846 			sc->sc_tx_th.wt_flags |= IEEE80211_RADIOTAP_F_WEP;
3847 		sc->sc_tx_th.wt_rate = sc->sc_hwmap[txrate].ieeerate;
3848 		sc->sc_tx_th.wt_txpower = ni->ni_txpower;
3849 		sc->sc_tx_th.wt_antenna = sc->sc_txantenna;
3850 
3851 		bpf_mtap2(sc->sc_drvbpf,
3852 			&sc->sc_tx_th, sc->sc_tx_th_len, m0);
3853 	}
3854 
3855 	/*
3856 	 * Determine if a tx interrupt should be generated for
3857 	 * this descriptor.  We take a tx interrupt to reap
3858 	 * descriptors when the h/w hits an EOL condition or
3859 	 * when the descriptor is specifically marked to generate
3860 	 * an interrupt.  We periodically mark descriptors in this
3861 	 * way to insure timely replenishing of the supply needed
3862 	 * for sending frames.  Defering interrupts reduces system
3863 	 * load and potentially allows more concurrent work to be
3864 	 * done but if done to aggressively can cause senders to
3865 	 * backup.
3866 	 *
3867 	 * NB: use >= to deal with sc_txintrperiod changing
3868 	 *     dynamically through sysctl.
3869 	 */
3870 	if (flags & HAL_TXDESC_INTREQ) {
3871 		txq->axq_intrcnt = 0;
3872 	} else if (++txq->axq_intrcnt >= sc->sc_txintrperiod) {
3873 		flags |= HAL_TXDESC_INTREQ;
3874 		txq->axq_intrcnt = 0;
3875 	}
3876 
3877 	/*
3878 	 * Formulate first tx descriptor with tx controls.
3879 	 */
3880 	/* XXX check return value? */
3881 	ath_hal_setuptxdesc(ah, ds
3882 		, pktlen		/* packet length */
3883 		, hdrlen		/* header length */
3884 		, atype			/* Atheros packet type */
3885 		, ni->ni_txpower	/* txpower */
3886 		, txrate, try0		/* series 0 rate/tries */
3887 		, keyix			/* key cache index */
3888 		, sc->sc_txantenna	/* antenna mode */
3889 		, flags			/* flags */
3890 		, ctsrate		/* rts/cts rate */
3891 		, ctsduration		/* rts/cts duration */
3892 	);
3893 	bf->bf_flags = flags;
3894 	/*
3895 	 * Setup the multi-rate retry state only when we're
3896 	 * going to use it.  This assumes ath_hal_setuptxdesc
3897 	 * initializes the descriptors (so we don't have to)
3898 	 * when the hardware supports multi-rate retry and
3899 	 * we don't use it.
3900 	 */
3901 	if (ismrr)
3902 		ath_rate_setupxtxdesc(sc, an, ds, shortPreamble, rix);
3903 
3904 	ath_tx_handoff(sc, txq, bf);
3905 	return 0;
3906 }
3907 
3908 /*
3909  * Process completed xmit descriptors from the specified queue.
3910  */
3911 static int
3912 ath_tx_processq(struct ath_softc *sc, struct ath_txq *txq)
3913 {
3914 	struct ath_hal *ah = sc->sc_ah;
3915 	struct ieee80211com *ic = &sc->sc_ic;
3916 	struct ath_buf *bf;
3917 	struct ath_desc *ds, *ds0;
3918 	struct ath_tx_status *ts;
3919 	struct ieee80211_node *ni;
3920 	struct ath_node *an;
3921 	int sr, lr, pri, nacked;
3922 	HAL_STATUS status;
3923 
3924 	DPRINTF(sc, ATH_DEBUG_TX_PROC, "%s: tx queue %u head %p link %p\n",
3925 		__func__, txq->axq_qnum,
3926 		(caddr_t)(uintptr_t) ath_hal_gettxbuf(sc->sc_ah, txq->axq_qnum),
3927 		txq->axq_link);
3928 	nacked = 0;
3929 	for (;;) {
3930 		ATH_TXQ_LOCK(txq);
3931 		txq->axq_intrcnt = 0;	/* reset periodic desc intr count */
3932 		bf = STAILQ_FIRST(&txq->axq_q);
3933 		if (bf == NULL) {
3934 			ATH_TXQ_UNLOCK(txq);
3935 			break;
3936 		}
3937 		ds0 = &bf->bf_desc[0];
3938 		ds = &bf->bf_desc[bf->bf_nseg - 1];
3939 		ts = &bf->bf_status.ds_txstat;
3940 		status = ath_hal_txprocdesc(ah, ds, ts);
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 (ts->ts_status == 0) {
3958 				u_int8_t txant = ts->ts_antenna;
3959 				sc->sc_stats.ast_ant_tx[txant]++;
3960 				sc->sc_ant_tx[txant]++;
3961 				if (ts->ts_rate & HAL_TXSTAT_ALTRATE)
3962 					sc->sc_stats.ast_tx_altrate++;
3963 				sc->sc_stats.ast_tx_rssi = ts->ts_rssi;
3964 				ATH_RSSI_LPF(sc->sc_halstats.ns_avgtxrssi,
3965 					ts->ts_rssi);
3966 				pri = M_WME_GETAC(bf->bf_m);
3967 				if (pri >= WME_AC_VO)
3968 					ic->ic_wme.wme_hipri_traffic++;
3969 				ni->ni_inact = ni->ni_inact_reload;
3970 			} else {
3971 				if (ts->ts_status & HAL_TXERR_XRETRY)
3972 					sc->sc_stats.ast_tx_xretries++;
3973 				if (ts->ts_status & HAL_TXERR_FIFO)
3974 					sc->sc_stats.ast_tx_fifoerr++;
3975 				if (ts->ts_status & HAL_TXERR_FILT)
3976 					sc->sc_stats.ast_tx_filtered++;
3977 			}
3978 			sr = ts->ts_shortretry;
3979 			lr = ts->ts_longretry;
3980 			sc->sc_stats.ast_tx_shortretry += sr;
3981 			sc->sc_stats.ast_tx_longretry += lr;
3982 			/*
3983 			 * Hand the descriptor to the rate control algorithm.
3984 			 */
3985 			if ((ts->ts_status & HAL_TXERR_FILT) == 0 &&
3986 			    (bf->bf_flags & HAL_TXDESC_NOACK) == 0) {
3987 				/*
3988 				 * If frame was ack'd update the last rx time
3989 				 * used to workaround phantom bmiss interrupts.
3990 				 */
3991 				if (ts->ts_status == 0)
3992 					nacked++;
3993 				ath_rate_tx_complete(sc, an, bf);
3994 			}
3995 			/*
3996 			 * Reclaim reference to node.
3997 			 *
3998 			 * NB: the node may be reclaimed here if, for example
3999 			 *     this is a DEAUTH message that was sent and the
4000 			 *     node was timed out due to inactivity.
4001 			 */
4002 			ieee80211_free_node(ni);
4003 		}
4004 		bus_dmamap_sync(sc->sc_dmat, bf->bf_dmamap,
4005 		    BUS_DMASYNC_POSTWRITE);
4006 		bus_dmamap_unload(sc->sc_dmat, bf->bf_dmamap);
4007 		m_freem(bf->bf_m);
4008 		bf->bf_m = NULL;
4009 		bf->bf_node = NULL;
4010 
4011 		ATH_TXBUF_LOCK(sc);
4012 		STAILQ_INSERT_TAIL(&sc->sc_txbuf, bf, bf_list);
4013 		ATH_TXBUF_UNLOCK(sc);
4014 	}
4015 	return nacked;
4016 }
4017 
4018 static __inline int
4019 txqactive(struct ath_hal *ah, int qnum)
4020 {
4021 	u_int32_t txqs = 1<<qnum;
4022 	ath_hal_gettxintrtxqs(ah, &txqs);
4023 	return (txqs & (1<<qnum));
4024 }
4025 
4026 /*
4027  * Deferred processing of transmit interrupt; special-cased
4028  * for a single hardware transmit queue (e.g. 5210 and 5211).
4029  */
4030 static void
4031 ath_tx_proc_q0(void *arg, int npending)
4032 {
4033 	struct ath_softc *sc = arg;
4034 	struct ifnet *ifp = sc->sc_ifp;
4035 
4036 	if (txqactive(sc->sc_ah, 0) && ath_tx_processq(sc, &sc->sc_txq[0]))
4037 		sc->sc_lastrx = ath_hal_gettsf64(sc->sc_ah);
4038 	if (txqactive(sc->sc_ah, sc->sc_cabq->axq_qnum))
4039 		ath_tx_processq(sc, sc->sc_cabq);
4040 	ifp->if_drv_flags &= ~IFF_DRV_OACTIVE;
4041 	sc->sc_tx_timer = 0;
4042 
4043 	if (sc->sc_softled)
4044 		ath_led_event(sc, ATH_LED_TX);
4045 
4046 	ath_start(ifp);
4047 }
4048 
4049 /*
4050  * Deferred processing of transmit interrupt; special-cased
4051  * for four hardware queues, 0-3 (e.g. 5212 w/ WME support).
4052  */
4053 static void
4054 ath_tx_proc_q0123(void *arg, int npending)
4055 {
4056 	struct ath_softc *sc = arg;
4057 	struct ifnet *ifp = sc->sc_ifp;
4058 	int nacked;
4059 
4060 	/*
4061 	 * Process each active queue.
4062 	 */
4063 	nacked = 0;
4064 	if (txqactive(sc->sc_ah, 0))
4065 		nacked += ath_tx_processq(sc, &sc->sc_txq[0]);
4066 	if (txqactive(sc->sc_ah, 1))
4067 		nacked += ath_tx_processq(sc, &sc->sc_txq[1]);
4068 	if (txqactive(sc->sc_ah, 2))
4069 		nacked += ath_tx_processq(sc, &sc->sc_txq[2]);
4070 	if (txqactive(sc->sc_ah, 3))
4071 		nacked += ath_tx_processq(sc, &sc->sc_txq[3]);
4072 	if (txqactive(sc->sc_ah, sc->sc_cabq->axq_qnum))
4073 		ath_tx_processq(sc, sc->sc_cabq);
4074 	if (nacked)
4075 		sc->sc_lastrx = ath_hal_gettsf64(sc->sc_ah);
4076 
4077 	ifp->if_drv_flags &= ~IFF_DRV_OACTIVE;
4078 	sc->sc_tx_timer = 0;
4079 
4080 	if (sc->sc_softled)
4081 		ath_led_event(sc, ATH_LED_TX);
4082 
4083 	ath_start(ifp);
4084 }
4085 
4086 /*
4087  * Deferred processing of transmit interrupt.
4088  */
4089 static void
4090 ath_tx_proc(void *arg, int npending)
4091 {
4092 	struct ath_softc *sc = arg;
4093 	struct ifnet *ifp = sc->sc_ifp;
4094 	int i, nacked;
4095 
4096 	/*
4097 	 * Process each active queue.
4098 	 */
4099 	nacked = 0;
4100 	for (i = 0; i < HAL_NUM_TX_QUEUES; i++)
4101 		if (ATH_TXQ_SETUP(sc, i) && txqactive(sc->sc_ah, i))
4102 			nacked += ath_tx_processq(sc, &sc->sc_txq[i]);
4103 	if (nacked)
4104 		sc->sc_lastrx = ath_hal_gettsf64(sc->sc_ah);
4105 
4106 	ifp->if_drv_flags &= ~IFF_DRV_OACTIVE;
4107 	sc->sc_tx_timer = 0;
4108 
4109 	if (sc->sc_softled)
4110 		ath_led_event(sc, ATH_LED_TX);
4111 
4112 	ath_start(ifp);
4113 }
4114 
4115 static void
4116 ath_tx_draintxq(struct ath_softc *sc, struct ath_txq *txq)
4117 {
4118 #ifdef ATH_DEBUG
4119 	struct ath_hal *ah = sc->sc_ah;
4120 #endif
4121 	struct ieee80211_node *ni;
4122 	struct ath_buf *bf;
4123 	u_int ix;
4124 
4125 	/*
4126 	 * NB: this assumes output has been stopped and
4127 	 *     we do not need to block ath_tx_tasklet
4128 	 */
4129 	for (ix = 0;; ix++) {
4130 		ATH_TXQ_LOCK(txq);
4131 		bf = STAILQ_FIRST(&txq->axq_q);
4132 		if (bf == NULL) {
4133 			txq->axq_link = NULL;
4134 			ATH_TXQ_UNLOCK(txq);
4135 			break;
4136 		}
4137 		ATH_TXQ_REMOVE_HEAD(txq, bf_list);
4138 		ATH_TXQ_UNLOCK(txq);
4139 #ifdef ATH_DEBUG
4140 		if (sc->sc_debug & ATH_DEBUG_RESET) {
4141 			ath_printtxbuf(bf, txq->axq_qnum, ix,
4142 				ath_hal_txprocdesc(ah, bf->bf_desc,
4143 				    &bf->bf_status.ds_txstat) == 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,
4209 				    &bf->bf_status.ds_txstat) == HAL_OK);
4210 			ieee80211_dump_pkt(mtod(bf->bf_m, caddr_t),
4211 				bf->bf_m->m_len, 0, -1);
4212 		}
4213 	}
4214 #endif /* ATH_DEBUG */
4215 	ifp->if_drv_flags &= ~IFF_DRV_OACTIVE;
4216 	sc->sc_tx_timer = 0;
4217 }
4218 
4219 /*
4220  * Disable the receive h/w in preparation for a reset.
4221  */
4222 static void
4223 ath_stoprecv(struct ath_softc *sc)
4224 {
4225 #define	PA2DESC(_sc, _pa) \
4226 	((struct ath_desc *)((caddr_t)(_sc)->sc_rxdma.dd_desc + \
4227 		((_pa) - (_sc)->sc_rxdma.dd_desc_paddr)))
4228 	struct ath_hal *ah = sc->sc_ah;
4229 
4230 	ath_hal_stoppcurecv(ah);	/* disable PCU */
4231 	ath_hal_setrxfilter(ah, 0);	/* clear recv filter */
4232 	ath_hal_stopdmarecv(ah);	/* disable DMA engine */
4233 	DELAY(3000);			/* 3ms is long enough for 1 frame */
4234 #ifdef ATH_DEBUG
4235 	if (sc->sc_debug & (ATH_DEBUG_RESET | ATH_DEBUG_FATAL)) {
4236 		struct ath_buf *bf;
4237 		u_int ix;
4238 
4239 		printf("%s: rx queue %p, link %p\n", __func__,
4240 			(caddr_t)(uintptr_t) ath_hal_getrxbuf(ah), sc->sc_rxlink);
4241 		ix = 0;
4242 		STAILQ_FOREACH(bf, &sc->sc_rxbuf, bf_list) {
4243 			struct ath_desc *ds = bf->bf_desc;
4244 			struct ath_rx_status *rs = &bf->bf_status.ds_rxstat;
4245 			HAL_STATUS status = ath_hal_rxprocdesc(ah, ds,
4246 				bf->bf_daddr, PA2DESC(sc, ds->ds_link), rs);
4247 			if (status == HAL_OK || (sc->sc_debug & ATH_DEBUG_FATAL))
4248 				ath_printrxbuf(bf, ix, status == HAL_OK);
4249 			ix++;
4250 		}
4251 	}
4252 #endif
4253 	sc->sc_rxlink = NULL;		/* just in case */
4254 #undef PA2DESC
4255 }
4256 
4257 /*
4258  * Enable the receive h/w following a reset.
4259  */
4260 static int
4261 ath_startrecv(struct ath_softc *sc)
4262 {
4263 	struct ath_hal *ah = sc->sc_ah;
4264 	struct ath_buf *bf;
4265 
4266 	sc->sc_rxlink = NULL;
4267 	STAILQ_FOREACH(bf, &sc->sc_rxbuf, bf_list) {
4268 		int error = ath_rxbuf_init(sc, bf);
4269 		if (error != 0) {
4270 			DPRINTF(sc, ATH_DEBUG_RECV,
4271 				"%s: ath_rxbuf_init failed %d\n",
4272 				__func__, error);
4273 			return error;
4274 		}
4275 	}
4276 
4277 	bf = STAILQ_FIRST(&sc->sc_rxbuf);
4278 	ath_hal_putrxbuf(ah, bf->bf_daddr);
4279 	ath_hal_rxena(ah);		/* enable recv descriptors */
4280 	ath_mode_init(sc);		/* set filters, etc. */
4281 	ath_hal_startpcurecv(ah);	/* re-enable PCU/DMA engine */
4282 	return 0;
4283 }
4284 
4285 /*
4286  * Update internal state after a channel change.
4287  */
4288 static void
4289 ath_chan_change(struct ath_softc *sc, struct ieee80211_channel *chan)
4290 {
4291 	struct ieee80211com *ic = &sc->sc_ic;
4292 	enum ieee80211_phymode mode;
4293 	u_int16_t flags;
4294 
4295 	/*
4296 	 * Change channels and update the h/w rate map
4297 	 * if we're switching; e.g. 11a to 11b/g.
4298 	 */
4299 	mode = ieee80211_chan2mode(ic, chan);
4300 	if (mode != sc->sc_curmode)
4301 		ath_setcurmode(sc, mode);
4302 	/*
4303 	 * Update BPF state.  NB: ethereal et. al. don't handle
4304 	 * merged flags well so pick a unique mode for their use.
4305 	 */
4306 	if (IEEE80211_IS_CHAN_A(chan))
4307 		flags = IEEE80211_CHAN_A;
4308 	/* XXX 11g schizophrenia */
4309 	else if (IEEE80211_IS_CHAN_G(chan) ||
4310 	    IEEE80211_IS_CHAN_PUREG(chan))
4311 		flags = IEEE80211_CHAN_G;
4312 	else
4313 		flags = IEEE80211_CHAN_B;
4314 	if (IEEE80211_IS_CHAN_T(chan))
4315 		flags |= IEEE80211_CHAN_TURBO;
4316 	sc->sc_tx_th.wt_chan_freq = sc->sc_rx_th.wr_chan_freq =
4317 		htole16(chan->ic_freq);
4318 	sc->sc_tx_th.wt_chan_flags = sc->sc_rx_th.wr_chan_flags =
4319 		htole16(flags);
4320 }
4321 
4322 /*
4323  * Poll for a channel clear indication; this is required
4324  * for channels requiring DFS and not previously visited
4325  * and/or with a recent radar detection.
4326  */
4327 static void
4328 ath_dfswait(void *arg)
4329 {
4330 	struct ath_softc *sc = arg;
4331 	struct ath_hal *ah = sc->sc_ah;
4332 	HAL_CHANNEL hchan;
4333 
4334 	ath_hal_radar_wait(ah, &hchan);
4335 	DPRINTF(sc, ATH_DEBUG_DFS, "%s: radar_wait %u/%x/%x\n",
4336 	    __func__, hchan.channel, hchan.channelFlags, hchan.privFlags);
4337 
4338 	if (hchan.privFlags & CHANNEL_INTERFERENCE) {
4339 		if_printf(sc->sc_ifp,
4340 		    "channel %u/0x%x/0x%x has interference\n",
4341 		    hchan.channel, hchan.channelFlags, hchan.privFlags);
4342 		return;
4343 	}
4344 	if ((hchan.privFlags & CHANNEL_DFS) == 0) {
4345 		/* XXX should not happen */
4346 		return;
4347 	}
4348 	if (hchan.privFlags & CHANNEL_DFS_CLEAR) {
4349 		sc->sc_curchan.privFlags |= CHANNEL_DFS_CLEAR;
4350 		sc->sc_ifp->if_drv_flags &= ~IFF_DRV_OACTIVE;
4351 		if_printf(sc->sc_ifp,
4352 		    "channel %u/0x%x/0x%x marked clear\n",
4353 		    hchan.channel, hchan.channelFlags, hchan.privFlags);
4354 	} else
4355 		callout_reset(&sc->sc_dfs_ch, 2 * hz, ath_dfswait, sc);
4356 }
4357 
4358 /*
4359  * Set/change channels.  If the channel is really being changed,
4360  * it's done by reseting the chip.  To accomplish this we must
4361  * first cleanup any pending DMA, then restart stuff after a la
4362  * ath_init.
4363  */
4364 static int
4365 ath_chan_set(struct ath_softc *sc, struct ieee80211_channel *chan)
4366 {
4367 	struct ath_hal *ah = sc->sc_ah;
4368 	struct ieee80211com *ic = &sc->sc_ic;
4369 	HAL_CHANNEL hchan;
4370 
4371 	/*
4372 	 * Convert to a HAL channel description with
4373 	 * the flags constrained to reflect the current
4374 	 * operating mode.
4375 	 */
4376 	hchan.channel = chan->ic_freq;
4377 	hchan.channelFlags = ath_chan2flags(ic, chan);
4378 
4379 	DPRINTF(sc, ATH_DEBUG_RESET,
4380 	    "%s: %u (%u MHz, hal flags 0x%x) -> %u (%u MHz, hal flags 0x%x)\n",
4381 	    __func__,
4382 	    ath_hal_mhz2ieee(ah, sc->sc_curchan.channel,
4383 		sc->sc_curchan.channelFlags),
4384 	    	sc->sc_curchan.channel, sc->sc_curchan.channelFlags,
4385 	    ath_hal_mhz2ieee(ah, hchan.channel, hchan.channelFlags),
4386 	        hchan.channel, hchan.channelFlags);
4387 	if (hchan.channel != sc->sc_curchan.channel ||
4388 	    hchan.channelFlags != sc->sc_curchan.channelFlags) {
4389 		HAL_STATUS status;
4390 
4391 		/*
4392 		 * To switch channels clear any pending DMA operations;
4393 		 * wait long enough for the RX fifo to drain, reset the
4394 		 * hardware at the new frequency, and then re-enable
4395 		 * the relevant bits of the h/w.
4396 		 */
4397 		ath_hal_intrset(ah, 0);		/* disable interrupts */
4398 		ath_draintxq(sc);		/* clear pending tx frames */
4399 		ath_stoprecv(sc);		/* turn off frame recv */
4400 		if (!ath_hal_reset(ah, sc->sc_opmode, &hchan, AH_TRUE, &status)) {
4401 			if_printf(ic->ic_ifp, "%s: unable to reset "
4402 			    "channel %u (%u Mhz, flags 0x%x hal flags 0x%x)\n",
4403 			    __func__, ieee80211_chan2ieee(ic, chan),
4404 			    chan->ic_freq, chan->ic_flags, hchan.channelFlags);
4405 			return EIO;
4406 		}
4407 		sc->sc_curchan = hchan;
4408 		ath_update_txpow(sc);		/* update tx power state */
4409 		sc->sc_diversity = ath_hal_getdiversity(ah);
4410 		sc->sc_calinterval = 1;
4411 		sc->sc_caltries = 0;
4412 
4413 		/*
4414 		 * Re-enable rx framework.
4415 		 */
4416 		if (ath_startrecv(sc) != 0) {
4417 			if_printf(ic->ic_ifp,
4418 				"%s: unable to restart recv logic\n", __func__);
4419 			return EIO;
4420 		}
4421 
4422 		/*
4423 		 * Change channels and update the h/w rate map
4424 		 * if we're switching; e.g. 11a to 11b/g.
4425 		 */
4426 		ic->ic_ibss_chan = chan;
4427 		ath_chan_change(sc, chan);
4428 
4429 		/*
4430 		 * Handle DFS required waiting period to determine
4431 		 * if channel is clear of radar traffic.
4432 		 */
4433 		if (ic->ic_opmode == IEEE80211_M_HOSTAP) {
4434 #define	DFS_AND_NOT_CLEAR(_c) \
4435 	(((_c)->privFlags & (CHANNEL_DFS | CHANNEL_DFS_CLEAR)) == CHANNEL_DFS)
4436 			if (DFS_AND_NOT_CLEAR(&sc->sc_curchan)) {
4437 				if_printf(sc->sc_ifp,
4438 					"wait for DFS clear channel signal\n");
4439 				/* XXX stop sndq */
4440 				sc->sc_ifp->if_drv_flags |= IFF_DRV_OACTIVE;
4441 				callout_reset(&sc->sc_dfs_ch,
4442 					2 * hz, ath_dfswait, sc);
4443 			} else
4444 				callout_stop(&sc->sc_dfs_ch);
4445 #undef DFS_NOT_CLEAR
4446 		}
4447 
4448 		/*
4449 		 * Re-enable interrupts.
4450 		 */
4451 		ath_hal_intrset(ah, sc->sc_imask);
4452 	}
4453 	return 0;
4454 }
4455 
4456 static void
4457 ath_next_scan(void *arg)
4458 {
4459 	struct ath_softc *sc = arg;
4460 	struct ieee80211com *ic = &sc->sc_ic;
4461 
4462 	if (ic->ic_state == IEEE80211_S_SCAN)
4463 		ieee80211_next_scan(ic);
4464 }
4465 
4466 /*
4467  * Periodically recalibrate the PHY to account
4468  * for temperature/environment changes.
4469  */
4470 static void
4471 ath_calibrate(void *arg)
4472 {
4473 	struct ath_softc *sc = arg;
4474 	struct ath_hal *ah = sc->sc_ah;
4475 	HAL_BOOL iqCalDone;
4476 
4477 	sc->sc_stats.ast_per_cal++;
4478 
4479 	if (ath_hal_getrfgain(ah) == HAL_RFGAIN_NEED_CHANGE) {
4480 		/*
4481 		 * Rfgain is out of bounds, reset the chip
4482 		 * to load new gain values.
4483 		 */
4484 		DPRINTF(sc, ATH_DEBUG_CALIBRATE,
4485 			"%s: rfgain change\n", __func__);
4486 		sc->sc_stats.ast_per_rfgain++;
4487 		ath_reset(sc->sc_ifp);
4488 	}
4489 	if (!ath_hal_calibrate(ah, &sc->sc_curchan, &iqCalDone)) {
4490 		DPRINTF(sc, ATH_DEBUG_ANY,
4491 			"%s: calibration of channel %u failed\n",
4492 			__func__, sc->sc_curchan.channel);
4493 		sc->sc_stats.ast_per_calfail++;
4494 	}
4495 	/*
4496 	 * Calibrate noise floor data again in case of change.
4497 	 */
4498 	ath_hal_process_noisefloor(ah);
4499 	/*
4500 	 * Poll more frequently when the IQ calibration is in
4501 	 * progress to speedup loading the final settings.
4502 	 * We temper this aggressive polling with an exponential
4503 	 * back off after 4 tries up to ath_calinterval.
4504 	 */
4505 	if (iqCalDone || sc->sc_calinterval >= ath_calinterval) {
4506 		sc->sc_caltries = 0;
4507 		sc->sc_calinterval = ath_calinterval;
4508 	} else if (sc->sc_caltries > 4) {
4509 		sc->sc_caltries = 0;
4510 		sc->sc_calinterval <<= 1;
4511 		if (sc->sc_calinterval > ath_calinterval)
4512 			sc->sc_calinterval = ath_calinterval;
4513 	}
4514 	KASSERT(0 < sc->sc_calinterval && sc->sc_calinterval <= ath_calinterval,
4515 		("bad calibration interval %u", sc->sc_calinterval));
4516 
4517 	DPRINTF(sc, ATH_DEBUG_CALIBRATE,
4518 		"%s: next +%u (%siqCalDone tries %u)\n", __func__,
4519 		sc->sc_calinterval, iqCalDone ? "" : "!", sc->sc_caltries);
4520 	sc->sc_caltries++;
4521 	callout_reset(&sc->sc_cal_ch, sc->sc_calinterval * hz,
4522 		ath_calibrate, sc);
4523 }
4524 
4525 static int
4526 ath_newstate(struct ieee80211com *ic, enum ieee80211_state nstate, int arg)
4527 {
4528 	struct ifnet *ifp = ic->ic_ifp;
4529 	struct ath_softc *sc = ifp->if_softc;
4530 	struct ath_hal *ah = sc->sc_ah;
4531 	struct ieee80211_node *ni;
4532 	int i, error;
4533 	const u_int8_t *bssid;
4534 	u_int32_t rfilt;
4535 	static const HAL_LED_STATE leds[] = {
4536 	    HAL_LED_INIT,	/* IEEE80211_S_INIT */
4537 	    HAL_LED_SCAN,	/* IEEE80211_S_SCAN */
4538 	    HAL_LED_AUTH,	/* IEEE80211_S_AUTH */
4539 	    HAL_LED_ASSOC, 	/* IEEE80211_S_ASSOC */
4540 	    HAL_LED_RUN, 	/* IEEE80211_S_RUN */
4541 	};
4542 
4543 	DPRINTF(sc, ATH_DEBUG_STATE, "%s: %s -> %s\n", __func__,
4544 		ieee80211_state_name[ic->ic_state],
4545 		ieee80211_state_name[nstate]);
4546 
4547 	callout_stop(&sc->sc_scan_ch);
4548 	callout_stop(&sc->sc_cal_ch);
4549 	callout_stop(&sc->sc_dfs_ch);
4550 	ath_hal_setledstate(ah, leds[nstate]);	/* set LED */
4551 
4552 	if (nstate == IEEE80211_S_INIT) {
4553 		sc->sc_imask &= ~(HAL_INT_SWBA | HAL_INT_BMISS);
4554 		/*
4555 		 * NB: disable interrupts so we don't rx frames.
4556 		 */
4557 		ath_hal_intrset(ah, sc->sc_imask &~ HAL_INT_GLOBAL);
4558 		/*
4559 		 * Notify the rate control algorithm.
4560 		 */
4561 		ath_rate_newstate(sc, nstate);
4562 		goto done;
4563 	}
4564 	ni = ic->ic_bss;
4565 	error = ath_chan_set(sc, ic->ic_curchan);
4566 	if (error != 0)
4567 		goto bad;
4568 	rfilt = ath_calcrxfilter(sc, nstate);
4569 	if (nstate == IEEE80211_S_SCAN)
4570 		bssid = ifp->if_broadcastaddr;
4571 	else
4572 		bssid = ni->ni_bssid;
4573 	ath_hal_setrxfilter(ah, rfilt);
4574 	DPRINTF(sc, ATH_DEBUG_STATE, "%s: RX filter 0x%x bssid %s\n",
4575 		 __func__, rfilt, ether_sprintf(bssid));
4576 
4577 	if (nstate == IEEE80211_S_RUN && ic->ic_opmode == IEEE80211_M_STA)
4578 		ath_hal_setassocid(ah, bssid, ni->ni_associd);
4579 	else
4580 		ath_hal_setassocid(ah, bssid, 0);
4581 	if (ic->ic_flags & IEEE80211_F_PRIVACY) {
4582 		for (i = 0; i < IEEE80211_WEP_NKID; i++)
4583 			if (ath_hal_keyisvalid(ah, i))
4584 				ath_hal_keysetmac(ah, i, bssid);
4585 	}
4586 
4587 	/*
4588 	 * Notify the rate control algorithm so rates
4589 	 * are setup should ath_beacon_alloc be called.
4590 	 */
4591 	ath_rate_newstate(sc, nstate);
4592 
4593 	if (ic->ic_opmode == IEEE80211_M_MONITOR) {
4594 		/* nothing to do */;
4595 	} else if (nstate == IEEE80211_S_RUN) {
4596 		DPRINTF(sc, ATH_DEBUG_STATE,
4597 			"%s(RUN): ic_flags=0x%08x iv=%d bssid=%s "
4598 			"capinfo=0x%04x chan=%d\n"
4599 			 , __func__
4600 			 , ic->ic_flags
4601 			 , ni->ni_intval
4602 			 , ether_sprintf(ni->ni_bssid)
4603 			 , ni->ni_capinfo
4604 			 , ieee80211_chan2ieee(ic, ic->ic_curchan));
4605 
4606 		switch (ic->ic_opmode) {
4607 		case IEEE80211_M_HOSTAP:
4608 		case IEEE80211_M_IBSS:
4609 			/*
4610 			 * Allocate and setup the beacon frame.
4611 			 *
4612 			 * Stop any previous beacon DMA.  This may be
4613 			 * necessary, for example, when an ibss merge
4614 			 * causes reconfiguration; there will be a state
4615 			 * transition from RUN->RUN that means we may
4616 			 * be called with beacon transmission active.
4617 			 */
4618 			ath_hal_stoptxdma(ah, sc->sc_bhalq);
4619 			ath_beacon_free(sc);
4620 			error = ath_beacon_alloc(sc, ni);
4621 			if (error != 0)
4622 				goto bad;
4623 			/*
4624 			 * If joining an adhoc network defer beacon timer
4625 			 * configuration to the next beacon frame so we
4626 			 * have a current TSF to use.  Otherwise we're
4627 			 * starting an ibss/bss so there's no need to delay.
4628 			 */
4629 			if (ic->ic_opmode == IEEE80211_M_IBSS &&
4630 			    ic->ic_bss->ni_tstamp.tsf != 0)
4631 				sc->sc_syncbeacon = 1;
4632 			else
4633 				ath_beacon_config(sc);
4634 			break;
4635 		case IEEE80211_M_STA:
4636 			/*
4637 			 * Allocate a key cache slot to the station.
4638 			 */
4639 			if ((ic->ic_flags & IEEE80211_F_PRIVACY) == 0 &&
4640 			    sc->sc_hasclrkey &&
4641 			    ni->ni_ucastkey.wk_keyix == IEEE80211_KEYIX_NONE)
4642 				ath_setup_stationkey(ni);
4643 			/*
4644 			 * Defer beacon timer configuration to the next
4645 			 * beacon frame so we have a current TSF to use
4646 			 * (any TSF collected when scanning is likely old).
4647 			 */
4648 			sc->sc_syncbeacon = 1;
4649 			break;
4650 		default:
4651 			break;
4652 		}
4653 
4654 		/*
4655 		 * Let the hal process statistics collected during a
4656 		 * scan so it can provide calibrated noise floor data.
4657 		 */
4658 		ath_hal_process_noisefloor(ah);
4659 		/*
4660 		 * Reset rssi stats; maybe not the best place...
4661 		 */
4662 		sc->sc_halstats.ns_avgbrssi = ATH_RSSI_DUMMY_MARKER;
4663 		sc->sc_halstats.ns_avgrssi = ATH_RSSI_DUMMY_MARKER;
4664 		sc->sc_halstats.ns_avgtxrssi = ATH_RSSI_DUMMY_MARKER;
4665 	} else {
4666 		ath_hal_intrset(ah,
4667 			sc->sc_imask &~ (HAL_INT_SWBA | HAL_INT_BMISS));
4668 		sc->sc_imask &= ~(HAL_INT_SWBA | HAL_INT_BMISS);
4669 	}
4670 done:
4671 	/*
4672 	 * Invoke the parent method to complete the work.
4673 	 */
4674 	error = sc->sc_newstate(ic, nstate, arg);
4675 	/*
4676 	 * Finally, start any timers.
4677 	 */
4678 	if (nstate == IEEE80211_S_RUN) {
4679 		/* start periodic recalibration timer */
4680 		callout_reset(&sc->sc_cal_ch, sc->sc_calinterval * hz,
4681 			ath_calibrate, sc);
4682 	} else if (nstate == IEEE80211_S_SCAN) {
4683 		/* start ap/neighbor scan timer */
4684 		callout_reset(&sc->sc_scan_ch, (ath_dwelltime * hz) / 1000,
4685 			ath_next_scan, sc);
4686 	}
4687 bad:
4688 	return error;
4689 }
4690 
4691 /*
4692  * Allocate a key cache slot to the station so we can
4693  * setup a mapping from key index to node. The key cache
4694  * slot is needed for managing antenna state and for
4695  * compression when stations do not use crypto.  We do
4696  * it uniliaterally here; if crypto is employed this slot
4697  * will be reassigned.
4698  */
4699 static void
4700 ath_setup_stationkey(struct ieee80211_node *ni)
4701 {
4702 	struct ieee80211com *ic = ni->ni_ic;
4703 	struct ath_softc *sc = ic->ic_ifp->if_softc;
4704 	ieee80211_keyix keyix, rxkeyix;
4705 
4706 	if (!ath_key_alloc(ic, &ni->ni_ucastkey, &keyix, &rxkeyix)) {
4707 		/*
4708 		 * Key cache is full; we'll fall back to doing
4709 		 * the more expensive lookup in software.  Note
4710 		 * this also means no h/w compression.
4711 		 */
4712 		/* XXX msg+statistic */
4713 	} else {
4714 		/* XXX locking? */
4715 		ni->ni_ucastkey.wk_keyix = keyix;
4716 		ni->ni_ucastkey.wk_rxkeyix = rxkeyix;
4717 		/* NB: this will create a pass-thru key entry */
4718 		ath_keyset(sc, &ni->ni_ucastkey, ni->ni_macaddr, ic->ic_bss);
4719 	}
4720 }
4721 
4722 /*
4723  * Setup driver-specific state for a newly associated node.
4724  * Note that we're called also on a re-associate, the isnew
4725  * param tells us if this is the first time or not.
4726  */
4727 static void
4728 ath_newassoc(struct ieee80211_node *ni, int isnew)
4729 {
4730 	struct ieee80211com *ic = ni->ni_ic;
4731 	struct ath_softc *sc = ic->ic_ifp->if_softc;
4732 
4733 	ath_rate_newassoc(sc, ATH_NODE(ni), isnew);
4734 	if (isnew &&
4735 	    (ic->ic_flags & IEEE80211_F_PRIVACY) == 0 && sc->sc_hasclrkey) {
4736 		KASSERT(ni->ni_ucastkey.wk_keyix == IEEE80211_KEYIX_NONE,
4737 		    ("new assoc with a unicast key already setup (keyix %u)",
4738 		    ni->ni_ucastkey.wk_keyix));
4739 		ath_setup_stationkey(ni);
4740 	}
4741 }
4742 
4743 static int
4744 ath_getchannels(struct ath_softc *sc, u_int cc,
4745 	HAL_BOOL outdoor, HAL_BOOL xchanmode)
4746 {
4747 #define	COMPAT	(CHANNEL_ALL_NOTURBO|CHANNEL_PASSIVE)
4748 #define IS_CHAN_PUBLIC_SAFETY(_c) \
4749 	(((_c)->channelFlags & CHANNEL_5GHZ) && \
4750 	 ((_c)->channel > 4940 && (_c)->channel < 4990))
4751 	struct ieee80211com *ic = &sc->sc_ic;
4752 	struct ifnet *ifp = sc->sc_ifp;
4753 	struct ath_hal *ah = sc->sc_ah;
4754 	HAL_CHANNEL *chans;
4755 	int i, ix, nchan;
4756 
4757 	chans = malloc(IEEE80211_CHAN_MAX * sizeof(HAL_CHANNEL),
4758 			M_TEMP, M_NOWAIT);
4759 	if (chans == NULL) {
4760 		if_printf(ifp, "unable to allocate channel table\n");
4761 		return ENOMEM;
4762 	}
4763 	if (!ath_hal_init_channels(ah, chans, IEEE80211_CHAN_MAX, &nchan,
4764 	    NULL, 0, NULL,
4765 	    cc, HAL_MODE_ALL, outdoor, xchanmode)) {
4766 		u_int32_t rd;
4767 
4768 		ath_hal_getregdomain(ah, &rd);
4769 		if_printf(ifp, "unable to collect channel list from hal; "
4770 			"regdomain likely %u country code %u\n", rd, cc);
4771 		free(chans, M_TEMP);
4772 		return EINVAL;
4773 	}
4774 
4775 	/*
4776 	 * Convert HAL channels to ieee80211 ones and insert
4777 	 * them in the table according to their channel number.
4778 	 */
4779 	for (i = 0; i < nchan; i++) {
4780 		HAL_CHANNEL *c = &chans[i];
4781 		u_int16_t flags;
4782 
4783 		/*
4784 		 * XXX we're not ready to handle the ieee number mapping
4785 		 * for public safety channels as they overlap with any
4786 		 * 2GHz channels; for now use the non-public safety
4787 		 * numbering which is non-overlapping.
4788 		 */
4789 		if (IS_CHAN_PUBLIC_SAFETY(c))
4790 			ix = (c->channel - 4000) / 5;
4791 		else
4792 			ix = ath_hal_mhz2ieee(ah, c->channel, c->channelFlags);
4793 		if (ix > IEEE80211_CHAN_MAX) {
4794 			if_printf(ifp, "bad hal channel %d (%u/%x) ignored\n",
4795 				ix, c->channel, c->channelFlags);
4796 			continue;
4797 		}
4798 		if (ix < 0) {
4799 			/* XXX can't handle stuff <2400 right now */
4800 			if (bootverbose)
4801 				if_printf(ifp, "hal channel %d (%u/%x) "
4802 				    "cannot be handled; ignored\n",
4803 				    ix, c->channel, c->channelFlags);
4804 			continue;
4805 		}
4806 		/*
4807 		 * Calculate net80211 flags; most are compatible
4808 		 * but some need massaging.  Note the static turbo
4809 		 * conversion can be removed once net80211 is updated
4810 		 * to understand static vs. dynamic turbo.
4811 		 */
4812 		flags = c->channelFlags & COMPAT;
4813 		if (c->channelFlags & CHANNEL_STURBO)
4814 			flags |= IEEE80211_CHAN_TURBO;
4815 		if (ic->ic_channels[ix].ic_freq == 0) {
4816 			ic->ic_channels[ix].ic_freq = c->channel;
4817 			ic->ic_channels[ix].ic_flags = flags;
4818 		} else {
4819 			/* channels overlap; e.g. 11g and 11b */
4820 			ic->ic_channels[ix].ic_flags |= flags;
4821 		}
4822 	}
4823 	free(chans, M_TEMP);
4824 	return 0;
4825 #undef IS_CHAN_PUBLIC_SAFETY
4826 #undef COMPAT
4827 }
4828 
4829 static void
4830 ath_led_done(void *arg)
4831 {
4832 	struct ath_softc *sc = arg;
4833 
4834 	sc->sc_blinking = 0;
4835 }
4836 
4837 /*
4838  * Turn the LED off: flip the pin and then set a timer so no
4839  * update will happen for the specified duration.
4840  */
4841 static void
4842 ath_led_off(void *arg)
4843 {
4844 	struct ath_softc *sc = arg;
4845 
4846 	ath_hal_gpioset(sc->sc_ah, sc->sc_ledpin, !sc->sc_ledon);
4847 	callout_reset(&sc->sc_ledtimer, sc->sc_ledoff, ath_led_done, sc);
4848 }
4849 
4850 /*
4851  * Blink the LED according to the specified on/off times.
4852  */
4853 static void
4854 ath_led_blink(struct ath_softc *sc, int on, int off)
4855 {
4856 	DPRINTF(sc, ATH_DEBUG_LED, "%s: on %u off %u\n", __func__, on, off);
4857 	ath_hal_gpioset(sc->sc_ah, sc->sc_ledpin, sc->sc_ledon);
4858 	sc->sc_blinking = 1;
4859 	sc->sc_ledoff = off;
4860 	callout_reset(&sc->sc_ledtimer, on, ath_led_off, sc);
4861 }
4862 
4863 static void
4864 ath_led_event(struct ath_softc *sc, int event)
4865 {
4866 
4867 	sc->sc_ledevent = ticks;	/* time of last event */
4868 	if (sc->sc_blinking)		/* don't interrupt active blink */
4869 		return;
4870 	switch (event) {
4871 	case ATH_LED_POLL:
4872 		ath_led_blink(sc, sc->sc_hwmap[0].ledon,
4873 			sc->sc_hwmap[0].ledoff);
4874 		break;
4875 	case ATH_LED_TX:
4876 		ath_led_blink(sc, sc->sc_hwmap[sc->sc_txrate].ledon,
4877 			sc->sc_hwmap[sc->sc_txrate].ledoff);
4878 		break;
4879 	case ATH_LED_RX:
4880 		ath_led_blink(sc, sc->sc_hwmap[sc->sc_rxrate].ledon,
4881 			sc->sc_hwmap[sc->sc_rxrate].ledoff);
4882 		break;
4883 	}
4884 }
4885 
4886 static void
4887 ath_update_txpow(struct ath_softc *sc)
4888 {
4889 	struct ieee80211com *ic = &sc->sc_ic;
4890 	struct ath_hal *ah = sc->sc_ah;
4891 	u_int32_t txpow;
4892 
4893 	if (sc->sc_curtxpow != ic->ic_txpowlimit) {
4894 		ath_hal_settxpowlimit(ah, ic->ic_txpowlimit);
4895 		/* read back in case value is clamped */
4896 		ath_hal_gettxpowlimit(ah, &txpow);
4897 		ic->ic_txpowlimit = sc->sc_curtxpow = txpow;
4898 	}
4899 	/*
4900 	 * Fetch max tx power level for status requests.
4901 	 */
4902 	ath_hal_getmaxtxpow(sc->sc_ah, &txpow);
4903 	ic->ic_bss->ni_txpower = txpow;
4904 }
4905 
4906 static void
4907 rate_setup(struct ath_softc *sc,
4908 	const HAL_RATE_TABLE *rt, struct ieee80211_rateset *rs)
4909 {
4910 	int i, maxrates;
4911 
4912 	if (rt->rateCount > IEEE80211_RATE_MAXSIZE) {
4913 		DPRINTF(sc, ATH_DEBUG_ANY,
4914 			"%s: rate table too small (%u > %u)\n",
4915 		       __func__, rt->rateCount, IEEE80211_RATE_MAXSIZE);
4916 		maxrates = IEEE80211_RATE_MAXSIZE;
4917 	} else
4918 		maxrates = rt->rateCount;
4919 	for (i = 0; i < maxrates; i++)
4920 		rs->rs_rates[i] = rt->info[i].dot11Rate;
4921 	rs->rs_nrates = maxrates;
4922 }
4923 
4924 static int
4925 ath_rate_setup(struct ath_softc *sc, u_int mode)
4926 {
4927 	struct ath_hal *ah = sc->sc_ah;
4928 	struct ieee80211com *ic = &sc->sc_ic;
4929 	const HAL_RATE_TABLE *rt;
4930 
4931 	switch (mode) {
4932 	case IEEE80211_MODE_11A:
4933 		rt = ath_hal_getratetable(ah, HAL_MODE_11A);
4934 		break;
4935 	case IEEE80211_MODE_11B:
4936 		rt = ath_hal_getratetable(ah, HAL_MODE_11B);
4937 		break;
4938 	case IEEE80211_MODE_11G:
4939 		rt = ath_hal_getratetable(ah, HAL_MODE_11G);
4940 		break;
4941 	case IEEE80211_MODE_TURBO_A:
4942 		/* XXX until static/dynamic turbo is fixed */
4943 		rt = ath_hal_getratetable(ah, HAL_MODE_TURBO);
4944 		break;
4945 	case IEEE80211_MODE_TURBO_G:
4946 		rt = ath_hal_getratetable(ah, HAL_MODE_108G);
4947 		break;
4948 	default:
4949 		DPRINTF(sc, ATH_DEBUG_ANY, "%s: invalid mode %u\n",
4950 			__func__, mode);
4951 		return 0;
4952 	}
4953 	sc->sc_rates[mode] = rt;
4954 	if (rt != NULL) {
4955 		rate_setup(sc, rt, &ic->ic_sup_rates[mode]);
4956 		return 1;
4957 	} else
4958 		return 0;
4959 }
4960 
4961 static void
4962 ath_setcurmode(struct ath_softc *sc, enum ieee80211_phymode mode)
4963 {
4964 #define	N(a)	(sizeof(a)/sizeof(a[0]))
4965 	/* NB: on/off times from the Atheros NDIS driver, w/ permission */
4966 	static const struct {
4967 		u_int		rate;		/* tx/rx 802.11 rate */
4968 		u_int16_t	timeOn;		/* LED on time (ms) */
4969 		u_int16_t	timeOff;	/* LED off time (ms) */
4970 	} blinkrates[] = {
4971 		{ 108,  40,  10 },
4972 		{  96,  44,  11 },
4973 		{  72,  50,  13 },
4974 		{  48,  57,  14 },
4975 		{  36,  67,  16 },
4976 		{  24,  80,  20 },
4977 		{  22, 100,  25 },
4978 		{  18, 133,  34 },
4979 		{  12, 160,  40 },
4980 		{  10, 200,  50 },
4981 		{   6, 240,  58 },
4982 		{   4, 267,  66 },
4983 		{   2, 400, 100 },
4984 		{   0, 500, 130 },
4985 	};
4986 	const HAL_RATE_TABLE *rt;
4987 	int i, j;
4988 
4989 	memset(sc->sc_rixmap, 0xff, sizeof(sc->sc_rixmap));
4990 	rt = sc->sc_rates[mode];
4991 	KASSERT(rt != NULL, ("no h/w rate set for phy mode %u", mode));
4992 	for (i = 0; i < rt->rateCount; i++)
4993 		sc->sc_rixmap[rt->info[i].dot11Rate & IEEE80211_RATE_VAL] = i;
4994 	memset(sc->sc_hwmap, 0, sizeof(sc->sc_hwmap));
4995 	for (i = 0; i < 32; i++) {
4996 		u_int8_t ix = rt->rateCodeToIndex[i];
4997 		if (ix == 0xff) {
4998 			sc->sc_hwmap[i].ledon = (500 * hz) / 1000;
4999 			sc->sc_hwmap[i].ledoff = (130 * hz) / 1000;
5000 			continue;
5001 		}
5002 		sc->sc_hwmap[i].ieeerate =
5003 			rt->info[ix].dot11Rate & IEEE80211_RATE_VAL;
5004 		sc->sc_hwmap[i].txflags = IEEE80211_RADIOTAP_F_DATAPAD;
5005 		if (rt->info[ix].shortPreamble ||
5006 		    rt->info[ix].phy == IEEE80211_T_OFDM)
5007 			sc->sc_hwmap[i].txflags |= IEEE80211_RADIOTAP_F_SHORTPRE;
5008 		/* NB: receive frames include FCS */
5009 		sc->sc_hwmap[i].rxflags = sc->sc_hwmap[i].txflags |
5010 			IEEE80211_RADIOTAP_F_FCS;
5011 		/* setup blink rate table to avoid per-packet lookup */
5012 		for (j = 0; j < N(blinkrates)-1; j++)
5013 			if (blinkrates[j].rate == sc->sc_hwmap[i].ieeerate)
5014 				break;
5015 		/* NB: this uses the last entry if the rate isn't found */
5016 		/* XXX beware of overlow */
5017 		sc->sc_hwmap[i].ledon = (blinkrates[j].timeOn * hz) / 1000;
5018 		sc->sc_hwmap[i].ledoff = (blinkrates[j].timeOff * hz) / 1000;
5019 	}
5020 	sc->sc_currates = rt;
5021 	sc->sc_curmode = mode;
5022 	/*
5023 	 * All protection frames are transmited at 2Mb/s for
5024 	 * 11g, otherwise at 1Mb/s.
5025 	 */
5026 	if (mode == IEEE80211_MODE_11G)
5027 		sc->sc_protrix = ath_tx_findrix(rt, 2*2);
5028 	else
5029 		sc->sc_protrix = ath_tx_findrix(rt, 2*1);
5030 	/* rate index used to send management frames */
5031 	sc->sc_minrateix = 0;
5032 	/*
5033 	 * Setup multicast rate state.
5034 	 */
5035 	/* XXX layering violation */
5036 	sc->sc_mcastrix = ath_tx_findrix(rt, sc->sc_ic.ic_mcast_rate);
5037 	sc->sc_mcastrate = sc->sc_ic.ic_mcast_rate;
5038 	/* NB: caller is responsible for reseting rate control state */
5039 #undef N
5040 }
5041 
5042 #ifdef ATH_DEBUG
5043 static void
5044 ath_printrxbuf(const struct ath_buf *bf, u_int ix, int done)
5045 {
5046 	const struct ath_rx_status *rs = &bf->bf_status.ds_rxstat;
5047 	const struct ath_desc *ds;
5048 	int i;
5049 
5050 	for (i = 0, ds = bf->bf_desc; i < bf->bf_nseg; i++, ds++) {
5051 		printf("R[%2u] (DS.V:%p DS.P:%p) L:%08x D:%08x%s\n"
5052 		       "      %08x %08x %08x %08x\n",
5053 		    ix, ds, (const struct ath_desc *)bf->bf_daddr + i,
5054 		    ds->ds_link, ds->ds_data,
5055 		    !done ? "" : (rs->rs_status == 0) ? " *" : " !",
5056 		    ds->ds_ctl0, ds->ds_ctl1,
5057 		    ds->ds_hw[0], ds->ds_hw[1]);
5058 	}
5059 }
5060 
5061 static void
5062 ath_printtxbuf(const struct ath_buf *bf, u_int qnum, u_int ix, int done)
5063 {
5064 	const struct ath_tx_status *ts = &bf->bf_status.ds_txstat;
5065 	const struct ath_desc *ds;
5066 	int i;
5067 
5068 	printf("Q%u[%3u]", qnum, ix);
5069 	for (i = 0, ds = bf->bf_desc; i < bf->bf_nseg; i++, ds++) {
5070 		printf(" (DS.V:%p DS.P:%p) L:%08x D:%08x F:04%x%s\n"
5071 		       "        %08x %08x %08x %08x %08x %08x\n",
5072 		    ds, (const struct ath_desc *)bf->bf_daddr + i,
5073 		    ds->ds_link, ds->ds_data, bf->bf_flags,
5074 		    !done ? "" : (ts->ts_status == 0) ? " *" : " !",
5075 		    ds->ds_ctl0, ds->ds_ctl1,
5076 		    ds->ds_hw[0], ds->ds_hw[1], ds->ds_hw[2], ds->ds_hw[3]);
5077 	}
5078 }
5079 #endif /* ATH_DEBUG */
5080 
5081 static void
5082 ath_watchdog(struct ifnet *ifp)
5083 {
5084 	struct ath_softc *sc = ifp->if_softc;
5085 	struct ieee80211com *ic = &sc->sc_ic;
5086 
5087 	ifp->if_timer = 0;
5088 	if ((ifp->if_drv_flags & IFF_DRV_RUNNING) == 0 || sc->sc_invalid)
5089 		return;
5090 	if (sc->sc_tx_timer) {
5091 		if (--sc->sc_tx_timer == 0) {
5092 			if_printf(ifp, "device timeout\n");
5093 			ath_reset(ifp);
5094 			ifp->if_oerrors++;
5095 			sc->sc_stats.ast_watchdog++;
5096 		} else
5097 			ifp->if_timer = 1;
5098 	}
5099 	ieee80211_watchdog(ic);
5100 }
5101 
5102 #ifdef ATH_DIAGAPI
5103 /*
5104  * Diagnostic interface to the HAL.  This is used by various
5105  * tools to do things like retrieve register contents for
5106  * debugging.  The mechanism is intentionally opaque so that
5107  * it can change frequently w/o concern for compatiblity.
5108  */
5109 static int
5110 ath_ioctl_diag(struct ath_softc *sc, struct ath_diag *ad)
5111 {
5112 	struct ath_hal *ah = sc->sc_ah;
5113 	u_int id = ad->ad_id & ATH_DIAG_ID;
5114 	void *indata = NULL;
5115 	void *outdata = NULL;
5116 	u_int32_t insize = ad->ad_in_size;
5117 	u_int32_t outsize = ad->ad_out_size;
5118 	int error = 0;
5119 
5120 	if (ad->ad_id & ATH_DIAG_IN) {
5121 		/*
5122 		 * Copy in data.
5123 		 */
5124 		indata = malloc(insize, M_TEMP, M_NOWAIT);
5125 		if (indata == NULL) {
5126 			error = ENOMEM;
5127 			goto bad;
5128 		}
5129 		error = copyin(ad->ad_in_data, indata, insize);
5130 		if (error)
5131 			goto bad;
5132 	}
5133 	if (ad->ad_id & ATH_DIAG_DYN) {
5134 		/*
5135 		 * Allocate a buffer for the results (otherwise the HAL
5136 		 * returns a pointer to a buffer where we can read the
5137 		 * results).  Note that we depend on the HAL leaving this
5138 		 * pointer for us to use below in reclaiming the buffer;
5139 		 * may want to be more defensive.
5140 		 */
5141 		outdata = malloc(outsize, M_TEMP, M_NOWAIT);
5142 		if (outdata == NULL) {
5143 			error = ENOMEM;
5144 			goto bad;
5145 		}
5146 	}
5147 	if (ath_hal_getdiagstate(ah, id, indata, insize, &outdata, &outsize)) {
5148 		if (outsize < ad->ad_out_size)
5149 			ad->ad_out_size = outsize;
5150 		if (outdata != NULL)
5151 			error = copyout(outdata, ad->ad_out_data,
5152 					ad->ad_out_size);
5153 	} else {
5154 		error = EINVAL;
5155 	}
5156 bad:
5157 	if ((ad->ad_id & ATH_DIAG_IN) && indata != NULL)
5158 		free(indata, M_TEMP);
5159 	if ((ad->ad_id & ATH_DIAG_DYN) && outdata != NULL)
5160 		free(outdata, M_TEMP);
5161 	return error;
5162 }
5163 #endif /* ATH_DIAGAPI */
5164 
5165 static int
5166 ath_ioctl(struct ifnet *ifp, u_long cmd, caddr_t data)
5167 {
5168 #define	IS_RUNNING(ifp) \
5169 	((ifp->if_flags & IFF_UP) && (ifp->if_drv_flags & IFF_DRV_RUNNING))
5170 	struct ath_softc *sc = ifp->if_softc;
5171 	struct ieee80211com *ic = &sc->sc_ic;
5172 	struct ifreq *ifr = (struct ifreq *)data;
5173 	int error = 0;
5174 
5175 	ATH_LOCK(sc);
5176 	switch (cmd) {
5177 	case SIOCSIFFLAGS:
5178 		if (IS_RUNNING(ifp)) {
5179 			/*
5180 			 * To avoid rescanning another access point,
5181 			 * do not call ath_init() here.  Instead,
5182 			 * only reflect promisc mode settings.
5183 			 */
5184 			ath_mode_init(sc);
5185 		} else if (ifp->if_flags & IFF_UP) {
5186 			/*
5187 			 * Beware of being called during attach/detach
5188 			 * to reset promiscuous mode.  In that case we
5189 			 * will still be marked UP but not RUNNING.
5190 			 * However trying to re-init the interface
5191 			 * is the wrong thing to do as we've already
5192 			 * torn down much of our state.  There's
5193 			 * probably a better way to deal with this.
5194 			 */
5195 			if (!sc->sc_invalid && ic->ic_bss != NULL)
5196 				ath_init(sc);	/* XXX lose error */
5197 		} else
5198 			ath_stop_locked(ifp);
5199 		break;
5200 	case SIOCADDMULTI:
5201 	case SIOCDELMULTI:
5202 		/*
5203 		 * The upper layer has already installed/removed
5204 		 * the multicast address(es), just recalculate the
5205 		 * multicast filter for the card.
5206 		 */
5207 		if (ifp->if_drv_flags & IFF_DRV_RUNNING)
5208 			ath_mode_init(sc);
5209 		break;
5210 	case SIOCGATHSTATS:
5211 		/* NB: embed these numbers to get a consistent view */
5212 		sc->sc_stats.ast_tx_packets = ifp->if_opackets;
5213 		sc->sc_stats.ast_rx_packets = ifp->if_ipackets;
5214 		sc->sc_stats.ast_rx_rssi = ieee80211_getrssi(ic);
5215 		sc->sc_stats.ast_rx_noise =
5216 			ath_hal_getchannoise(sc->sc_ah, &sc->sc_curchan);
5217 		sc->sc_stats.ast_tx_rate = sc->sc_hwmap[sc->sc_txrate].ieeerate;
5218 		ATH_UNLOCK(sc);
5219 		/*
5220 		 * NB: Drop the softc lock in case of a page fault;
5221 		 * we'll accept any potential inconsisentcy in the
5222 		 * statistics.  The alternative is to copy the data
5223 		 * to a local structure.
5224 		 */
5225 		return copyout(&sc->sc_stats,
5226 				ifr->ifr_data, sizeof (sc->sc_stats));
5227 #ifdef ATH_DIAGAPI
5228 	case SIOCGATHDIAG:
5229 		ATH_UNLOCK(sc);
5230 		error = ath_ioctl_diag(sc, (struct ath_diag *) ifr);
5231 		ATH_LOCK(sc);
5232 		break;
5233 #endif
5234 	default:
5235 		error = ieee80211_ioctl(ic, cmd, data);
5236 		if (error == ENETRESET) {
5237 			if (IS_RUNNING(ifp) &&
5238 			    ic->ic_roaming != IEEE80211_ROAMING_MANUAL)
5239 				ath_init(sc);	/* XXX lose error */
5240 			error = 0;
5241 		}
5242 		if (error == ERESTART)
5243 			error = IS_RUNNING(ifp) ? ath_reset(ifp) : 0;
5244 		break;
5245 	}
5246 	ATH_UNLOCK(sc);
5247 	return error;
5248 #undef IS_RUNNING
5249 }
5250 
5251 static int
5252 ath_sysctl_slottime(SYSCTL_HANDLER_ARGS)
5253 {
5254 	struct ath_softc *sc = arg1;
5255 	u_int slottime = ath_hal_getslottime(sc->sc_ah);
5256 	int error;
5257 
5258 	error = sysctl_handle_int(oidp, &slottime, 0, req);
5259 	if (error || !req->newptr)
5260 		return error;
5261 	return !ath_hal_setslottime(sc->sc_ah, slottime) ? EINVAL : 0;
5262 }
5263 
5264 static int
5265 ath_sysctl_acktimeout(SYSCTL_HANDLER_ARGS)
5266 {
5267 	struct ath_softc *sc = arg1;
5268 	u_int acktimeout = ath_hal_getacktimeout(sc->sc_ah);
5269 	int error;
5270 
5271 	error = sysctl_handle_int(oidp, &acktimeout, 0, req);
5272 	if (error || !req->newptr)
5273 		return error;
5274 	return !ath_hal_setacktimeout(sc->sc_ah, acktimeout) ? EINVAL : 0;
5275 }
5276 
5277 static int
5278 ath_sysctl_ctstimeout(SYSCTL_HANDLER_ARGS)
5279 {
5280 	struct ath_softc *sc = arg1;
5281 	u_int ctstimeout = ath_hal_getctstimeout(sc->sc_ah);
5282 	int error;
5283 
5284 	error = sysctl_handle_int(oidp, &ctstimeout, 0, req);
5285 	if (error || !req->newptr)
5286 		return error;
5287 	return !ath_hal_setctstimeout(sc->sc_ah, ctstimeout) ? EINVAL : 0;
5288 }
5289 
5290 static int
5291 ath_sysctl_softled(SYSCTL_HANDLER_ARGS)
5292 {
5293 	struct ath_softc *sc = arg1;
5294 	int softled = sc->sc_softled;
5295 	int error;
5296 
5297 	error = sysctl_handle_int(oidp, &softled, 0, req);
5298 	if (error || !req->newptr)
5299 		return error;
5300 	softled = (softled != 0);
5301 	if (softled != sc->sc_softled) {
5302 		if (softled) {
5303 			/* NB: handle any sc_ledpin change */
5304 			ath_hal_gpioCfgOutput(sc->sc_ah, sc->sc_ledpin);
5305 			ath_hal_gpioset(sc->sc_ah, sc->sc_ledpin,
5306 				!sc->sc_ledon);
5307 		}
5308 		sc->sc_softled = softled;
5309 	}
5310 	return 0;
5311 }
5312 
5313 static int
5314 ath_sysctl_rxantenna(SYSCTL_HANDLER_ARGS)
5315 {
5316 	struct ath_softc *sc = arg1;
5317 	u_int defantenna = ath_hal_getdefantenna(sc->sc_ah);
5318 	int error;
5319 
5320 	error = sysctl_handle_int(oidp, &defantenna, 0, req);
5321 	if (!error && req->newptr)
5322 		ath_hal_setdefantenna(sc->sc_ah, defantenna);
5323 	return error;
5324 }
5325 
5326 static int
5327 ath_sysctl_diversity(SYSCTL_HANDLER_ARGS)
5328 {
5329 	struct ath_softc *sc = arg1;
5330 	u_int diversity = ath_hal_getdiversity(sc->sc_ah);
5331 	int error;
5332 
5333 	error = sysctl_handle_int(oidp, &diversity, 0, req);
5334 	if (error || !req->newptr)
5335 		return error;
5336 	if (!ath_hal_setdiversity(sc->sc_ah, diversity))
5337 		return EINVAL;
5338 	sc->sc_diversity = diversity;
5339 	return 0;
5340 }
5341 
5342 static int
5343 ath_sysctl_diag(SYSCTL_HANDLER_ARGS)
5344 {
5345 	struct ath_softc *sc = arg1;
5346 	u_int32_t diag;
5347 	int error;
5348 
5349 	if (!ath_hal_getdiag(sc->sc_ah, &diag))
5350 		return EINVAL;
5351 	error = sysctl_handle_int(oidp, &diag, 0, req);
5352 	if (error || !req->newptr)
5353 		return error;
5354 	return !ath_hal_setdiag(sc->sc_ah, diag) ? EINVAL : 0;
5355 }
5356 
5357 static int
5358 ath_sysctl_tpscale(SYSCTL_HANDLER_ARGS)
5359 {
5360 	struct ath_softc *sc = arg1;
5361 	struct ifnet *ifp = sc->sc_ifp;
5362 	u_int32_t scale;
5363 	int error;
5364 
5365 	ath_hal_gettpscale(sc->sc_ah, &scale);
5366 	error = sysctl_handle_int(oidp, &scale, 0, req);
5367 	if (error || !req->newptr)
5368 		return error;
5369 	return !ath_hal_settpscale(sc->sc_ah, scale) ? EINVAL : ath_reset(ifp);
5370 }
5371 
5372 static int
5373 ath_sysctl_tpc(SYSCTL_HANDLER_ARGS)
5374 {
5375 	struct ath_softc *sc = arg1;
5376 	u_int tpc = ath_hal_gettpc(sc->sc_ah);
5377 	int error;
5378 
5379 	error = sysctl_handle_int(oidp, &tpc, 0, req);
5380 	if (error || !req->newptr)
5381 		return error;
5382 	return !ath_hal_settpc(sc->sc_ah, tpc) ? EINVAL : 0;
5383 }
5384 
5385 static int
5386 ath_sysctl_rfkill(SYSCTL_HANDLER_ARGS)
5387 {
5388 	struct ath_softc *sc = arg1;
5389 	struct ath_hal *ah = sc->sc_ah;
5390 	u_int rfkill = ath_hal_getrfkill(ah);
5391 	int error;
5392 
5393 	error = sysctl_handle_int(oidp, &rfkill, 0, req);
5394 	if (error || !req->newptr)
5395 		return error;
5396 	if (rfkill == ath_hal_getrfkill(ah))	/* unchanged */
5397 		return 0;
5398 	if (!ath_hal_setrfkill(ah, rfkill) || ath_reset(sc->sc_ifp) != 0)
5399 		return EINVAL;
5400 	else
5401 		return 0;
5402 }
5403 
5404 static int
5405 ath_sysctl_rfsilent(SYSCTL_HANDLER_ARGS)
5406 {
5407 	struct ath_softc *sc = arg1;
5408 	u_int rfsilent;
5409 	int error;
5410 
5411 	ath_hal_getrfsilent(sc->sc_ah, &rfsilent);
5412 	error = sysctl_handle_int(oidp, &rfsilent, 0, req);
5413 	if (error || !req->newptr)
5414 		return error;
5415 	if (!ath_hal_setrfsilent(sc->sc_ah, rfsilent))
5416 		return EINVAL;
5417 	sc->sc_rfsilentpin = rfsilent & 0x1c;
5418 	sc->sc_rfsilentpol = (rfsilent & 0x2) != 0;
5419 	return 0;
5420 }
5421 
5422 static int
5423 ath_sysctl_regdomain(SYSCTL_HANDLER_ARGS)
5424 {
5425 	struct ath_softc *sc = arg1;
5426 	u_int32_t rd;
5427 	int error;
5428 
5429 	if (!ath_hal_getregdomain(sc->sc_ah, &rd))
5430 		return EINVAL;
5431 	error = sysctl_handle_int(oidp, &rd, 0, req);
5432 	if (error || !req->newptr)
5433 		return error;
5434 	return !ath_hal_setregdomain(sc->sc_ah, rd) ? EINVAL : 0;
5435 }
5436 
5437 static int
5438 ath_sysctl_tpack(SYSCTL_HANDLER_ARGS)
5439 {
5440 	struct ath_softc *sc = arg1;
5441 	u_int32_t tpack;
5442 	int error;
5443 
5444 	ath_hal_gettpack(sc->sc_ah, &tpack);
5445 	error = sysctl_handle_int(oidp, &tpack, 0, req);
5446 	if (error || !req->newptr)
5447 		return error;
5448 	return !ath_hal_settpack(sc->sc_ah, tpack) ? EINVAL : 0;
5449 }
5450 
5451 static int
5452 ath_sysctl_tpcts(SYSCTL_HANDLER_ARGS)
5453 {
5454 	struct ath_softc *sc = arg1;
5455 	u_int32_t tpcts;
5456 	int error;
5457 
5458 	ath_hal_gettpcts(sc->sc_ah, &tpcts);
5459 	error = sysctl_handle_int(oidp, &tpcts, 0, req);
5460 	if (error || !req->newptr)
5461 		return error;
5462 	return !ath_hal_settpcts(sc->sc_ah, tpcts) ? EINVAL : 0;
5463 }
5464 
5465 static void
5466 ath_sysctlattach(struct ath_softc *sc)
5467 {
5468 	struct sysctl_ctx_list *ctx = device_get_sysctl_ctx(sc->sc_dev);
5469 	struct sysctl_oid *tree = device_get_sysctl_tree(sc->sc_dev);
5470 	struct ath_hal *ah = sc->sc_ah;
5471 
5472 	ath_hal_getcountrycode(sc->sc_ah, &sc->sc_countrycode);
5473 	SYSCTL_ADD_INT(ctx, SYSCTL_CHILDREN(tree), OID_AUTO,
5474 		"countrycode", CTLFLAG_RD, &sc->sc_countrycode, 0,
5475 		"EEPROM country code");
5476 	SYSCTL_ADD_PROC(ctx, SYSCTL_CHILDREN(tree), OID_AUTO,
5477 		"regdomain", CTLTYPE_INT | CTLFLAG_RW, sc, 0,
5478 		ath_sysctl_regdomain, "I", "EEPROM regdomain code");
5479 #ifdef	ATH_DEBUG
5480 	sc->sc_debug = ath_debug;
5481 	SYSCTL_ADD_INT(ctx, SYSCTL_CHILDREN(tree), OID_AUTO,
5482 		"debug", CTLFLAG_RW, &sc->sc_debug, 0,
5483 		"control debugging printfs");
5484 #endif
5485 	SYSCTL_ADD_PROC(ctx, SYSCTL_CHILDREN(tree), OID_AUTO,
5486 		"slottime", CTLTYPE_INT | CTLFLAG_RW, sc, 0,
5487 		ath_sysctl_slottime, "I", "802.11 slot time (us)");
5488 	SYSCTL_ADD_PROC(ctx, SYSCTL_CHILDREN(tree), OID_AUTO,
5489 		"acktimeout", CTLTYPE_INT | CTLFLAG_RW, sc, 0,
5490 		ath_sysctl_acktimeout, "I", "802.11 ACK timeout (us)");
5491 	SYSCTL_ADD_PROC(ctx, SYSCTL_CHILDREN(tree), OID_AUTO,
5492 		"ctstimeout", CTLTYPE_INT | CTLFLAG_RW, sc, 0,
5493 		ath_sysctl_ctstimeout, "I", "802.11 CTS timeout (us)");
5494 	SYSCTL_ADD_PROC(ctx, SYSCTL_CHILDREN(tree), OID_AUTO,
5495 		"softled", CTLTYPE_INT | CTLFLAG_RW, sc, 0,
5496 		ath_sysctl_softled, "I", "enable/disable software LED support");
5497 	SYSCTL_ADD_INT(ctx, SYSCTL_CHILDREN(tree), OID_AUTO,
5498 		"ledpin", CTLFLAG_RW, &sc->sc_ledpin, 0,
5499 		"GPIO pin connected to LED");
5500 	SYSCTL_ADD_INT(ctx, SYSCTL_CHILDREN(tree), OID_AUTO,
5501 		"ledon", CTLFLAG_RW, &sc->sc_ledon, 0,
5502 		"setting to turn LED on");
5503 	SYSCTL_ADD_INT(ctx, SYSCTL_CHILDREN(tree), OID_AUTO,
5504 		"ledidle", CTLFLAG_RW, &sc->sc_ledidle, 0,
5505 		"idle time for inactivity LED (ticks)");
5506 	SYSCTL_ADD_INT(ctx, SYSCTL_CHILDREN(tree), OID_AUTO,
5507 		"txantenna", CTLFLAG_RW, &sc->sc_txantenna, 0,
5508 		"tx antenna (0=auto)");
5509 	SYSCTL_ADD_PROC(ctx, SYSCTL_CHILDREN(tree), OID_AUTO,
5510 		"rxantenna", CTLTYPE_INT | CTLFLAG_RW, sc, 0,
5511 		ath_sysctl_rxantenna, "I", "default/rx antenna");
5512 	if (ath_hal_hasdiversity(ah))
5513 		SYSCTL_ADD_PROC(ctx, SYSCTL_CHILDREN(tree), OID_AUTO,
5514 			"diversity", CTLTYPE_INT | CTLFLAG_RW, sc, 0,
5515 			ath_sysctl_diversity, "I", "antenna diversity");
5516 	sc->sc_txintrperiod = ATH_TXINTR_PERIOD;
5517 	SYSCTL_ADD_INT(ctx, SYSCTL_CHILDREN(tree), OID_AUTO,
5518 		"txintrperiod", CTLFLAG_RW, &sc->sc_txintrperiod, 0,
5519 		"tx descriptor batching");
5520 	SYSCTL_ADD_PROC(ctx, SYSCTL_CHILDREN(tree), OID_AUTO,
5521 		"diag", CTLTYPE_INT | CTLFLAG_RW, sc, 0,
5522 		ath_sysctl_diag, "I", "h/w diagnostic control");
5523 	SYSCTL_ADD_PROC(ctx, SYSCTL_CHILDREN(tree), OID_AUTO,
5524 		"tpscale", CTLTYPE_INT | CTLFLAG_RW, sc, 0,
5525 		ath_sysctl_tpscale, "I", "tx power scaling");
5526 	if (ath_hal_hastpc(ah)) {
5527 		SYSCTL_ADD_PROC(ctx, SYSCTL_CHILDREN(tree), OID_AUTO,
5528 			"tpc", CTLTYPE_INT | CTLFLAG_RW, sc, 0,
5529 			ath_sysctl_tpc, "I", "enable/disable per-packet TPC");
5530 		SYSCTL_ADD_PROC(ctx, SYSCTL_CHILDREN(tree), OID_AUTO,
5531 			"tpack", CTLTYPE_INT | CTLFLAG_RW, sc, 0,
5532 			ath_sysctl_tpack, "I", "tx power for ack frames");
5533 		SYSCTL_ADD_PROC(ctx, SYSCTL_CHILDREN(tree), OID_AUTO,
5534 			"tpcts", CTLTYPE_INT | CTLFLAG_RW, sc, 0,
5535 			ath_sysctl_tpcts, "I", "tx power for cts frames");
5536 	}
5537 	if (ath_hal_hasrfsilent(ah)) {
5538 		SYSCTL_ADD_PROC(ctx, SYSCTL_CHILDREN(tree), OID_AUTO,
5539 			"rfsilent", CTLTYPE_INT | CTLFLAG_RW, sc, 0,
5540 			ath_sysctl_rfsilent, "I", "h/w RF silent config");
5541 		SYSCTL_ADD_PROC(ctx, SYSCTL_CHILDREN(tree), OID_AUTO,
5542 			"rfkill", CTLTYPE_INT | CTLFLAG_RW, sc, 0,
5543 			ath_sysctl_rfkill, "I", "enable/disable RF kill switch");
5544 	}
5545 	sc->sc_monpass = HAL_RXERR_DECRYPT | HAL_RXERR_MIC;
5546 	SYSCTL_ADD_INT(ctx, SYSCTL_CHILDREN(tree), OID_AUTO,
5547 		"monpass", CTLFLAG_RW, &sc->sc_monpass, 0,
5548 		"mask of error frames to pass when monitoring");
5549 }
5550 
5551 static void
5552 ath_bpfattach(struct ath_softc *sc)
5553 {
5554 	struct ifnet *ifp = sc->sc_ifp;
5555 
5556 	bpfattach2(ifp, DLT_IEEE802_11_RADIO,
5557 		sizeof(struct ieee80211_frame) + sizeof(sc->sc_tx_th),
5558 		&sc->sc_drvbpf);
5559 	/*
5560 	 * Initialize constant fields.
5561 	 * XXX make header lengths a multiple of 32-bits so subsequent
5562 	 *     headers are properly aligned; this is a kludge to keep
5563 	 *     certain applications happy.
5564 	 *
5565 	 * NB: the channel is setup each time we transition to the
5566 	 *     RUN state to avoid filling it in for each frame.
5567 	 */
5568 	sc->sc_tx_th_len = roundup(sizeof(sc->sc_tx_th), sizeof(u_int32_t));
5569 	sc->sc_tx_th.wt_ihdr.it_len = htole16(sc->sc_tx_th_len);
5570 	sc->sc_tx_th.wt_ihdr.it_present = htole32(ATH_TX_RADIOTAP_PRESENT);
5571 
5572 	sc->sc_rx_th_len = roundup(sizeof(sc->sc_rx_th), sizeof(u_int32_t));
5573 	sc->sc_rx_th.wr_ihdr.it_len = htole16(sc->sc_rx_th_len);
5574 	sc->sc_rx_th.wr_ihdr.it_present = htole32(ATH_RX_RADIOTAP_PRESENT);
5575 }
5576 
5577 static int
5578 ath_tx_raw_start(struct ath_softc *sc, struct ieee80211_node *ni,
5579 	struct ath_buf *bf, struct mbuf *m0,
5580 	const struct ieee80211_bpf_params *params)
5581 {
5582 	struct ieee80211com *ic = &sc->sc_ic;
5583 	struct ath_hal *ah = sc->sc_ah;
5584 	int error, ismcast, ismrr;
5585 	int hdrlen, pktlen, try0, txantenna;
5586 	u_int8_t rix, cix, txrate, ctsrate, rate1, rate2, rate3;
5587 	struct ath_txq *txq;
5588 	struct ieee80211_frame *wh;
5589 	u_int flags, ctsduration;
5590 	HAL_PKT_TYPE atype;
5591 	const HAL_RATE_TABLE *rt;
5592 	struct ath_desc *ds;
5593 	u_int pri;
5594 
5595 	wh = mtod(m0, struct ieee80211_frame *);
5596 	ismcast = IEEE80211_IS_MULTICAST(wh->i_addr1);
5597 	hdrlen = ieee80211_anyhdrsize(wh);
5598 	/*
5599 	 * Packet length must not include any
5600 	 * pad bytes; deduct them here.
5601 	 */
5602 	/* XXX honor IEEE80211_BPF_DATAPAD */
5603 	pktlen = m0->m_pkthdr.len - (hdrlen & 3) + IEEE80211_CRC_LEN;
5604 
5605 	error = ath_tx_dmasetup(sc, bf, m0);
5606 	if (error != 0)
5607 		return error;
5608 	m0 = bf->bf_m;				/* NB: may have changed */
5609 	wh = mtod(m0, struct ieee80211_frame *);
5610 	bf->bf_node = ni;			/* NB: held reference */
5611 
5612 	flags = HAL_TXDESC_CLRDMASK;		/* XXX needed for crypto errs */
5613 	flags |= HAL_TXDESC_INTREQ;		/* force interrupt */
5614 	if (params->ibp_flags & IEEE80211_BPF_RTS)
5615 		flags |= HAL_TXDESC_RTSENA;
5616 	else if (params->ibp_flags & IEEE80211_BPF_CTS)
5617 		flags |= HAL_TXDESC_CTSENA;
5618 	/* XXX leave ismcast to injector? */
5619 	if ((params->ibp_flags & IEEE80211_BPF_NOACK) || ismcast)
5620 		flags |= HAL_TXDESC_NOACK;
5621 
5622 	rt = sc->sc_currates;
5623 	KASSERT(rt != NULL, ("no rate table, mode %u", sc->sc_curmode));
5624 	rix = ath_tx_findrix(rt, params->ibp_rate0);
5625 	txrate = rt->info[rix].rateCode;
5626 	if (params->ibp_flags & IEEE80211_BPF_SHORTPRE)
5627 		txrate |= rt->info[rix].shortPreamble;
5628 	sc->sc_txrate = txrate;
5629 	try0 = params->ibp_try0;
5630 	ismrr = (params->ibp_try1 != 0);
5631 	txantenna = params->ibp_pri >> 2;
5632 	if (txantenna == 0)			/* XXX? */
5633 		txantenna = sc->sc_txantenna;
5634 	ctsduration = 0;
5635 	if (flags & (HAL_TXDESC_CTSENA | HAL_TXDESC_RTSENA)) {
5636 		cix = ath_tx_findrix(rt, params->ibp_ctsrate);
5637 		ctsrate = rt->info[cix].rateCode;
5638 		if (params->ibp_flags & IEEE80211_BPF_SHORTPRE) {
5639 			ctsrate |= rt->info[cix].shortPreamble;
5640 			if (flags & HAL_TXDESC_RTSENA)		/* SIFS + CTS */
5641 				ctsduration += rt->info[cix].spAckDuration;
5642 			ctsduration += ath_hal_computetxtime(ah,
5643 				rt, pktlen, rix, AH_TRUE);
5644 			if ((flags & HAL_TXDESC_NOACK) == 0)	/* SIFS + ACK */
5645 				ctsduration += rt->info[rix].spAckDuration;
5646 		} else {
5647 			if (flags & HAL_TXDESC_RTSENA)		/* SIFS + CTS */
5648 				ctsduration += rt->info[cix].lpAckDuration;
5649 			ctsduration += ath_hal_computetxtime(ah,
5650 				rt, pktlen, rix, AH_FALSE);
5651 			if ((flags & HAL_TXDESC_NOACK) == 0)	/* SIFS + ACK */
5652 				ctsduration += rt->info[rix].lpAckDuration;
5653 		}
5654 		ismrr = 0;			/* XXX */
5655 	} else
5656 		ctsrate = 0;
5657 	pri = params->ibp_pri & 3;
5658 	/*
5659 	 * NB: we mark all packets as type PSPOLL so the h/w won't
5660 	 * set the sequence number, duration, etc.
5661 	 */
5662 	atype = HAL_PKT_TYPE_PSPOLL;
5663 
5664 	if (IFF_DUMPPKTS(sc, ATH_DEBUG_XMIT))
5665 		ieee80211_dump_pkt(mtod(m0, caddr_t), m0->m_len,
5666 			sc->sc_hwmap[txrate].ieeerate, -1);
5667 
5668 	if (bpf_peers_present(ic->ic_rawbpf))
5669 		bpf_mtap(ic->ic_rawbpf, m0);
5670 	if (bpf_peers_present(sc->sc_drvbpf)) {
5671 		u_int64_t tsf = ath_hal_gettsf64(ah);
5672 
5673 		sc->sc_tx_th.wt_tsf = htole64(tsf);
5674 		sc->sc_tx_th.wt_flags = sc->sc_hwmap[txrate].txflags;
5675 		if (wh->i_fc[1] & IEEE80211_FC1_WEP)
5676 			sc->sc_tx_th.wt_flags |= IEEE80211_RADIOTAP_F_WEP;
5677 		sc->sc_tx_th.wt_rate = sc->sc_hwmap[txrate].ieeerate;
5678 		sc->sc_tx_th.wt_txpower = ni->ni_txpower;
5679 		sc->sc_tx_th.wt_antenna = sc->sc_txantenna;
5680 
5681 		bpf_mtap2(sc->sc_drvbpf,
5682 			&sc->sc_tx_th, sc->sc_tx_th_len, m0);
5683 	}
5684 
5685 	/*
5686 	 * Formulate first tx descriptor with tx controls.
5687 	 */
5688 	ds = bf->bf_desc;
5689 	/* XXX check return value? */
5690 	ath_hal_setuptxdesc(ah, ds
5691 		, pktlen		/* packet length */
5692 		, hdrlen		/* header length */
5693 		, atype			/* Atheros packet type */
5694 		, params->ibp_power	/* txpower */
5695 		, txrate, try0		/* series 0 rate/tries */
5696 		, HAL_TXKEYIX_INVALID	/* key cache index */
5697 		, txantenna		/* antenna mode */
5698 		, flags			/* flags */
5699 		, ctsrate		/* rts/cts rate */
5700 		, ctsduration		/* rts/cts duration */
5701 	);
5702 	bf->bf_flags = flags;
5703 
5704 	if (ismrr) {
5705 		rix = ath_tx_findrix(rt, params->ibp_rate1);
5706 		rate1 = rt->info[rix].rateCode;
5707 		if (params->ibp_flags & IEEE80211_BPF_SHORTPRE)
5708 			rate1 |= rt->info[rix].shortPreamble;
5709 		if (params->ibp_try2) {
5710 			rix = ath_tx_findrix(rt, params->ibp_rate2);
5711 			rate2 = rt->info[rix].rateCode;
5712 			if (params->ibp_flags & IEEE80211_BPF_SHORTPRE)
5713 				rate2 |= rt->info[rix].shortPreamble;
5714 		} else
5715 			rate2 = 0;
5716 		if (params->ibp_try3) {
5717 			rix = ath_tx_findrix(rt, params->ibp_rate3);
5718 			rate3 = rt->info[rix].rateCode;
5719 			if (params->ibp_flags & IEEE80211_BPF_SHORTPRE)
5720 				rate3 |= rt->info[rix].shortPreamble;
5721 		} else
5722 			rate3 = 0;
5723 		ath_hal_setupxtxdesc(ah, ds
5724 			, rate1, params->ibp_try1	/* series 1 */
5725 			, rate2, params->ibp_try2	/* series 2 */
5726 			, rate3, params->ibp_try3	/* series 3 */
5727 		);
5728 	}
5729 
5730 	/*
5731 	 * When servicing one or more stations in power-save mode
5732 	 * (or) if there is some mcast data waiting on the mcast
5733 	 * queue (to prevent out of order delivery) multicast
5734 	 * frames must be buffered until after the beacon.
5735 	 */
5736 	txq = sc->sc_ac2q[pri];
5737 	if (ismcast && (ic->ic_ps_sta || sc->sc_mcastq.axq_depth))
5738 		txq = &sc->sc_mcastq;
5739 	ath_tx_handoff(sc, txq, bf);
5740 	return 0;
5741 }
5742 
5743 static int
5744 ath_raw_xmit(struct ieee80211_node *ni, struct mbuf *m,
5745 	const struct ieee80211_bpf_params *params)
5746 {
5747 	struct ieee80211com *ic = ni->ni_ic;
5748 	struct ifnet *ifp = ic->ic_ifp;
5749 	struct ath_softc *sc = ifp->if_softc;
5750 	struct ath_buf *bf;
5751 
5752 	if ((ifp->if_drv_flags & IFF_DRV_RUNNING) == 0 || sc->sc_invalid) {
5753 		m_freem(m);
5754 		return ENETDOWN;
5755 	}
5756 	/*
5757 	 * Grab a TX buffer and associated resources.
5758 	 */
5759 	ATH_TXBUF_LOCK(sc);
5760 	bf = STAILQ_FIRST(&sc->sc_txbuf);
5761 	if (bf != NULL)
5762 		STAILQ_REMOVE_HEAD(&sc->sc_txbuf, bf_list);
5763 	ATH_TXBUF_UNLOCK(sc);
5764 	if (bf == NULL) {
5765 		DPRINTF(sc, ATH_DEBUG_XMIT, "%s: out of xmit buffers\n",
5766 			__func__);
5767 		sc->sc_stats.ast_tx_qstop++;
5768 		ifp->if_drv_flags |= IFF_DRV_OACTIVE;
5769 		m_freem(m);
5770 		return ENOBUFS;
5771 	}
5772 
5773 	ifp->if_opackets++;
5774 	sc->sc_stats.ast_tx_raw++;
5775 
5776 	if (params == NULL) {
5777 		/*
5778 		 * Legacy path; interpret frame contents to decide
5779 		 * precisely how to send the frame.
5780 		 */
5781 		if (ath_tx_start(sc, ni, bf, m))
5782 			goto bad;
5783 	} else {
5784 		/*
5785 		 * Caller supplied explicit parameters to use in
5786 		 * sending the frame.
5787 		 */
5788 		if (ath_tx_raw_start(sc, ni, bf, m, params))
5789 			goto bad;
5790 	}
5791 	sc->sc_tx_timer = 5;
5792 	ifp->if_timer = 1;
5793 
5794 	return 0;
5795 bad:
5796 	ifp->if_oerrors++;
5797 	ATH_TXBUF_LOCK(sc);
5798 	STAILQ_INSERT_TAIL(&sc->sc_txbuf, bf, bf_list);
5799 	ATH_TXBUF_UNLOCK(sc);
5800 	ieee80211_free_node(ni);
5801 	return EIO;		/* XXX */
5802 }
5803 
5804 /*
5805  * Announce various information on device/driver attach.
5806  */
5807 static void
5808 ath_announce(struct ath_softc *sc)
5809 {
5810 #define	HAL_MODE_DUALBAND	(HAL_MODE_11A|HAL_MODE_11B)
5811 	struct ifnet *ifp = sc->sc_ifp;
5812 	struct ath_hal *ah = sc->sc_ah;
5813 	u_int modes, cc;
5814 
5815 	if_printf(ifp, "mac %d.%d phy %d.%d",
5816 		ah->ah_macVersion, ah->ah_macRev,
5817 		ah->ah_phyRev >> 4, ah->ah_phyRev & 0xf);
5818 	/*
5819 	 * Print radio revision(s).  We check the wireless modes
5820 	 * to avoid falsely printing revs for inoperable parts.
5821 	 * Dual-band radio revs are returned in the 5Ghz rev number.
5822 	 */
5823 	ath_hal_getcountrycode(ah, &cc);
5824 	modes = ath_hal_getwirelessmodes(ah, cc);
5825 	if ((modes & HAL_MODE_DUALBAND) == HAL_MODE_DUALBAND) {
5826 		if (ah->ah_analog5GhzRev && ah->ah_analog2GhzRev)
5827 			printf(" 5ghz radio %d.%d 2ghz radio %d.%d",
5828 				ah->ah_analog5GhzRev >> 4,
5829 				ah->ah_analog5GhzRev & 0xf,
5830 				ah->ah_analog2GhzRev >> 4,
5831 				ah->ah_analog2GhzRev & 0xf);
5832 		else
5833 			printf(" radio %d.%d", ah->ah_analog5GhzRev >> 4,
5834 				ah->ah_analog5GhzRev & 0xf);
5835 	} else
5836 		printf(" radio %d.%d", ah->ah_analog5GhzRev >> 4,
5837 			ah->ah_analog5GhzRev & 0xf);
5838 	printf("\n");
5839 	if (bootverbose) {
5840 		int i;
5841 		for (i = 0; i <= WME_AC_VO; i++) {
5842 			struct ath_txq *txq = sc->sc_ac2q[i];
5843 			if_printf(ifp, "Use hw queue %u for %s traffic\n",
5844 				txq->axq_qnum, ieee80211_wme_acnames[i]);
5845 		}
5846 		if_printf(ifp, "Use hw queue %u for CAB traffic\n",
5847 			sc->sc_cabq->axq_qnum);
5848 		if_printf(ifp, "Use hw queue %u for beacons\n", sc->sc_bhalq);
5849 	}
5850 	if (ath_rxbuf != ATH_RXBUF)
5851 		if_printf(ifp, "using %u rx buffers\n", ath_rxbuf);
5852 	if (ath_txbuf != ATH_TXBUF)
5853 		if_printf(ifp, "using %u tx buffers\n", ath_txbuf);
5854 #undef HAL_MODE_DUALBAND
5855 }
5856