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