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