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