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