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