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