xref: /freebsd/sys/dev/ath/if_ath.c (revision d056fa046c6a91b90cd98165face0e42a33a5173)
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[4] & 1) {		/* NB: only at DTIM */
2141 		ATH_TXQ_LOCK(cabq);
2142 		ATH_TXQ_LOCK(&sc->sc_mcastq);
2143 		if (nmcastq) {
2144 			struct ath_buf *bfm;
2145 
2146 			/*
2147 			 * Move frames from the s/w mcast q to the h/w cab q.
2148 			 */
2149 			bfm = STAILQ_FIRST(&sc->sc_mcastq.axq_q);
2150 			if (cabq->axq_link != NULL) {
2151 				*cabq->axq_link = bfm->bf_daddr;
2152 			} else
2153 				ath_hal_puttxbuf(ah, cabq->axq_qnum,
2154 					bfm->bf_daddr);
2155 			ath_txqmove(cabq, &sc->sc_mcastq);
2156 
2157 			sc->sc_stats.ast_cabq_xmit += nmcastq;
2158 		}
2159 		/* NB: gated by beacon so safe to start here */
2160 		ath_hal_txstart(ah, cabq->axq_qnum);
2161 		ATH_TXQ_UNLOCK(cabq);
2162 		ATH_TXQ_UNLOCK(&sc->sc_mcastq);
2163 	}
2164 	ath_hal_puttxbuf(ah, sc->sc_bhalq, bf->bf_daddr);
2165 	ath_hal_txstart(ah, sc->sc_bhalq);
2166 	DPRINTF(sc, ATH_DEBUG_BEACON_PROC,
2167 		"%s: TXDP[%u] = %p (%p)\n", __func__,
2168 		sc->sc_bhalq, (caddr_t)bf->bf_daddr, bf->bf_desc);
2169 
2170 	sc->sc_stats.ast_be_xmit++;
2171 }
2172 
2173 /*
2174  * Reset the hardware after detecting beacons have stopped.
2175  */
2176 static void
2177 ath_bstuck_proc(void *arg, int pending)
2178 {
2179 	struct ath_softc *sc = arg;
2180 	struct ifnet *ifp = sc->sc_ifp;
2181 
2182 	if_printf(ifp, "stuck beacon; resetting (bmiss count %u)\n",
2183 		sc->sc_bmisscount);
2184 	ath_reset(ifp);
2185 }
2186 
2187 /*
2188  * Reclaim beacon resources.
2189  */
2190 static void
2191 ath_beacon_free(struct ath_softc *sc)
2192 {
2193 	struct ath_buf *bf;
2194 
2195 	STAILQ_FOREACH(bf, &sc->sc_bbuf, bf_list) {
2196 		if (bf->bf_m != NULL) {
2197 			bus_dmamap_unload(sc->sc_dmat, bf->bf_dmamap);
2198 			m_freem(bf->bf_m);
2199 			bf->bf_m = NULL;
2200 		}
2201 		if (bf->bf_node != NULL) {
2202 			ieee80211_free_node(bf->bf_node);
2203 			bf->bf_node = NULL;
2204 		}
2205 	}
2206 }
2207 
2208 /*
2209  * Configure the beacon and sleep timers.
2210  *
2211  * When operating as an AP this resets the TSF and sets
2212  * up the hardware to notify us when we need to issue beacons.
2213  *
2214  * When operating in station mode this sets up the beacon
2215  * timers according to the timestamp of the last received
2216  * beacon and the current TSF, configures PCF and DTIM
2217  * handling, programs the sleep registers so the hardware
2218  * will wakeup in time to receive beacons, and configures
2219  * the beacon miss handling so we'll receive a BMISS
2220  * interrupt when we stop seeing beacons from the AP
2221  * we've associated with.
2222  */
2223 static void
2224 ath_beacon_config(struct ath_softc *sc)
2225 {
2226 #define	TSF_TO_TU(_h,_l) \
2227 	((((u_int32_t)(_h)) << 22) | (((u_int32_t)(_l)) >> 10))
2228 #define	FUDGE	2
2229 	struct ath_hal *ah = sc->sc_ah;
2230 	struct ieee80211com *ic = &sc->sc_ic;
2231 	struct ieee80211_node *ni = ic->ic_bss;
2232 	u_int32_t nexttbtt, intval, tsftu;
2233 	u_int64_t tsf;
2234 
2235 	/* extract tstamp from last beacon and convert to TU */
2236 	nexttbtt = TSF_TO_TU(LE_READ_4(ni->ni_tstamp.data + 4),
2237 			     LE_READ_4(ni->ni_tstamp.data));
2238 	/* NB: the beacon interval is kept internally in TU's */
2239 	intval = ni->ni_intval & HAL_BEACON_PERIOD;
2240 	if (nexttbtt == 0)		/* e.g. for ap mode */
2241 		nexttbtt = intval;
2242 	else if (intval)		/* NB: can be 0 for monitor mode */
2243 		nexttbtt = roundup(nexttbtt, intval);
2244 	DPRINTF(sc, ATH_DEBUG_BEACON, "%s: nexttbtt %u intval %u (%u)\n",
2245 		__func__, nexttbtt, intval, ni->ni_intval);
2246 	if (ic->ic_opmode == IEEE80211_M_STA) {
2247 		HAL_BEACON_STATE bs;
2248 		int dtimperiod, dtimcount;
2249 		int cfpperiod, cfpcount;
2250 
2251 		/*
2252 		 * Setup dtim and cfp parameters according to
2253 		 * last beacon we received (which may be none).
2254 		 */
2255 		dtimperiod = ni->ni_dtim_period;
2256 		if (dtimperiod <= 0)		/* NB: 0 if not known */
2257 			dtimperiod = 1;
2258 		dtimcount = ni->ni_dtim_count;
2259 		if (dtimcount >= dtimperiod)	/* NB: sanity check */
2260 			dtimcount = 0;		/* XXX? */
2261 		cfpperiod = 1;			/* NB: no PCF support yet */
2262 		cfpcount = 0;
2263 		/*
2264 		 * Pull nexttbtt forward to reflect the current
2265 		 * TSF and calculate dtim+cfp state for the result.
2266 		 */
2267 		tsf = ath_hal_gettsf64(ah);
2268 		tsftu = TSF_TO_TU(tsf>>32, tsf) + FUDGE;
2269 		do {
2270 			nexttbtt += intval;
2271 			if (--dtimcount < 0) {
2272 				dtimcount = dtimperiod - 1;
2273 				if (--cfpcount < 0)
2274 					cfpcount = cfpperiod - 1;
2275 			}
2276 		} while (nexttbtt < tsftu);
2277 		memset(&bs, 0, sizeof(bs));
2278 		bs.bs_intval = intval;
2279 		bs.bs_nexttbtt = nexttbtt;
2280 		bs.bs_dtimperiod = dtimperiod*intval;
2281 		bs.bs_nextdtim = bs.bs_nexttbtt + dtimcount*intval;
2282 		bs.bs_cfpperiod = cfpperiod*bs.bs_dtimperiod;
2283 		bs.bs_cfpnext = bs.bs_nextdtim + cfpcount*bs.bs_dtimperiod;
2284 		bs.bs_cfpmaxduration = 0;
2285 #if 0
2286 		/*
2287 		 * The 802.11 layer records the offset to the DTIM
2288 		 * bitmap while receiving beacons; use it here to
2289 		 * enable h/w detection of our AID being marked in
2290 		 * the bitmap vector (to indicate frames for us are
2291 		 * pending at the AP).
2292 		 * XXX do DTIM handling in s/w to WAR old h/w bugs
2293 		 * XXX enable based on h/w rev for newer chips
2294 		 */
2295 		bs.bs_timoffset = ni->ni_timoff;
2296 #endif
2297 		/*
2298 		 * Calculate the number of consecutive beacons to miss
2299 		 * before taking a BMISS interrupt.  The configuration
2300 		 * is specified in ms, so we need to convert that to
2301 		 * TU's and then calculate based on the beacon interval.
2302 		 * Note that we clamp the result to at most 10 beacons.
2303 		 */
2304 		bs.bs_bmissthreshold = ic->ic_bmissthreshold;
2305 		if (bs.bs_bmissthreshold > 10)
2306 			bs.bs_bmissthreshold = 10;
2307 		else if (bs.bs_bmissthreshold <= 0)
2308 			bs.bs_bmissthreshold = 1;
2309 
2310 		/*
2311 		 * Calculate sleep duration.  The configuration is
2312 		 * given in ms.  We insure a multiple of the beacon
2313 		 * period is used.  Also, if the sleep duration is
2314 		 * greater than the DTIM period then it makes senses
2315 		 * to make it a multiple of that.
2316 		 *
2317 		 * XXX fixed at 100ms
2318 		 */
2319 		bs.bs_sleepduration =
2320 			roundup(IEEE80211_MS_TO_TU(100), bs.bs_intval);
2321 		if (bs.bs_sleepduration > bs.bs_dtimperiod)
2322 			bs.bs_sleepduration = roundup(bs.bs_sleepduration, bs.bs_dtimperiod);
2323 
2324 		DPRINTF(sc, ATH_DEBUG_BEACON,
2325 			"%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"
2326 			, __func__
2327 			, tsf, tsftu
2328 			, bs.bs_intval
2329 			, bs.bs_nexttbtt
2330 			, bs.bs_dtimperiod
2331 			, bs.bs_nextdtim
2332 			, bs.bs_bmissthreshold
2333 			, bs.bs_sleepduration
2334 			, bs.bs_cfpperiod
2335 			, bs.bs_cfpmaxduration
2336 			, bs.bs_cfpnext
2337 			, bs.bs_timoffset
2338 		);
2339 		ath_hal_intrset(ah, 0);
2340 		ath_hal_beacontimers(ah, &bs);
2341 		sc->sc_imask |= HAL_INT_BMISS;
2342 		ath_hal_intrset(ah, sc->sc_imask);
2343 	} else {
2344 		ath_hal_intrset(ah, 0);
2345 		if (nexttbtt == intval)
2346 			intval |= HAL_BEACON_RESET_TSF;
2347 		if (ic->ic_opmode == IEEE80211_M_IBSS) {
2348 			/*
2349 			 * In IBSS mode enable the beacon timers but only
2350 			 * enable SWBA interrupts if we need to manually
2351 			 * prepare beacon frames.  Otherwise we use a
2352 			 * self-linked tx descriptor and let the hardware
2353 			 * deal with things.
2354 			 */
2355 			intval |= HAL_BEACON_ENA;
2356 			if (!sc->sc_hasveol)
2357 				sc->sc_imask |= HAL_INT_SWBA;
2358 			if ((intval & HAL_BEACON_RESET_TSF) == 0) {
2359 				/*
2360 				 * Pull nexttbtt forward to reflect
2361 				 * the current TSF.
2362 				 */
2363 				tsf = ath_hal_gettsf64(ah);
2364 				tsftu = TSF_TO_TU(tsf>>32, tsf) + FUDGE;
2365 				do {
2366 					nexttbtt += intval;
2367 				} while (nexttbtt < tsftu);
2368 			}
2369 			ath_beaconq_config(sc);
2370 		} else if (ic->ic_opmode == IEEE80211_M_HOSTAP) {
2371 			/*
2372 			 * In AP mode we enable the beacon timers and
2373 			 * SWBA interrupts to prepare beacon frames.
2374 			 */
2375 			intval |= HAL_BEACON_ENA;
2376 			sc->sc_imask |= HAL_INT_SWBA;	/* beacon prepare */
2377 			ath_beaconq_config(sc);
2378 		}
2379 		ath_hal_beaconinit(ah, nexttbtt, intval);
2380 		sc->sc_bmisscount = 0;
2381 		ath_hal_intrset(ah, sc->sc_imask);
2382 		/*
2383 		 * When using a self-linked beacon descriptor in
2384 		 * ibss mode load it once here.
2385 		 */
2386 		if (ic->ic_opmode == IEEE80211_M_IBSS && sc->sc_hasveol)
2387 			ath_beacon_proc(sc, 0);
2388 	}
2389 	sc->sc_syncbeacon = 0;
2390 #undef FUDGE
2391 #undef TSF_TO_TU
2392 }
2393 
2394 static void
2395 ath_load_cb(void *arg, bus_dma_segment_t *segs, int nsegs, int error)
2396 {
2397 	bus_addr_t *paddr = (bus_addr_t*) arg;
2398 	KASSERT(error == 0, ("error %u on bus_dma callback", error));
2399 	*paddr = segs->ds_addr;
2400 }
2401 
2402 static int
2403 ath_descdma_setup(struct ath_softc *sc,
2404 	struct ath_descdma *dd, ath_bufhead *head,
2405 	const char *name, int nbuf, int ndesc)
2406 {
2407 #define	DS2PHYS(_dd, _ds) \
2408 	((_dd)->dd_desc_paddr + ((caddr_t)(_ds) - (caddr_t)(_dd)->dd_desc))
2409 	struct ifnet *ifp = sc->sc_ifp;
2410 	struct ath_desc *ds;
2411 	struct ath_buf *bf;
2412 	int i, bsize, error;
2413 
2414 	DPRINTF(sc, ATH_DEBUG_RESET, "%s: %s DMA: %u buffers %u desc/buf\n",
2415 	    __func__, name, nbuf, ndesc);
2416 
2417 	dd->dd_name = name;
2418 	dd->dd_desc_len = sizeof(struct ath_desc) * nbuf * ndesc;
2419 
2420 	/*
2421 	 * Setup DMA descriptor area.
2422 	 */
2423 	error = bus_dma_tag_create(NULL,	/* parent */
2424 		       PAGE_SIZE, 0,		/* alignment, bounds */
2425 		       BUS_SPACE_MAXADDR_32BIT,	/* lowaddr */
2426 		       BUS_SPACE_MAXADDR,	/* highaddr */
2427 		       NULL, NULL,		/* filter, filterarg */
2428 		       dd->dd_desc_len,		/* maxsize */
2429 		       1,			/* nsegments */
2430 		       dd->dd_desc_len,		/* maxsegsize */
2431 		       BUS_DMA_ALLOCNOW,	/* flags */
2432 		       NULL,			/* lockfunc */
2433 		       NULL,			/* lockarg */
2434 		       &dd->dd_dmat);
2435 	if (error != 0) {
2436 		if_printf(ifp, "cannot allocate %s DMA tag\n", dd->dd_name);
2437 		return error;
2438 	}
2439 
2440 	/* allocate descriptors */
2441 	error = bus_dmamap_create(dd->dd_dmat, BUS_DMA_NOWAIT, &dd->dd_dmamap);
2442 	if (error != 0) {
2443 		if_printf(ifp, "unable to create dmamap for %s descriptors, "
2444 			"error %u\n", dd->dd_name, error);
2445 		goto fail0;
2446 	}
2447 
2448 	error = bus_dmamem_alloc(dd->dd_dmat, (void**) &dd->dd_desc,
2449 				 BUS_DMA_NOWAIT, &dd->dd_dmamap);
2450 	if (error != 0) {
2451 		if_printf(ifp, "unable to alloc memory for %u %s descriptors, "
2452 			"error %u\n", nbuf * ndesc, dd->dd_name, error);
2453 		goto fail1;
2454 	}
2455 
2456 	error = bus_dmamap_load(dd->dd_dmat, dd->dd_dmamap,
2457 				dd->dd_desc, dd->dd_desc_len,
2458 				ath_load_cb, &dd->dd_desc_paddr,
2459 				BUS_DMA_NOWAIT);
2460 	if (error != 0) {
2461 		if_printf(ifp, "unable to map %s descriptors, error %u\n",
2462 			dd->dd_name, error);
2463 		goto fail2;
2464 	}
2465 
2466 	ds = dd->dd_desc;
2467 	DPRINTF(sc, ATH_DEBUG_RESET, "%s: %s DMA map: %p (%lu) -> %p (%lu)\n",
2468 	    __func__, dd->dd_name, ds, (u_long) dd->dd_desc_len,
2469 	    (caddr_t) dd->dd_desc_paddr, /*XXX*/ (u_long) dd->dd_desc_len);
2470 
2471 	/* allocate rx buffers */
2472 	bsize = sizeof(struct ath_buf) * nbuf;
2473 	bf = malloc(bsize, M_ATHDEV, M_NOWAIT | M_ZERO);
2474 	if (bf == NULL) {
2475 		if_printf(ifp, "malloc of %s buffers failed, size %u\n",
2476 			dd->dd_name, bsize);
2477 		goto fail3;
2478 	}
2479 	dd->dd_bufptr = bf;
2480 
2481 	STAILQ_INIT(head);
2482 	for (i = 0; i < nbuf; i++, bf++, ds += ndesc) {
2483 		bf->bf_desc = ds;
2484 		bf->bf_daddr = DS2PHYS(dd, ds);
2485 		error = bus_dmamap_create(sc->sc_dmat, BUS_DMA_NOWAIT,
2486 				&bf->bf_dmamap);
2487 		if (error != 0) {
2488 			if_printf(ifp, "unable to create dmamap for %s "
2489 				"buffer %u, error %u\n", dd->dd_name, i, error);
2490 			ath_descdma_cleanup(sc, dd, head);
2491 			return error;
2492 		}
2493 		STAILQ_INSERT_TAIL(head, bf, bf_list);
2494 	}
2495 	return 0;
2496 fail3:
2497 	bus_dmamap_unload(dd->dd_dmat, dd->dd_dmamap);
2498 fail2:
2499 	bus_dmamem_free(dd->dd_dmat, dd->dd_desc, dd->dd_dmamap);
2500 fail1:
2501 	bus_dmamap_destroy(dd->dd_dmat, dd->dd_dmamap);
2502 fail0:
2503 	bus_dma_tag_destroy(dd->dd_dmat);
2504 	memset(dd, 0, sizeof(*dd));
2505 	return error;
2506 #undef DS2PHYS
2507 }
2508 
2509 static void
2510 ath_descdma_cleanup(struct ath_softc *sc,
2511 	struct ath_descdma *dd, ath_bufhead *head)
2512 {
2513 	struct ath_buf *bf;
2514 	struct ieee80211_node *ni;
2515 
2516 	bus_dmamap_unload(dd->dd_dmat, dd->dd_dmamap);
2517 	bus_dmamem_free(dd->dd_dmat, dd->dd_desc, dd->dd_dmamap);
2518 	bus_dmamap_destroy(dd->dd_dmat, dd->dd_dmamap);
2519 	bus_dma_tag_destroy(dd->dd_dmat);
2520 
2521 	STAILQ_FOREACH(bf, head, bf_list) {
2522 		if (bf->bf_m) {
2523 			m_freem(bf->bf_m);
2524 			bf->bf_m = NULL;
2525 		}
2526 		if (bf->bf_dmamap != NULL) {
2527 			bus_dmamap_destroy(sc->sc_dmat, bf->bf_dmamap);
2528 			bf->bf_dmamap = NULL;
2529 		}
2530 		ni = bf->bf_node;
2531 		bf->bf_node = NULL;
2532 		if (ni != NULL) {
2533 			/*
2534 			 * Reclaim node reference.
2535 			 */
2536 			ieee80211_free_node(ni);
2537 		}
2538 	}
2539 
2540 	STAILQ_INIT(head);
2541 	free(dd->dd_bufptr, M_ATHDEV);
2542 	memset(dd, 0, sizeof(*dd));
2543 }
2544 
2545 static int
2546 ath_desc_alloc(struct ath_softc *sc)
2547 {
2548 	int error;
2549 
2550 	error = ath_descdma_setup(sc, &sc->sc_rxdma, &sc->sc_rxbuf,
2551 			"rx", ath_rxbuf, 1);
2552 	if (error != 0)
2553 		return error;
2554 
2555 	error = ath_descdma_setup(sc, &sc->sc_txdma, &sc->sc_txbuf,
2556 			"tx", ath_txbuf, ATH_TXDESC);
2557 	if (error != 0) {
2558 		ath_descdma_cleanup(sc, &sc->sc_rxdma, &sc->sc_rxbuf);
2559 		return error;
2560 	}
2561 
2562 	error = ath_descdma_setup(sc, &sc->sc_bdma, &sc->sc_bbuf,
2563 			"beacon", 1, 1);
2564 	if (error != 0) {
2565 		ath_descdma_cleanup(sc, &sc->sc_txdma, &sc->sc_txbuf);
2566 		ath_descdma_cleanup(sc, &sc->sc_rxdma, &sc->sc_rxbuf);
2567 		return error;
2568 	}
2569 	return 0;
2570 }
2571 
2572 static void
2573 ath_desc_free(struct ath_softc *sc)
2574 {
2575 
2576 	if (sc->sc_bdma.dd_desc_len != 0)
2577 		ath_descdma_cleanup(sc, &sc->sc_bdma, &sc->sc_bbuf);
2578 	if (sc->sc_txdma.dd_desc_len != 0)
2579 		ath_descdma_cleanup(sc, &sc->sc_txdma, &sc->sc_txbuf);
2580 	if (sc->sc_rxdma.dd_desc_len != 0)
2581 		ath_descdma_cleanup(sc, &sc->sc_rxdma, &sc->sc_rxbuf);
2582 }
2583 
2584 static struct ieee80211_node *
2585 ath_node_alloc(struct ieee80211_node_table *nt)
2586 {
2587 	struct ieee80211com *ic = nt->nt_ic;
2588 	struct ath_softc *sc = ic->ic_ifp->if_softc;
2589 	const size_t space = sizeof(struct ath_node) + sc->sc_rc->arc_space;
2590 	struct ath_node *an;
2591 
2592 	an = malloc(space, M_80211_NODE, M_NOWAIT|M_ZERO);
2593 	if (an == NULL) {
2594 		/* XXX stat+msg */
2595 		return NULL;
2596 	}
2597 	an->an_avgrssi = ATH_RSSI_DUMMY_MARKER;
2598 	ath_rate_node_init(sc, an);
2599 
2600 	DPRINTF(sc, ATH_DEBUG_NODE, "%s: an %p\n", __func__, an);
2601 	return &an->an_node;
2602 }
2603 
2604 static void
2605 ath_node_free(struct ieee80211_node *ni)
2606 {
2607 	struct ieee80211com *ic = ni->ni_ic;
2608         struct ath_softc *sc = ic->ic_ifp->if_softc;
2609 
2610 	DPRINTF(sc, ATH_DEBUG_NODE, "%s: ni %p\n", __func__, ni);
2611 
2612 	ath_rate_node_cleanup(sc, ATH_NODE(ni));
2613 	sc->sc_node_free(ni);
2614 }
2615 
2616 static u_int8_t
2617 ath_node_getrssi(const struct ieee80211_node *ni)
2618 {
2619 #define	HAL_EP_RND(x, mul) \
2620 	((((x)%(mul)) >= ((mul)/2)) ? ((x) + ((mul) - 1)) / (mul) : (x)/(mul))
2621 	u_int32_t avgrssi = ATH_NODE_CONST(ni)->an_avgrssi;
2622 	int32_t rssi;
2623 
2624 	/*
2625 	 * When only one frame is received there will be no state in
2626 	 * avgrssi so fallback on the value recorded by the 802.11 layer.
2627 	 */
2628 	if (avgrssi != ATH_RSSI_DUMMY_MARKER)
2629 		rssi = HAL_EP_RND(avgrssi, HAL_RSSI_EP_MULTIPLIER);
2630 	else
2631 		rssi = ni->ni_rssi;
2632 	return rssi < 0 ? 0 : rssi > 127 ? 127 : rssi;
2633 #undef HAL_EP_RND
2634 }
2635 
2636 static int
2637 ath_rxbuf_init(struct ath_softc *sc, struct ath_buf *bf)
2638 {
2639 	struct ath_hal *ah = sc->sc_ah;
2640 	int error;
2641 	struct mbuf *m;
2642 	struct ath_desc *ds;
2643 
2644 	m = bf->bf_m;
2645 	if (m == NULL) {
2646 		/*
2647 		 * NB: by assigning a page to the rx dma buffer we
2648 		 * implicitly satisfy the Atheros requirement that
2649 		 * this buffer be cache-line-aligned and sized to be
2650 		 * multiple of the cache line size.  Not doing this
2651 		 * causes weird stuff to happen (for the 5210 at least).
2652 		 */
2653 		m = m_getcl(M_DONTWAIT, MT_DATA, M_PKTHDR);
2654 		if (m == NULL) {
2655 			DPRINTF(sc, ATH_DEBUG_ANY,
2656 				"%s: no mbuf/cluster\n", __func__);
2657 			sc->sc_stats.ast_rx_nombuf++;
2658 			return ENOMEM;
2659 		}
2660 		m->m_pkthdr.len = m->m_len = m->m_ext.ext_size;
2661 
2662 		error = bus_dmamap_load_mbuf_sg(sc->sc_dmat,
2663 					     bf->bf_dmamap, m,
2664 					     bf->bf_segs, &bf->bf_nseg,
2665 					     BUS_DMA_NOWAIT);
2666 		if (error != 0) {
2667 			DPRINTF(sc, ATH_DEBUG_ANY,
2668 			    "%s: bus_dmamap_load_mbuf_sg failed; error %d\n",
2669 			    __func__, error);
2670 			sc->sc_stats.ast_rx_busdma++;
2671 			m_freem(m);
2672 			return error;
2673 		}
2674 		KASSERT(bf->bf_nseg == 1,
2675 			("multi-segment packet; nseg %u", bf->bf_nseg));
2676 		bf->bf_m = m;
2677 	}
2678 	bus_dmamap_sync(sc->sc_dmat, bf->bf_dmamap, BUS_DMASYNC_PREREAD);
2679 
2680 	/*
2681 	 * Setup descriptors.  For receive we always terminate
2682 	 * the descriptor list with a self-linked entry so we'll
2683 	 * not get overrun under high load (as can happen with a
2684 	 * 5212 when ANI processing enables PHY error frames).
2685 	 *
2686 	 * To insure the last descriptor is self-linked we create
2687 	 * each descriptor as self-linked and add it to the end.  As
2688 	 * each additional descriptor is added the previous self-linked
2689 	 * entry is ``fixed'' naturally.  This should be safe even
2690 	 * if DMA is happening.  When processing RX interrupts we
2691 	 * never remove/process the last, self-linked, entry on the
2692 	 * descriptor list.  This insures the hardware always has
2693 	 * someplace to write a new frame.
2694 	 */
2695 	ds = bf->bf_desc;
2696 	ds->ds_link = bf->bf_daddr;	/* link to self */
2697 	ds->ds_data = bf->bf_segs[0].ds_addr;
2698 	ds->ds_vdata = mtod(m, void *);	/* for radar */
2699 	ath_hal_setuprxdesc(ah, ds
2700 		, m->m_len		/* buffer size */
2701 		, 0
2702 	);
2703 
2704 	if (sc->sc_rxlink != NULL)
2705 		*sc->sc_rxlink = bf->bf_daddr;
2706 	sc->sc_rxlink = &ds->ds_link;
2707 	return 0;
2708 }
2709 
2710 /*
2711  * Extend 15-bit time stamp from rx descriptor to
2712  * a full 64-bit TSF using the specified TSF.
2713  */
2714 static __inline u_int64_t
2715 ath_extend_tsf(u_int32_t rstamp, u_int64_t tsf)
2716 {
2717 	if ((tsf & 0x7fff) < rstamp)
2718 		tsf -= 0x8000;
2719 	return ((tsf &~ 0x7fff) | rstamp);
2720 }
2721 
2722 /*
2723  * Intercept management frames to collect beacon rssi data
2724  * and to do ibss merges.
2725  */
2726 static void
2727 ath_recv_mgmt(struct ieee80211com *ic, struct mbuf *m,
2728 	struct ieee80211_node *ni,
2729 	int subtype, int rssi, u_int32_t rstamp)
2730 {
2731 	struct ath_softc *sc = ic->ic_ifp->if_softc;
2732 
2733 	/*
2734 	 * Call up first so subsequent work can use information
2735 	 * potentially stored in the node (e.g. for ibss merge).
2736 	 */
2737 	sc->sc_recv_mgmt(ic, m, ni, subtype, rssi, rstamp);
2738 	switch (subtype) {
2739 	case IEEE80211_FC0_SUBTYPE_BEACON:
2740 		/* update rssi statistics for use by the hal */
2741 		ATH_RSSI_LPF(sc->sc_halstats.ns_avgbrssi, rssi);
2742 		if (sc->sc_syncbeacon &&
2743 		    ni == ic->ic_bss && ic->ic_state == IEEE80211_S_RUN) {
2744 			/*
2745 			 * Resync beacon timers using the tsf of the beacon
2746 			 * frame we just received.
2747 			 */
2748 			ath_beacon_config(sc);
2749 		}
2750 		/* fall thru... */
2751 	case IEEE80211_FC0_SUBTYPE_PROBE_RESP:
2752 		if (ic->ic_opmode == IEEE80211_M_IBSS &&
2753 		    ic->ic_state == IEEE80211_S_RUN) {
2754 			u_int64_t tsf = ath_extend_tsf(rstamp,
2755 				ath_hal_gettsf64(sc->sc_ah));
2756 			/*
2757 			 * Handle ibss merge as needed; check the tsf on the
2758 			 * frame before attempting the merge.  The 802.11 spec
2759 			 * says the station should change it's bssid to match
2760 			 * the oldest station with the same ssid, where oldest
2761 			 * is determined by the tsf.  Note that hardware
2762 			 * reconfiguration happens through callback to
2763 			 * ath_newstate as the state machine will go from
2764 			 * RUN -> RUN when this happens.
2765 			 */
2766 			if (le64toh(ni->ni_tstamp.tsf) >= tsf) {
2767 				DPRINTF(sc, ATH_DEBUG_STATE,
2768 				    "ibss merge, rstamp %u tsf %ju "
2769 				    "tstamp %ju\n", rstamp, (uintmax_t)tsf,
2770 				    (uintmax_t)ni->ni_tstamp.tsf);
2771 				(void) ieee80211_ibss_merge(ni);
2772 			}
2773 		}
2774 		break;
2775 	}
2776 }
2777 
2778 /*
2779  * Set the default antenna.
2780  */
2781 static void
2782 ath_setdefantenna(struct ath_softc *sc, u_int antenna)
2783 {
2784 	struct ath_hal *ah = sc->sc_ah;
2785 
2786 	/* XXX block beacon interrupts */
2787 	ath_hal_setdefantenna(ah, antenna);
2788 	if (sc->sc_defant != antenna)
2789 		sc->sc_stats.ast_ant_defswitch++;
2790 	sc->sc_defant = antenna;
2791 	sc->sc_rxotherant = 0;
2792 }
2793 
2794 static int
2795 ath_rx_tap(struct ath_softc *sc, struct mbuf *m,
2796 	const struct ath_desc *ds, u_int64_t tsf, int16_t nf)
2797 {
2798 	u_int8_t rix;
2799 
2800 	KASSERT(sc->sc_drvbpf != NULL, ("no tap"));
2801 
2802 	/*
2803 	 * Discard anything shorter than an ack or cts.
2804 	 */
2805 	if (m->m_pkthdr.len < IEEE80211_ACK_LEN) {
2806 		DPRINTF(sc, ATH_DEBUG_RECV, "%s: runt packet %d\n",
2807 			__func__, m->m_pkthdr.len);
2808 		sc->sc_stats.ast_rx_tooshort++;
2809 		return 0;
2810 	}
2811 	sc->sc_rx_th.wr_tsf = htole64(
2812 		ath_extend_tsf(ds->ds_rxstat.rs_tstamp, tsf));
2813 	rix = ds->ds_rxstat.rs_rate;
2814 	sc->sc_rx_th.wr_flags = sc->sc_hwmap[rix].rxflags;
2815 	if (ds->ds_rxstat.rs_status & HAL_RXERR_CRC)
2816 		sc->sc_rx_th.wr_flags |= IEEE80211_RADIOTAP_F_BADFCS;
2817 	/* XXX propagate other error flags from descriptor */
2818 	sc->sc_rx_th.wr_rate = sc->sc_hwmap[rix].ieeerate;
2819 	sc->sc_rx_th.wr_antsignal = ds->ds_rxstat.rs_rssi + nf;
2820 	sc->sc_rx_th.wr_antnoise = nf;
2821 	sc->sc_rx_th.wr_antenna = ds->ds_rxstat.rs_antenna;
2822 
2823 	bpf_mtap2(sc->sc_drvbpf, &sc->sc_rx_th, sc->sc_rx_th_len, m);
2824 
2825 	return 1;
2826 }
2827 
2828 static void
2829 ath_rx_proc(void *arg, int npending)
2830 {
2831 #define	PA2DESC(_sc, _pa) \
2832 	((struct ath_desc *)((caddr_t)(_sc)->sc_rxdma.dd_desc + \
2833 		((_pa) - (_sc)->sc_rxdma.dd_desc_paddr)))
2834 	struct ath_softc *sc = arg;
2835 	struct ath_buf *bf;
2836 	struct ieee80211com *ic = &sc->sc_ic;
2837 	struct ifnet *ifp = sc->sc_ifp;
2838 	struct ath_hal *ah = sc->sc_ah;
2839 	struct ath_desc *ds;
2840 	struct mbuf *m;
2841 	struct ieee80211_node *ni;
2842 	struct ath_node *an;
2843 	int len, type, ngood;
2844 	u_int phyerr;
2845 	HAL_STATUS status;
2846 	int16_t nf;
2847 	u_int64_t tsf;
2848 
2849 	NET_LOCK_GIANT();		/* XXX */
2850 
2851 	DPRINTF(sc, ATH_DEBUG_RX_PROC, "%s: pending %u\n", __func__, npending);
2852 	ngood = 0;
2853 	nf = ath_hal_getchannoise(ah, &sc->sc_curchan);
2854 	tsf = ath_hal_gettsf64(ah);
2855 	do {
2856 		bf = STAILQ_FIRST(&sc->sc_rxbuf);
2857 		if (bf == NULL) {		/* NB: shouldn't happen */
2858 			if_printf(ifp, "%s: no buffer!\n", __func__);
2859 			break;
2860 		}
2861 		m = bf->bf_m;
2862 		if (m == NULL) {		/* NB: shouldn't happen */
2863 			/*
2864 			 * If mbuf allocation failed previously there
2865 			 * will be no mbuf; try again to re-populate it.
2866 			 */
2867 			/* XXX make debug msg */
2868 			if_printf(ifp, "%s: no mbuf!\n", __func__);
2869 			STAILQ_REMOVE_HEAD(&sc->sc_rxbuf, bf_list);
2870 			goto rx_next;
2871 		}
2872 		ds = bf->bf_desc;
2873 		if (ds->ds_link == bf->bf_daddr) {
2874 			/* NB: never process the self-linked entry at the end */
2875 			break;
2876 		}
2877 		/* XXX sync descriptor memory */
2878 		/*
2879 		 * Must provide the virtual address of the current
2880 		 * descriptor, the physical address, and the virtual
2881 		 * address of the next descriptor in the h/w chain.
2882 		 * This allows the HAL to look ahead to see if the
2883 		 * hardware is done with a descriptor by checking the
2884 		 * done bit in the following descriptor and the address
2885 		 * of the current descriptor the DMA engine is working
2886 		 * on.  All this is necessary because of our use of
2887 		 * a self-linked list to avoid rx overruns.
2888 		 */
2889 		status = ath_hal_rxprocdesc(ah, ds,
2890 				bf->bf_daddr, PA2DESC(sc, ds->ds_link));
2891 #ifdef ATH_DEBUG
2892 		if (sc->sc_debug & ATH_DEBUG_RECV_DESC)
2893 			ath_printrxbuf(bf, 0, status == HAL_OK);
2894 #endif
2895 		if (status == HAL_EINPROGRESS)
2896 			break;
2897 		STAILQ_REMOVE_HEAD(&sc->sc_rxbuf, bf_list);
2898 		if (ds->ds_rxstat.rs_more) {
2899 			/*
2900 			 * Frame spans multiple descriptors; this
2901 			 * cannot happen yet as we don't support
2902 			 * jumbograms.  If not in monitor mode,
2903 			 * discard the frame.
2904 			 */
2905 			if (ic->ic_opmode != IEEE80211_M_MONITOR) {
2906 				sc->sc_stats.ast_rx_toobig++;
2907 				goto rx_next;
2908 			}
2909 			/* fall thru for monitor mode handling... */
2910 		} else if (ds->ds_rxstat.rs_status != 0) {
2911 			if (ds->ds_rxstat.rs_status & HAL_RXERR_CRC)
2912 				sc->sc_stats.ast_rx_crcerr++;
2913 			if (ds->ds_rxstat.rs_status & HAL_RXERR_FIFO)
2914 				sc->sc_stats.ast_rx_fifoerr++;
2915 			if (ds->ds_rxstat.rs_status & HAL_RXERR_PHY) {
2916 				sc->sc_stats.ast_rx_phyerr++;
2917 				phyerr = ds->ds_rxstat.rs_phyerr & 0x1f;
2918 				sc->sc_stats.ast_rx_phy[phyerr]++;
2919 				goto rx_next;
2920 			}
2921 			if (ds->ds_rxstat.rs_status & HAL_RXERR_DECRYPT) {
2922 				/*
2923 				 * Decrypt error.  If the error occurred
2924 				 * because there was no hardware key, then
2925 				 * let the frame through so the upper layers
2926 				 * can process it.  This is necessary for 5210
2927 				 * parts which have no way to setup a ``clear''
2928 				 * key cache entry.
2929 				 *
2930 				 * XXX do key cache faulting
2931 				 */
2932 				if (ds->ds_rxstat.rs_keyix == HAL_RXKEYIX_INVALID)
2933 					goto rx_accept;
2934 				sc->sc_stats.ast_rx_badcrypt++;
2935 			}
2936 			if (ds->ds_rxstat.rs_status & HAL_RXERR_MIC) {
2937 				sc->sc_stats.ast_rx_badmic++;
2938 				/*
2939 				 * Do minimal work required to hand off
2940 				 * the 802.11 header for notifcation.
2941 				 */
2942 				/* XXX frag's and qos frames */
2943 				len = ds->ds_rxstat.rs_datalen;
2944 				if (len >= sizeof (struct ieee80211_frame)) {
2945 					bus_dmamap_sync(sc->sc_dmat,
2946 					    bf->bf_dmamap,
2947 					    BUS_DMASYNC_POSTREAD);
2948 					ieee80211_notify_michael_failure(ic,
2949 					    mtod(m, struct ieee80211_frame *),
2950 					    sc->sc_splitmic ?
2951 					        ds->ds_rxstat.rs_keyix-32 :
2952 					        ds->ds_rxstat.rs_keyix
2953 					);
2954 				}
2955 			}
2956 			ifp->if_ierrors++;
2957 			/*
2958 			 * When a tap is present pass error frames
2959 			 * that have been requested.  By default we
2960 			 * pass decrypt+mic errors but others may be
2961 			 * interesting (e.g. crc).
2962 			 */
2963 			if (bpf_peers_present(sc->sc_drvbpf) &&
2964 			    (ds->ds_rxstat.rs_status & sc->sc_monpass)) {
2965 				bus_dmamap_sync(sc->sc_dmat, bf->bf_dmamap,
2966 				    BUS_DMASYNC_POSTREAD);
2967 				/* NB: bpf needs the mbuf length setup */
2968 				len = ds->ds_rxstat.rs_datalen;
2969 				m->m_pkthdr.len = m->m_len = len;
2970 				(void) ath_rx_tap(sc, m, ds, tsf, nf);
2971 			}
2972 			/* XXX pass MIC errors up for s/w reclaculation */
2973 			goto rx_next;
2974 		}
2975 rx_accept:
2976 		/*
2977 		 * Sync and unmap the frame.  At this point we're
2978 		 * committed to passing the mbuf somewhere so clear
2979 		 * bf_m; this means a new mbuf must be allocated
2980 		 * when the rx descriptor is setup again to receive
2981 		 * another frame.
2982 		 */
2983 		bus_dmamap_sync(sc->sc_dmat, bf->bf_dmamap,
2984 		    BUS_DMASYNC_POSTREAD);
2985 		bus_dmamap_unload(sc->sc_dmat, bf->bf_dmamap);
2986 		bf->bf_m = NULL;
2987 
2988 		m->m_pkthdr.rcvif = ifp;
2989 		len = ds->ds_rxstat.rs_datalen;
2990 		m->m_pkthdr.len = m->m_len = len;
2991 
2992 		sc->sc_stats.ast_ant_rx[ds->ds_rxstat.rs_antenna]++;
2993 
2994 		if (bpf_peers_present(sc->sc_drvbpf) &&
2995 		    !ath_rx_tap(sc, m, ds, tsf, nf)) {
2996 			m_freem(m);		/* XXX reclaim */
2997 			goto rx_next;
2998 		}
2999 
3000 		/*
3001 		 * From this point on we assume the frame is at least
3002 		 * as large as ieee80211_frame_min; verify that.
3003 		 */
3004 		if (len < IEEE80211_MIN_LEN) {
3005 			DPRINTF(sc, ATH_DEBUG_RECV, "%s: short packet %d\n",
3006 				__func__, len);
3007 			sc->sc_stats.ast_rx_tooshort++;
3008 			m_freem(m);
3009 			goto rx_next;
3010 		}
3011 
3012 		if (IFF_DUMPPKTS(sc, ATH_DEBUG_RECV)) {
3013 			ieee80211_dump_pkt(mtod(m, caddr_t), len,
3014 				   sc->sc_hwmap[ds->ds_rxstat.rs_rate].ieeerate,
3015 				   ds->ds_rxstat.rs_rssi);
3016 		}
3017 
3018 		m_adj(m, -IEEE80211_CRC_LEN);
3019 
3020 		/*
3021 		 * Locate the node for sender, track state, and then
3022 		 * pass the (referenced) node up to the 802.11 layer
3023 		 * for its use.
3024 		 */
3025 		ni = ieee80211_find_rxnode_withkey(ic,
3026 			mtod(m, const struct ieee80211_frame_min *),
3027 			ds->ds_rxstat.rs_keyix == HAL_RXKEYIX_INVALID ?
3028 				IEEE80211_KEYIX_NONE : ds->ds_rxstat.rs_keyix);
3029 		/*
3030 		 * Track rx rssi and do any rx antenna management.
3031 		 */
3032 		an = ATH_NODE(ni);
3033 		ATH_RSSI_LPF(an->an_avgrssi, ds->ds_rxstat.rs_rssi);
3034 		ATH_RSSI_LPF(sc->sc_halstats.ns_avgrssi, ds->ds_rxstat.rs_rssi);
3035 		/*
3036 		 * Send frame up for processing.
3037 		 */
3038 		type = ieee80211_input(ic, m, ni,
3039 			ds->ds_rxstat.rs_rssi, ds->ds_rxstat.rs_tstamp);
3040 		ieee80211_free_node(ni);
3041 		if (sc->sc_diversity) {
3042 			/*
3043 			 * When using fast diversity, change the default rx
3044 			 * antenna if diversity chooses the other antenna 3
3045 			 * times in a row.
3046 			 */
3047 			if (sc->sc_defant != ds->ds_rxstat.rs_antenna) {
3048 				if (++sc->sc_rxotherant >= 3)
3049 					ath_setdefantenna(sc,
3050 						ds->ds_rxstat.rs_antenna);
3051 			} else
3052 				sc->sc_rxotherant = 0;
3053 		}
3054 		if (sc->sc_softled) {
3055 			/*
3056 			 * Blink for any data frame.  Otherwise do a
3057 			 * heartbeat-style blink when idle.  The latter
3058 			 * is mainly for station mode where we depend on
3059 			 * periodic beacon frames to trigger the poll event.
3060 			 */
3061 			if (type == IEEE80211_FC0_TYPE_DATA) {
3062 				sc->sc_rxrate = ds->ds_rxstat.rs_rate;
3063 				ath_led_event(sc, ATH_LED_RX);
3064 			} else if (ticks - sc->sc_ledevent >= sc->sc_ledidle)
3065 				ath_led_event(sc, ATH_LED_POLL);
3066 		}
3067 		/*
3068 		 * Arrange to update the last rx timestamp only for
3069 		 * frames from our ap when operating in station mode.
3070 		 * This assumes the rx key is always setup when associated.
3071 		 */
3072 		if (ic->ic_opmode == IEEE80211_M_STA &&
3073 		    ds->ds_rxstat.rs_keyix != HAL_RXKEYIX_INVALID)
3074 			ngood++;
3075 rx_next:
3076 		STAILQ_INSERT_TAIL(&sc->sc_rxbuf, bf, bf_list);
3077 	} while (ath_rxbuf_init(sc, bf) == 0);
3078 
3079 	/* rx signal state monitoring */
3080 	ath_hal_rxmonitor(ah, &sc->sc_halstats, &sc->sc_curchan);
3081 	if (ath_hal_radar_event(ah))
3082 		taskqueue_enqueue(sc->sc_tq, &sc->sc_radartask);
3083 	if (ngood)
3084 		sc->sc_lastrx = tsf;
3085 
3086 	NET_UNLOCK_GIANT();		/* XXX */
3087 #undef PA2DESC
3088 }
3089 
3090 static void
3091 ath_txq_init(struct ath_softc *sc, struct ath_txq *txq, int qnum)
3092 {
3093 	txq->axq_qnum = qnum;
3094 	txq->axq_depth = 0;
3095 	txq->axq_intrcnt = 0;
3096 	txq->axq_link = NULL;
3097 	STAILQ_INIT(&txq->axq_q);
3098 	ATH_TXQ_LOCK_INIT(sc, txq);
3099 }
3100 
3101 /*
3102  * Setup a h/w transmit queue.
3103  */
3104 static struct ath_txq *
3105 ath_txq_setup(struct ath_softc *sc, int qtype, int subtype)
3106 {
3107 #define	N(a)	(sizeof(a)/sizeof(a[0]))
3108 	struct ath_hal *ah = sc->sc_ah;
3109 	HAL_TXQ_INFO qi;
3110 	int qnum;
3111 
3112 	memset(&qi, 0, sizeof(qi));
3113 	qi.tqi_subtype = subtype;
3114 	qi.tqi_aifs = HAL_TXQ_USEDEFAULT;
3115 	qi.tqi_cwmin = HAL_TXQ_USEDEFAULT;
3116 	qi.tqi_cwmax = HAL_TXQ_USEDEFAULT;
3117 	/*
3118 	 * Enable interrupts only for EOL and DESC conditions.
3119 	 * We mark tx descriptors to receive a DESC interrupt
3120 	 * when a tx queue gets deep; otherwise waiting for the
3121 	 * EOL to reap descriptors.  Note that this is done to
3122 	 * reduce interrupt load and this only defers reaping
3123 	 * descriptors, never transmitting frames.  Aside from
3124 	 * reducing interrupts this also permits more concurrency.
3125 	 * The only potential downside is if the tx queue backs
3126 	 * up in which case the top half of the kernel may backup
3127 	 * due to a lack of tx descriptors.
3128 	 */
3129 	qi.tqi_qflags = HAL_TXQ_TXEOLINT_ENABLE | HAL_TXQ_TXDESCINT_ENABLE;
3130 	qnum = ath_hal_setuptxqueue(ah, qtype, &qi);
3131 	if (qnum == -1) {
3132 		/*
3133 		 * NB: don't print a message, this happens
3134 		 * normally on parts with too few tx queues
3135 		 */
3136 		return NULL;
3137 	}
3138 	if (qnum >= N(sc->sc_txq)) {
3139 		device_printf(sc->sc_dev,
3140 			"hal qnum %u out of range, max %zu!\n",
3141 			qnum, N(sc->sc_txq));
3142 		ath_hal_releasetxqueue(ah, qnum);
3143 		return NULL;
3144 	}
3145 	if (!ATH_TXQ_SETUP(sc, qnum)) {
3146 		ath_txq_init(sc, &sc->sc_txq[qnum], qnum);
3147 		sc->sc_txqsetup |= 1<<qnum;
3148 	}
3149 	return &sc->sc_txq[qnum];
3150 #undef N
3151 }
3152 
3153 /*
3154  * Setup a hardware data transmit queue for the specified
3155  * access control.  The hal may not support all requested
3156  * queues in which case it will return a reference to a
3157  * previously setup queue.  We record the mapping from ac's
3158  * to h/w queues for use by ath_tx_start and also track
3159  * the set of h/w queues being used to optimize work in the
3160  * transmit interrupt handler and related routines.
3161  */
3162 static int
3163 ath_tx_setup(struct ath_softc *sc, int ac, int haltype)
3164 {
3165 #define	N(a)	(sizeof(a)/sizeof(a[0]))
3166 	struct ath_txq *txq;
3167 
3168 	if (ac >= N(sc->sc_ac2q)) {
3169 		device_printf(sc->sc_dev, "AC %u out of range, max %zu!\n",
3170 			ac, N(sc->sc_ac2q));
3171 		return 0;
3172 	}
3173 	txq = ath_txq_setup(sc, HAL_TX_QUEUE_DATA, haltype);
3174 	if (txq != NULL) {
3175 		sc->sc_ac2q[ac] = txq;
3176 		return 1;
3177 	} else
3178 		return 0;
3179 #undef N
3180 }
3181 
3182 /*
3183  * Update WME parameters for a transmit queue.
3184  */
3185 static int
3186 ath_txq_update(struct ath_softc *sc, int ac)
3187 {
3188 #define	ATH_EXPONENT_TO_VALUE(v)	((1<<v)-1)
3189 #define	ATH_TXOP_TO_US(v)		(v<<5)
3190 	struct ieee80211com *ic = &sc->sc_ic;
3191 	struct ath_txq *txq = sc->sc_ac2q[ac];
3192 	struct wmeParams *wmep = &ic->ic_wme.wme_chanParams.cap_wmeParams[ac];
3193 	struct ath_hal *ah = sc->sc_ah;
3194 	HAL_TXQ_INFO qi;
3195 
3196 	ath_hal_gettxqueueprops(ah, txq->axq_qnum, &qi);
3197 	qi.tqi_aifs = wmep->wmep_aifsn;
3198 	qi.tqi_cwmin = ATH_EXPONENT_TO_VALUE(wmep->wmep_logcwmin);
3199 	qi.tqi_cwmax = ATH_EXPONENT_TO_VALUE(wmep->wmep_logcwmax);
3200 	qi.tqi_burstTime = ATH_TXOP_TO_US(wmep->wmep_txopLimit);
3201 
3202 	if (!ath_hal_settxqueueprops(ah, txq->axq_qnum, &qi)) {
3203 		device_printf(sc->sc_dev, "unable to update hardware queue "
3204 			"parameters for %s traffic!\n",
3205 			ieee80211_wme_acnames[ac]);
3206 		return 0;
3207 	} else {
3208 		ath_hal_resettxqueue(ah, txq->axq_qnum); /* push to h/w */
3209 		return 1;
3210 	}
3211 #undef ATH_TXOP_TO_US
3212 #undef ATH_EXPONENT_TO_VALUE
3213 }
3214 
3215 /*
3216  * Callback from the 802.11 layer to update WME parameters.
3217  */
3218 static int
3219 ath_wme_update(struct ieee80211com *ic)
3220 {
3221 	struct ath_softc *sc = ic->ic_ifp->if_softc;
3222 
3223 	return !ath_txq_update(sc, WME_AC_BE) ||
3224 	    !ath_txq_update(sc, WME_AC_BK) ||
3225 	    !ath_txq_update(sc, WME_AC_VI) ||
3226 	    !ath_txq_update(sc, WME_AC_VO) ? EIO : 0;
3227 }
3228 
3229 /*
3230  * Reclaim resources for a setup queue.
3231  */
3232 static void
3233 ath_tx_cleanupq(struct ath_softc *sc, struct ath_txq *txq)
3234 {
3235 
3236 	ath_hal_releasetxqueue(sc->sc_ah, txq->axq_qnum);
3237 	ATH_TXQ_LOCK_DESTROY(txq);
3238 	sc->sc_txqsetup &= ~(1<<txq->axq_qnum);
3239 }
3240 
3241 /*
3242  * Reclaim all tx queue resources.
3243  */
3244 static void
3245 ath_tx_cleanup(struct ath_softc *sc)
3246 {
3247 	int i;
3248 
3249 	ATH_TXBUF_LOCK_DESTROY(sc);
3250 	for (i = 0; i < HAL_NUM_TX_QUEUES; i++)
3251 		if (ATH_TXQ_SETUP(sc, i))
3252 			ath_tx_cleanupq(sc, &sc->sc_txq[i]);
3253 	ATH_TXQ_LOCK_DESTROY(&sc->sc_mcastq);
3254 }
3255 
3256 /*
3257  * Defragment an mbuf chain, returning at most maxfrags separate
3258  * mbufs+clusters.  If this is not possible NULL is returned and
3259  * the original mbuf chain is left in it's present (potentially
3260  * modified) state.  We use two techniques: collapsing consecutive
3261  * mbufs and replacing consecutive mbufs by a cluster.
3262  */
3263 static struct mbuf *
3264 ath_defrag(struct mbuf *m0, int how, int maxfrags)
3265 {
3266 	struct mbuf *m, *n, *n2, **prev;
3267 	u_int curfrags;
3268 
3269 	/*
3270 	 * Calculate the current number of frags.
3271 	 */
3272 	curfrags = 0;
3273 	for (m = m0; m != NULL; m = m->m_next)
3274 		curfrags++;
3275 	/*
3276 	 * First, try to collapse mbufs.  Note that we always collapse
3277 	 * towards the front so we don't need to deal with moving the
3278 	 * pkthdr.  This may be suboptimal if the first mbuf has much
3279 	 * less data than the following.
3280 	 */
3281 	m = m0;
3282 again:
3283 	for (;;) {
3284 		n = m->m_next;
3285 		if (n == NULL)
3286 			break;
3287 		if ((m->m_flags & M_RDONLY) == 0 &&
3288 		    n->m_len < M_TRAILINGSPACE(m)) {
3289 			bcopy(mtod(n, void *), mtod(m, char *) + m->m_len,
3290 				n->m_len);
3291 			m->m_len += n->m_len;
3292 			m->m_next = n->m_next;
3293 			m_free(n);
3294 			if (--curfrags <= maxfrags)
3295 				return m0;
3296 		} else
3297 			m = n;
3298 	}
3299 	KASSERT(maxfrags > 1,
3300 		("maxfrags %u, but normal collapse failed", maxfrags));
3301 	/*
3302 	 * Collapse consecutive mbufs to a cluster.
3303 	 */
3304 	prev = &m0->m_next;		/* NB: not the first mbuf */
3305 	while ((n = *prev) != NULL) {
3306 		if ((n2 = n->m_next) != NULL &&
3307 		    n->m_len + n2->m_len < MCLBYTES) {
3308 			m = m_getcl(how, MT_DATA, 0);
3309 			if (m == NULL)
3310 				goto bad;
3311 			bcopy(mtod(n, void *), mtod(m, void *), n->m_len);
3312 			bcopy(mtod(n2, void *), mtod(m, char *) + n->m_len,
3313 				n2->m_len);
3314 			m->m_len = n->m_len + n2->m_len;
3315 			m->m_next = n2->m_next;
3316 			*prev = m;
3317 			m_free(n);
3318 			m_free(n2);
3319 			if (--curfrags <= maxfrags)	/* +1 cl -2 mbufs */
3320 				return m0;
3321 			/*
3322 			 * Still not there, try the normal collapse
3323 			 * again before we allocate another cluster.
3324 			 */
3325 			goto again;
3326 		}
3327 		prev = &n->m_next;
3328 	}
3329 	/*
3330 	 * No place where we can collapse to a cluster; punt.
3331 	 * This can occur if, for example, you request 2 frags
3332 	 * but the packet requires that both be clusters (we
3333 	 * never reallocate the first mbuf to avoid moving the
3334 	 * packet header).
3335 	 */
3336 bad:
3337 	return NULL;
3338 }
3339 
3340 /*
3341  * Return h/w rate index for an IEEE rate (w/o basic rate bit).
3342  */
3343 static int
3344 ath_tx_findrix(const HAL_RATE_TABLE *rt, int rate)
3345 {
3346 	int i;
3347 
3348 	for (i = 0; i < rt->rateCount; i++)
3349 		if ((rt->info[i].dot11Rate & IEEE80211_RATE_VAL) == rate)
3350 			return i;
3351 	return 0;		/* NB: lowest rate */
3352 }
3353 
3354 static int
3355 ath_tx_start(struct ath_softc *sc, struct ieee80211_node *ni, struct ath_buf *bf,
3356     struct mbuf *m0)
3357 {
3358 	struct ieee80211com *ic = &sc->sc_ic;
3359 	struct ath_hal *ah = sc->sc_ah;
3360 	struct ifnet *ifp = sc->sc_ifp;
3361 	const struct chanAccParams *cap = &ic->ic_wme.wme_chanParams;
3362 	int i, error, iswep, ismcast, ismrr;
3363 	int keyix, hdrlen, pktlen, try0;
3364 	u_int8_t rix, txrate, ctsrate;
3365 	u_int8_t cix = 0xff;		/* NB: silence compiler */
3366 	struct ath_desc *ds, *ds0;
3367 	struct ath_txq *txq;
3368 	struct ieee80211_frame *wh;
3369 	u_int subtype, flags, ctsduration;
3370 	HAL_PKT_TYPE atype;
3371 	const HAL_RATE_TABLE *rt;
3372 	HAL_BOOL shortPreamble;
3373 	struct ath_node *an;
3374 	struct mbuf *m;
3375 	u_int pri;
3376 
3377 	wh = mtod(m0, struct ieee80211_frame *);
3378 	iswep = wh->i_fc[1] & IEEE80211_FC1_WEP;
3379 	ismcast = IEEE80211_IS_MULTICAST(wh->i_addr1);
3380 	hdrlen = ieee80211_anyhdrsize(wh);
3381 	/*
3382 	 * Packet length must not include any
3383 	 * pad bytes; deduct them here.
3384 	 */
3385 	pktlen = m0->m_pkthdr.len - (hdrlen & 3);
3386 
3387 	if (iswep) {
3388 		const struct ieee80211_cipher *cip;
3389 		struct ieee80211_key *k;
3390 
3391 		/*
3392 		 * Construct the 802.11 header+trailer for an encrypted
3393 		 * frame. The only reason this can fail is because of an
3394 		 * unknown or unsupported cipher/key type.
3395 		 */
3396 		k = ieee80211_crypto_encap(ic, ni, m0);
3397 		if (k == NULL) {
3398 			/*
3399 			 * This can happen when the key is yanked after the
3400 			 * frame was queued.  Just discard the frame; the
3401 			 * 802.11 layer counts failures and provides
3402 			 * debugging/diagnostics.
3403 			 */
3404 			m_freem(m0);
3405 			return EIO;
3406 		}
3407 		/*
3408 		 * Adjust the packet + header lengths for the crypto
3409 		 * additions and calculate the h/w key index.  When
3410 		 * a s/w mic is done the frame will have had any mic
3411 		 * added to it prior to entry so m0->m_pkthdr.len above will
3412 		 * account for it. Otherwise we need to add it to the
3413 		 * packet length.
3414 		 */
3415 		cip = k->wk_cipher;
3416 		hdrlen += cip->ic_header;
3417 		pktlen += cip->ic_header + cip->ic_trailer;
3418 		if ((k->wk_flags & IEEE80211_KEY_SWMIC) == 0)
3419 			pktlen += cip->ic_miclen;
3420 		keyix = k->wk_keyix;
3421 
3422 		/* packet header may have moved, reset our local pointer */
3423 		wh = mtod(m0, struct ieee80211_frame *);
3424 	} else if (ni->ni_ucastkey.wk_cipher == &ieee80211_cipher_none) {
3425 		/*
3426 		 * Use station key cache slot, if assigned.
3427 		 */
3428 		keyix = ni->ni_ucastkey.wk_keyix;
3429 		if (keyix == IEEE80211_KEYIX_NONE)
3430 			keyix = HAL_TXKEYIX_INVALID;
3431 	} else
3432 		keyix = HAL_TXKEYIX_INVALID;
3433 
3434 	pktlen += IEEE80211_CRC_LEN;
3435 
3436 	/*
3437 	 * Load the DMA map so any coalescing is done.  This
3438 	 * also calculates the number of descriptors we need.
3439 	 */
3440 	error = bus_dmamap_load_mbuf_sg(sc->sc_dmat, bf->bf_dmamap, m0,
3441 				     bf->bf_segs, &bf->bf_nseg,
3442 				     BUS_DMA_NOWAIT);
3443 	if (error == EFBIG) {
3444 		/* XXX packet requires too many descriptors */
3445 		bf->bf_nseg = ATH_TXDESC+1;
3446 	} else if (error != 0) {
3447 		sc->sc_stats.ast_tx_busdma++;
3448 		m_freem(m0);
3449 		return error;
3450 	}
3451 	/*
3452 	 * Discard null packets and check for packets that
3453 	 * require too many TX descriptors.  We try to convert
3454 	 * the latter to a cluster.
3455 	 */
3456 	if (bf->bf_nseg > ATH_TXDESC) {		/* too many desc's, linearize */
3457 		sc->sc_stats.ast_tx_linear++;
3458 		m = ath_defrag(m0, M_DONTWAIT, ATH_TXDESC);
3459 		if (m == NULL) {
3460 			m_freem(m0);
3461 			sc->sc_stats.ast_tx_nombuf++;
3462 			return ENOMEM;
3463 		}
3464 		m0 = m;
3465 		error = bus_dmamap_load_mbuf_sg(sc->sc_dmat, bf->bf_dmamap, m0,
3466 					     bf->bf_segs, &bf->bf_nseg,
3467 					     BUS_DMA_NOWAIT);
3468 		if (error != 0) {
3469 			sc->sc_stats.ast_tx_busdma++;
3470 			m_freem(m0);
3471 			return error;
3472 		}
3473 		KASSERT(bf->bf_nseg <= ATH_TXDESC,
3474 		    ("too many segments after defrag; nseg %u", bf->bf_nseg));
3475 	} else if (bf->bf_nseg == 0) {		/* null packet, discard */
3476 		sc->sc_stats.ast_tx_nodata++;
3477 		m_freem(m0);
3478 		return EIO;
3479 	}
3480 	DPRINTF(sc, ATH_DEBUG_XMIT, "%s: m %p len %u\n", __func__, m0, pktlen);
3481 	bus_dmamap_sync(sc->sc_dmat, bf->bf_dmamap, BUS_DMASYNC_PREWRITE);
3482 	bf->bf_m = m0;
3483 	bf->bf_node = ni;			/* NB: held reference */
3484 
3485 	/* setup descriptors */
3486 	ds = bf->bf_desc;
3487 	rt = sc->sc_currates;
3488 	KASSERT(rt != NULL, ("no rate table, mode %u", sc->sc_curmode));
3489 
3490 	/*
3491 	 * NB: the 802.11 layer marks whether or not we should
3492 	 * use short preamble based on the current mode and
3493 	 * negotiated parameters.
3494 	 */
3495 	if ((ic->ic_flags & IEEE80211_F_SHPREAMBLE) &&
3496 	    (ni->ni_capinfo & IEEE80211_CAPINFO_SHORT_PREAMBLE)) {
3497 		shortPreamble = AH_TRUE;
3498 		sc->sc_stats.ast_tx_shortpre++;
3499 	} else {
3500 		shortPreamble = AH_FALSE;
3501 	}
3502 
3503 	an = ATH_NODE(ni);
3504 	flags = HAL_TXDESC_CLRDMASK;		/* XXX needed for crypto errs */
3505 	ismrr = 0;				/* default no multi-rate retry*/
3506 	/*
3507 	 * Calculate Atheros packet type from IEEE80211 packet header,
3508 	 * setup for rate calculations, and select h/w transmit queue.
3509 	 */
3510 	switch (wh->i_fc[0] & IEEE80211_FC0_TYPE_MASK) {
3511 	case IEEE80211_FC0_TYPE_MGT:
3512 		subtype = wh->i_fc[0] & IEEE80211_FC0_SUBTYPE_MASK;
3513 		if (subtype == IEEE80211_FC0_SUBTYPE_BEACON)
3514 			atype = HAL_PKT_TYPE_BEACON;
3515 		else if (subtype == IEEE80211_FC0_SUBTYPE_PROBE_RESP)
3516 			atype = HAL_PKT_TYPE_PROBE_RESP;
3517 		else if (subtype == IEEE80211_FC0_SUBTYPE_ATIM)
3518 			atype = HAL_PKT_TYPE_ATIM;
3519 		else
3520 			atype = HAL_PKT_TYPE_NORMAL;	/* XXX */
3521 		rix = sc->sc_minrateix;
3522 		txrate = rt->info[rix].rateCode;
3523 		if (shortPreamble)
3524 			txrate |= rt->info[rix].shortPreamble;
3525 		try0 = ATH_TXMGTTRY;
3526 		/* NB: force all management frames to highest queue */
3527 		if (ni->ni_flags & IEEE80211_NODE_QOS) {
3528 			/* NB: force all management frames to highest queue */
3529 			pri = WME_AC_VO;
3530 		} else
3531 			pri = WME_AC_BE;
3532 		flags |= HAL_TXDESC_INTREQ;	/* force interrupt */
3533 		break;
3534 	case IEEE80211_FC0_TYPE_CTL:
3535 		atype = HAL_PKT_TYPE_PSPOLL;	/* stop setting of duration */
3536 		rix = sc->sc_minrateix;
3537 		txrate = rt->info[rix].rateCode;
3538 		if (shortPreamble)
3539 			txrate |= rt->info[rix].shortPreamble;
3540 		try0 = ATH_TXMGTTRY;
3541 		/* NB: force all ctl frames to highest queue */
3542 		if (ni->ni_flags & IEEE80211_NODE_QOS) {
3543 			/* NB: force all ctl frames to highest queue */
3544 			pri = WME_AC_VO;
3545 		} else
3546 			pri = WME_AC_BE;
3547 		flags |= HAL_TXDESC_INTREQ;	/* force interrupt */
3548 		break;
3549 	case IEEE80211_FC0_TYPE_DATA:
3550 		atype = HAL_PKT_TYPE_NORMAL;		/* default */
3551 		/*
3552 		 * Data frames: multicast frames go out at a fixed rate,
3553 		 * otherwise consult the rate control module for the
3554 		 * rate to use.
3555 		 */
3556 		if (ismcast) {
3557 			/*
3558 			 * Check mcast rate setting in case it's changed.
3559 			 * XXX move out of fastpath
3560 			 */
3561 			if (ic->ic_mcast_rate != sc->sc_mcastrate) {
3562 				sc->sc_mcastrix =
3563 					ath_tx_findrix(rt, ic->ic_mcast_rate);
3564 				sc->sc_mcastrate = ic->ic_mcast_rate;
3565 			}
3566 			rix = sc->sc_mcastrix;
3567 			txrate = rt->info[rix].rateCode;
3568 			if (shortPreamble)
3569 				txrate |= rt->info[rix].shortPreamble;
3570 			try0 = 1;
3571 		} else {
3572 			ath_rate_findrate(sc, an, shortPreamble, pktlen,
3573 				&rix, &try0, &txrate);
3574 			sc->sc_txrate = txrate;		/* for LED blinking */
3575 			if (try0 != ATH_TXMAXTRY)
3576 				ismrr = 1;
3577 		}
3578 		pri = M_WME_GETAC(m0);
3579 		if (cap->cap_wmeParams[pri].wmep_noackPolicy)
3580 			flags |= HAL_TXDESC_NOACK;
3581 		break;
3582 	default:
3583 		if_printf(ifp, "bogus frame type 0x%x (%s)\n",
3584 			wh->i_fc[0] & IEEE80211_FC0_TYPE_MASK, __func__);
3585 		/* XXX statistic */
3586 		m_freem(m0);
3587 		return EIO;
3588 	}
3589 	txq = sc->sc_ac2q[pri];
3590 
3591 	/*
3592 	 * When servicing one or more stations in power-save mode
3593 	 * (or) if there is some mcast data waiting on the mcast
3594 	 * queue (to prevent out of order delivery) multicast
3595 	 * frames must be buffered until after the beacon.
3596 	 */
3597 	if (ismcast && (ic->ic_ps_sta || sc->sc_mcastq.axq_depth)) {
3598 		txq = &sc->sc_mcastq;
3599 		/* XXX? more bit in 802.11 frame header */
3600 	}
3601 
3602 	/*
3603 	 * Calculate miscellaneous flags.
3604 	 */
3605 	if (ismcast) {
3606 		flags |= HAL_TXDESC_NOACK;	/* no ack on broad/multicast */
3607 	} else if (pktlen > ic->ic_rtsthreshold) {
3608 		flags |= HAL_TXDESC_RTSENA;	/* RTS based on frame length */
3609 		cix = rt->info[rix].controlRate;
3610 		sc->sc_stats.ast_tx_rts++;
3611 	}
3612 	if (flags & HAL_TXDESC_NOACK)		/* NB: avoid double counting */
3613 		sc->sc_stats.ast_tx_noack++;
3614 
3615 	/*
3616 	 * If 802.11g protection is enabled, determine whether
3617 	 * to use RTS/CTS or just CTS.  Note that this is only
3618 	 * done for OFDM unicast frames.
3619 	 */
3620 	if ((ic->ic_flags & IEEE80211_F_USEPROT) &&
3621 	    rt->info[rix].phy == IEEE80211_T_OFDM &&
3622 	    (flags & HAL_TXDESC_NOACK) == 0) {
3623 		/* XXX fragments must use CCK rates w/ protection */
3624 		if (ic->ic_protmode == IEEE80211_PROT_RTSCTS)
3625 			flags |= HAL_TXDESC_RTSENA;
3626 		else if (ic->ic_protmode == IEEE80211_PROT_CTSONLY)
3627 			flags |= HAL_TXDESC_CTSENA;
3628 		cix = rt->info[sc->sc_protrix].controlRate;
3629 		sc->sc_stats.ast_tx_protect++;
3630 	}
3631 
3632 	/*
3633 	 * Calculate duration.  This logically belongs in the 802.11
3634 	 * layer but it lacks sufficient information to calculate it.
3635 	 */
3636 	if ((flags & HAL_TXDESC_NOACK) == 0 &&
3637 	    (wh->i_fc[0] & IEEE80211_FC0_TYPE_MASK) != IEEE80211_FC0_TYPE_CTL) {
3638 		u_int16_t dur;
3639 		/*
3640 		 * XXX not right with fragmentation.
3641 		 */
3642 		if (shortPreamble)
3643 			dur = rt->info[rix].spAckDuration;
3644 		else
3645 			dur = rt->info[rix].lpAckDuration;
3646 		*(u_int16_t *)wh->i_dur = htole16(dur);
3647 	}
3648 
3649 	/*
3650 	 * Calculate RTS/CTS rate and duration if needed.
3651 	 */
3652 	ctsduration = 0;
3653 	if (flags & (HAL_TXDESC_RTSENA|HAL_TXDESC_CTSENA)) {
3654 		/*
3655 		 * CTS transmit rate is derived from the transmit rate
3656 		 * by looking in the h/w rate table.  We must also factor
3657 		 * in whether or not a short preamble is to be used.
3658 		 */
3659 		/* NB: cix is set above where RTS/CTS is enabled */
3660 		KASSERT(cix != 0xff, ("cix not setup"));
3661 		ctsrate = rt->info[cix].rateCode;
3662 		/*
3663 		 * Compute the transmit duration based on the frame
3664 		 * size and the size of an ACK frame.  We call into the
3665 		 * HAL to do the computation since it depends on the
3666 		 * characteristics of the actual PHY being used.
3667 		 *
3668 		 * NB: CTS is assumed the same size as an ACK so we can
3669 		 *     use the precalculated ACK durations.
3670 		 */
3671 		if (shortPreamble) {
3672 			ctsrate |= rt->info[cix].shortPreamble;
3673 			if (flags & HAL_TXDESC_RTSENA)		/* SIFS + CTS */
3674 				ctsduration += rt->info[cix].spAckDuration;
3675 			ctsduration += ath_hal_computetxtime(ah,
3676 				rt, pktlen, rix, AH_TRUE);
3677 			if ((flags & HAL_TXDESC_NOACK) == 0)	/* SIFS + ACK */
3678 				ctsduration += rt->info[rix].spAckDuration;
3679 		} else {
3680 			if (flags & HAL_TXDESC_RTSENA)		/* SIFS + CTS */
3681 				ctsduration += rt->info[cix].lpAckDuration;
3682 			ctsduration += ath_hal_computetxtime(ah,
3683 				rt, pktlen, rix, AH_FALSE);
3684 			if ((flags & HAL_TXDESC_NOACK) == 0)	/* SIFS + ACK */
3685 				ctsduration += rt->info[rix].lpAckDuration;
3686 		}
3687 		/*
3688 		 * Must disable multi-rate retry when using RTS/CTS.
3689 		 */
3690 		ismrr = 0;
3691 		try0 = ATH_TXMGTTRY;		/* XXX */
3692 	} else
3693 		ctsrate = 0;
3694 
3695 	if (IFF_DUMPPKTS(sc, ATH_DEBUG_XMIT))
3696 		ieee80211_dump_pkt(mtod(m0, caddr_t), m0->m_len,
3697 			sc->sc_hwmap[txrate].ieeerate, -1);
3698 
3699 	if (bpf_peers_present(ic->ic_rawbpf))
3700 		bpf_mtap(ic->ic_rawbpf, m0);
3701 	if (bpf_peers_present(sc->sc_drvbpf)) {
3702 		u_int64_t tsf = ath_hal_gettsf64(ah);
3703 
3704 		sc->sc_tx_th.wt_tsf = htole64(tsf);
3705 		sc->sc_tx_th.wt_flags = sc->sc_hwmap[txrate].txflags;
3706 		if (iswep)
3707 			sc->sc_tx_th.wt_flags |= IEEE80211_RADIOTAP_F_WEP;
3708 		sc->sc_tx_th.wt_rate = sc->sc_hwmap[txrate].ieeerate;
3709 		sc->sc_tx_th.wt_txpower = ni->ni_txpower;
3710 		sc->sc_tx_th.wt_antenna = sc->sc_txantenna;
3711 
3712 		bpf_mtap2(sc->sc_drvbpf,
3713 			&sc->sc_tx_th, sc->sc_tx_th_len, m0);
3714 	}
3715 
3716 	/*
3717 	 * Determine if a tx interrupt should be generated for
3718 	 * this descriptor.  We take a tx interrupt to reap
3719 	 * descriptors when the h/w hits an EOL condition or
3720 	 * when the descriptor is specifically marked to generate
3721 	 * an interrupt.  We periodically mark descriptors in this
3722 	 * way to insure timely replenishing of the supply needed
3723 	 * for sending frames.  Defering interrupts reduces system
3724 	 * load and potentially allows more concurrent work to be
3725 	 * done but if done to aggressively can cause senders to
3726 	 * backup.
3727 	 *
3728 	 * NB: use >= to deal with sc_txintrperiod changing
3729 	 *     dynamically through sysctl.
3730 	 */
3731 	if (flags & HAL_TXDESC_INTREQ) {
3732 		txq->axq_intrcnt = 0;
3733 	} else if (++txq->axq_intrcnt >= sc->sc_txintrperiod) {
3734 		flags |= HAL_TXDESC_INTREQ;
3735 		txq->axq_intrcnt = 0;
3736 	}
3737 
3738 	/*
3739 	 * Formulate first tx descriptor with tx controls.
3740 	 */
3741 	/* XXX check return value? */
3742 	ath_hal_setuptxdesc(ah, ds
3743 		, pktlen		/* packet length */
3744 		, hdrlen		/* header length */
3745 		, atype			/* Atheros packet type */
3746 		, ni->ni_txpower	/* txpower */
3747 		, txrate, try0		/* series 0 rate/tries */
3748 		, keyix			/* key cache index */
3749 		, sc->sc_txantenna	/* antenna mode */
3750 		, flags			/* flags */
3751 		, ctsrate		/* rts/cts rate */
3752 		, ctsduration		/* rts/cts duration */
3753 	);
3754 	bf->bf_flags = flags;
3755 	/*
3756 	 * Setup the multi-rate retry state only when we're
3757 	 * going to use it.  This assumes ath_hal_setuptxdesc
3758 	 * initializes the descriptors (so we don't have to)
3759 	 * when the hardware supports multi-rate retry and
3760 	 * we don't use it.
3761 	 */
3762 	if (ismrr)
3763 		ath_rate_setupxtxdesc(sc, an, ds, shortPreamble, rix);
3764 
3765 	/*
3766 	 * Fillin the remainder of the descriptor info.
3767 	 */
3768 	ds0 = ds;
3769 	for (i = 0; i < bf->bf_nseg; i++, ds++) {
3770 		ds->ds_data = bf->bf_segs[i].ds_addr;
3771 		if (i == bf->bf_nseg - 1)
3772 			ds->ds_link = 0;
3773 		else
3774 			ds->ds_link = bf->bf_daddr + sizeof(*ds) * (i + 1);
3775 		ath_hal_filltxdesc(ah, ds
3776 			, bf->bf_segs[i].ds_len	/* segment length */
3777 			, i == 0		/* first segment */
3778 			, i == bf->bf_nseg - 1	/* last segment */
3779 			, ds0			/* first descriptor */
3780 		);
3781 		DPRINTF(sc, ATH_DEBUG_XMIT,
3782 			"%s: %d: %08x %08x %08x %08x %08x %08x\n",
3783 			__func__, i, ds->ds_link, ds->ds_data,
3784 			ds->ds_ctl0, ds->ds_ctl1, ds->ds_hw[0], ds->ds_hw[1]);
3785 	}
3786 	/*
3787 	 * Insert the frame on the outbound list and pass it on
3788 	 * to the hardware.  Multicast frames buffered for power
3789 	 * save stations and transmit from the CAB queue are stored
3790 	 * on a s/w only queue and loaded on to the CAB queue in
3791 	 * the SWBA handler since frames only go out on DTIM and
3792 	 * to avoid possible races.
3793 	 */
3794 	ATH_TXQ_LOCK(txq);
3795 	ATH_TXQ_INSERT_TAIL(txq, bf, bf_list);
3796 	if (txq != &sc->sc_mcastq) {
3797 		if (txq->axq_link == NULL) {
3798 			ath_hal_puttxbuf(ah, txq->axq_qnum, bf->bf_daddr);
3799 			DPRINTF(sc, ATH_DEBUG_XMIT,
3800 			    "%s: TXDP[%u] = %p (%p) depth %d\n", __func__,
3801 			    txq->axq_qnum, (caddr_t)bf->bf_daddr, bf->bf_desc,
3802 			    txq->axq_depth);
3803 		} else {
3804 			*txq->axq_link = bf->bf_daddr;
3805 			DPRINTF(sc, ATH_DEBUG_XMIT,
3806 			    "%s: link[%u](%p)=%p (%p) depth %d\n", __func__,
3807 			    txq->axq_qnum, txq->axq_link,
3808 			    (caddr_t)bf->bf_daddr, bf->bf_desc, txq->axq_depth);
3809 		}
3810 		txq->axq_link = &bf->bf_desc[bf->bf_nseg - 1].ds_link;
3811 		ath_hal_txstart(ah, txq->axq_qnum);
3812 	} else {
3813 		if (txq->axq_link != NULL)
3814 			*txq->axq_link = bf->bf_daddr;
3815 		txq->axq_link = &bf->bf_desc[bf->bf_nseg - 1].ds_link;
3816 	}
3817 	ATH_TXQ_UNLOCK(txq);
3818 
3819 	return 0;
3820 }
3821 
3822 /*
3823  * Process completed xmit descriptors from the specified queue.
3824  */
3825 static int
3826 ath_tx_processq(struct ath_softc *sc, struct ath_txq *txq)
3827 {
3828 	struct ath_hal *ah = sc->sc_ah;
3829 	struct ieee80211com *ic = &sc->sc_ic;
3830 	struct ath_buf *bf;
3831 	struct ath_desc *ds, *ds0;
3832 	struct ieee80211_node *ni;
3833 	struct ath_node *an;
3834 	int sr, lr, pri, nacked;
3835 	HAL_STATUS status;
3836 
3837 	DPRINTF(sc, ATH_DEBUG_TX_PROC, "%s: tx queue %u head %p link %p\n",
3838 		__func__, txq->axq_qnum,
3839 		(caddr_t)(uintptr_t) ath_hal_gettxbuf(sc->sc_ah, txq->axq_qnum),
3840 		txq->axq_link);
3841 	nacked = 0;
3842 	for (;;) {
3843 		ATH_TXQ_LOCK(txq);
3844 		txq->axq_intrcnt = 0;	/* reset periodic desc intr count */
3845 		bf = STAILQ_FIRST(&txq->axq_q);
3846 		if (bf == NULL) {
3847 			ATH_TXQ_UNLOCK(txq);
3848 			break;
3849 		}
3850 		ds0 = &bf->bf_desc[0];
3851 		ds = &bf->bf_desc[bf->bf_nseg - 1];
3852 		status = ath_hal_txprocdesc(ah, ds);
3853 #ifdef ATH_DEBUG
3854 		if (sc->sc_debug & ATH_DEBUG_XMIT_DESC)
3855 			ath_printtxbuf(bf, txq->axq_qnum, 0, status == HAL_OK);
3856 #endif
3857 		if (status == HAL_EINPROGRESS) {
3858 			ATH_TXQ_UNLOCK(txq);
3859 			break;
3860 		}
3861 		ATH_TXQ_REMOVE_HEAD(txq, bf_list);
3862 		if (txq->axq_depth == 0)
3863 			txq->axq_link = NULL;
3864 		ATH_TXQ_UNLOCK(txq);
3865 
3866 		ni = bf->bf_node;
3867 		if (ni != NULL) {
3868 			an = ATH_NODE(ni);
3869 			if (ds->ds_txstat.ts_status == 0) {
3870 				u_int8_t txant = ds->ds_txstat.ts_antenna;
3871 				sc->sc_stats.ast_ant_tx[txant]++;
3872 				sc->sc_ant_tx[txant]++;
3873 				if (ds->ds_txstat.ts_rate & HAL_TXSTAT_ALTRATE)
3874 					sc->sc_stats.ast_tx_altrate++;
3875 				sc->sc_stats.ast_tx_rssi =
3876 					ds->ds_txstat.ts_rssi;
3877 				ATH_RSSI_LPF(sc->sc_halstats.ns_avgtxrssi,
3878 					ds->ds_txstat.ts_rssi);
3879 				pri = M_WME_GETAC(bf->bf_m);
3880 				if (pri >= WME_AC_VO)
3881 					ic->ic_wme.wme_hipri_traffic++;
3882 				ni->ni_inact = ni->ni_inact_reload;
3883 			} else {
3884 				if (ds->ds_txstat.ts_status & HAL_TXERR_XRETRY)
3885 					sc->sc_stats.ast_tx_xretries++;
3886 				if (ds->ds_txstat.ts_status & HAL_TXERR_FIFO)
3887 					sc->sc_stats.ast_tx_fifoerr++;
3888 				if (ds->ds_txstat.ts_status & HAL_TXERR_FILT)
3889 					sc->sc_stats.ast_tx_filtered++;
3890 			}
3891 			sr = ds->ds_txstat.ts_shortretry;
3892 			lr = ds->ds_txstat.ts_longretry;
3893 			sc->sc_stats.ast_tx_shortretry += sr;
3894 			sc->sc_stats.ast_tx_longretry += lr;
3895 			/*
3896 			 * Hand the descriptor to the rate control algorithm.
3897 			 */
3898 			if ((ds->ds_txstat.ts_status & HAL_TXERR_FILT) == 0 &&
3899 			    (bf->bf_flags & HAL_TXDESC_NOACK) == 0) {
3900 				/*
3901 				 * If frame was ack'd update the last rx time
3902 				 * used to workaround phantom bmiss interrupts.
3903 				 */
3904 				if (ds->ds_txstat.ts_status == 0)
3905 					nacked++;
3906 				ath_rate_tx_complete(sc, an, ds, ds0);
3907 			}
3908 			/*
3909 			 * Reclaim reference to node.
3910 			 *
3911 			 * NB: the node may be reclaimed here if, for example
3912 			 *     this is a DEAUTH message that was sent and the
3913 			 *     node was timed out due to inactivity.
3914 			 */
3915 			ieee80211_free_node(ni);
3916 		}
3917 		bus_dmamap_sync(sc->sc_dmat, bf->bf_dmamap,
3918 		    BUS_DMASYNC_POSTWRITE);
3919 		bus_dmamap_unload(sc->sc_dmat, bf->bf_dmamap);
3920 		m_freem(bf->bf_m);
3921 		bf->bf_m = NULL;
3922 		bf->bf_node = NULL;
3923 
3924 		ATH_TXBUF_LOCK(sc);
3925 		STAILQ_INSERT_TAIL(&sc->sc_txbuf, bf, bf_list);
3926 		ATH_TXBUF_UNLOCK(sc);
3927 	}
3928 	return nacked;
3929 }
3930 
3931 static __inline int
3932 txqactive(struct ath_hal *ah, int qnum)
3933 {
3934 	u_int32_t txqs = 1<<qnum;
3935 	ath_hal_gettxintrtxqs(ah, &txqs);
3936 	return (txqs & (1<<qnum));
3937 }
3938 
3939 /*
3940  * Deferred processing of transmit interrupt; special-cased
3941  * for a single hardware transmit queue (e.g. 5210 and 5211).
3942  */
3943 static void
3944 ath_tx_proc_q0(void *arg, int npending)
3945 {
3946 	struct ath_softc *sc = arg;
3947 	struct ifnet *ifp = sc->sc_ifp;
3948 
3949 	if (txqactive(sc->sc_ah, 0) && ath_tx_processq(sc, &sc->sc_txq[0]))
3950 		sc->sc_lastrx = ath_hal_gettsf64(sc->sc_ah);
3951 	if (txqactive(sc->sc_ah, sc->sc_cabq->axq_qnum))
3952 		ath_tx_processq(sc, sc->sc_cabq);
3953 	ifp->if_drv_flags &= ~IFF_DRV_OACTIVE;
3954 	sc->sc_tx_timer = 0;
3955 
3956 	if (sc->sc_softled)
3957 		ath_led_event(sc, ATH_LED_TX);
3958 
3959 	ath_start(ifp);
3960 }
3961 
3962 /*
3963  * Deferred processing of transmit interrupt; special-cased
3964  * for four hardware queues, 0-3 (e.g. 5212 w/ WME support).
3965  */
3966 static void
3967 ath_tx_proc_q0123(void *arg, int npending)
3968 {
3969 	struct ath_softc *sc = arg;
3970 	struct ifnet *ifp = sc->sc_ifp;
3971 	int nacked;
3972 
3973 	/*
3974 	 * Process each active queue.
3975 	 */
3976 	nacked = 0;
3977 	if (txqactive(sc->sc_ah, 0))
3978 		nacked += ath_tx_processq(sc, &sc->sc_txq[0]);
3979 	if (txqactive(sc->sc_ah, 1))
3980 		nacked += ath_tx_processq(sc, &sc->sc_txq[1]);
3981 	if (txqactive(sc->sc_ah, 2))
3982 		nacked += ath_tx_processq(sc, &sc->sc_txq[2]);
3983 	if (txqactive(sc->sc_ah, 3))
3984 		nacked += ath_tx_processq(sc, &sc->sc_txq[3]);
3985 	if (txqactive(sc->sc_ah, sc->sc_cabq->axq_qnum))
3986 		ath_tx_processq(sc, sc->sc_cabq);
3987 	if (nacked)
3988 		sc->sc_lastrx = ath_hal_gettsf64(sc->sc_ah);
3989 
3990 	ifp->if_drv_flags &= ~IFF_DRV_OACTIVE;
3991 	sc->sc_tx_timer = 0;
3992 
3993 	if (sc->sc_softled)
3994 		ath_led_event(sc, ATH_LED_TX);
3995 
3996 	ath_start(ifp);
3997 }
3998 
3999 /*
4000  * Deferred processing of transmit interrupt.
4001  */
4002 static void
4003 ath_tx_proc(void *arg, int npending)
4004 {
4005 	struct ath_softc *sc = arg;
4006 	struct ifnet *ifp = sc->sc_ifp;
4007 	int i, nacked;
4008 
4009 	/*
4010 	 * Process each active queue.
4011 	 */
4012 	nacked = 0;
4013 	for (i = 0; i < HAL_NUM_TX_QUEUES; i++)
4014 		if (ATH_TXQ_SETUP(sc, i) && txqactive(sc->sc_ah, i))
4015 			nacked += ath_tx_processq(sc, &sc->sc_txq[i]);
4016 	if (nacked)
4017 		sc->sc_lastrx = ath_hal_gettsf64(sc->sc_ah);
4018 
4019 	ifp->if_drv_flags &= ~IFF_DRV_OACTIVE;
4020 	sc->sc_tx_timer = 0;
4021 
4022 	if (sc->sc_softled)
4023 		ath_led_event(sc, ATH_LED_TX);
4024 
4025 	ath_start(ifp);
4026 }
4027 
4028 static void
4029 ath_tx_draintxq(struct ath_softc *sc, struct ath_txq *txq)
4030 {
4031 #ifdef ATH_DEBUG
4032 	struct ath_hal *ah = sc->sc_ah;
4033 #endif
4034 	struct ieee80211_node *ni;
4035 	struct ath_buf *bf;
4036 	u_int ix;
4037 
4038 	/*
4039 	 * NB: this assumes output has been stopped and
4040 	 *     we do not need to block ath_tx_tasklet
4041 	 */
4042 	for (ix = 0;; ix++) {
4043 		ATH_TXQ_LOCK(txq);
4044 		bf = STAILQ_FIRST(&txq->axq_q);
4045 		if (bf == NULL) {
4046 			txq->axq_link = NULL;
4047 			ATH_TXQ_UNLOCK(txq);
4048 			break;
4049 		}
4050 		ATH_TXQ_REMOVE_HEAD(txq, bf_list);
4051 		ATH_TXQ_UNLOCK(txq);
4052 #ifdef ATH_DEBUG
4053 		if (sc->sc_debug & ATH_DEBUG_RESET) {
4054 			ath_printtxbuf(bf, txq->axq_qnum, ix,
4055 				ath_hal_txprocdesc(ah, bf->bf_desc) == HAL_OK);
4056 			ieee80211_dump_pkt(mtod(bf->bf_m, caddr_t),
4057 				bf->bf_m->m_len, 0, -1);
4058 		}
4059 #endif /* ATH_DEBUG */
4060 		bus_dmamap_unload(sc->sc_dmat, bf->bf_dmamap);
4061 		m_freem(bf->bf_m);
4062 		bf->bf_m = NULL;
4063 		ni = bf->bf_node;
4064 		bf->bf_node = NULL;
4065 		if (ni != NULL) {
4066 			/*
4067 			 * Reclaim node reference.
4068 			 */
4069 			ieee80211_free_node(ni);
4070 		}
4071 		ATH_TXBUF_LOCK(sc);
4072 		STAILQ_INSERT_TAIL(&sc->sc_txbuf, bf, bf_list);
4073 		ATH_TXBUF_UNLOCK(sc);
4074 	}
4075 }
4076 
4077 static void
4078 ath_tx_stopdma(struct ath_softc *sc, struct ath_txq *txq)
4079 {
4080 	struct ath_hal *ah = sc->sc_ah;
4081 
4082 	DPRINTF(sc, ATH_DEBUG_RESET, "%s: tx queue [%u] %p, link %p\n",
4083 	    __func__, txq->axq_qnum,
4084 	    (caddr_t)(uintptr_t) ath_hal_gettxbuf(ah, txq->axq_qnum),
4085 	    txq->axq_link);
4086 	(void) ath_hal_stoptxdma(ah, txq->axq_qnum);
4087 }
4088 
4089 /*
4090  * Drain the transmit queues and reclaim resources.
4091  */
4092 static void
4093 ath_draintxq(struct ath_softc *sc)
4094 {
4095 	struct ath_hal *ah = sc->sc_ah;
4096 	struct ifnet *ifp = sc->sc_ifp;
4097 	int i;
4098 
4099 	/* XXX return value */
4100 	if (!sc->sc_invalid) {
4101 		/* don't touch the hardware if marked invalid */
4102 		DPRINTF(sc, ATH_DEBUG_RESET, "%s: tx queue [%u] %p, link %p\n",
4103 		    __func__, sc->sc_bhalq,
4104 		    (caddr_t)(uintptr_t) ath_hal_gettxbuf(ah, sc->sc_bhalq),
4105 		    NULL);
4106 		(void) ath_hal_stoptxdma(ah, sc->sc_bhalq);
4107 		for (i = 0; i < HAL_NUM_TX_QUEUES; i++)
4108 			if (ATH_TXQ_SETUP(sc, i))
4109 				ath_tx_stopdma(sc, &sc->sc_txq[i]);
4110 	}
4111 	for (i = 0; i < HAL_NUM_TX_QUEUES; i++)
4112 		if (ATH_TXQ_SETUP(sc, i))
4113 			ath_tx_draintxq(sc, &sc->sc_txq[i]);
4114 	ath_tx_draintxq(sc, &sc->sc_mcastq);
4115 #ifdef ATH_DEBUG
4116 	if (sc->sc_debug & ATH_DEBUG_RESET) {
4117 		struct ath_buf *bf = STAILQ_FIRST(&sc->sc_bbuf);
4118 		if (bf != NULL && bf->bf_m != NULL) {
4119 			ath_printtxbuf(bf, sc->sc_bhalq, 0,
4120 				ath_hal_txprocdesc(ah, bf->bf_desc) == HAL_OK);
4121 			ieee80211_dump_pkt(mtod(bf->bf_m, caddr_t),
4122 				bf->bf_m->m_len, 0, -1);
4123 		}
4124 	}
4125 #endif /* ATH_DEBUG */
4126 	ifp->if_drv_flags &= ~IFF_DRV_OACTIVE;
4127 	sc->sc_tx_timer = 0;
4128 }
4129 
4130 /*
4131  * Disable the receive h/w in preparation for a reset.
4132  */
4133 static void
4134 ath_stoprecv(struct ath_softc *sc)
4135 {
4136 #define	PA2DESC(_sc, _pa) \
4137 	((struct ath_desc *)((caddr_t)(_sc)->sc_rxdma.dd_desc + \
4138 		((_pa) - (_sc)->sc_rxdma.dd_desc_paddr)))
4139 	struct ath_hal *ah = sc->sc_ah;
4140 
4141 	ath_hal_stoppcurecv(ah);	/* disable PCU */
4142 	ath_hal_setrxfilter(ah, 0);	/* clear recv filter */
4143 	ath_hal_stopdmarecv(ah);	/* disable DMA engine */
4144 	DELAY(3000);			/* 3ms is long enough for 1 frame */
4145 #ifdef ATH_DEBUG
4146 	if (sc->sc_debug & (ATH_DEBUG_RESET | ATH_DEBUG_FATAL)) {
4147 		struct ath_buf *bf;
4148 		u_int ix;
4149 
4150 		printf("%s: rx queue %p, link %p\n", __func__,
4151 			(caddr_t)(uintptr_t) ath_hal_getrxbuf(ah), sc->sc_rxlink);
4152 		ix = 0;
4153 		STAILQ_FOREACH(bf, &sc->sc_rxbuf, bf_list) {
4154 			struct ath_desc *ds = bf->bf_desc;
4155 			HAL_STATUS status = ath_hal_rxprocdesc(ah, ds,
4156 				bf->bf_daddr, PA2DESC(sc, ds->ds_link));
4157 			if (status == HAL_OK || (sc->sc_debug & ATH_DEBUG_FATAL))
4158 				ath_printrxbuf(bf, ix, status == HAL_OK);
4159 			ix++;
4160 		}
4161 	}
4162 #endif
4163 	sc->sc_rxlink = NULL;		/* just in case */
4164 #undef PA2DESC
4165 }
4166 
4167 /*
4168  * Enable the receive h/w following a reset.
4169  */
4170 static int
4171 ath_startrecv(struct ath_softc *sc)
4172 {
4173 	struct ath_hal *ah = sc->sc_ah;
4174 	struct ath_buf *bf;
4175 
4176 	sc->sc_rxlink = NULL;
4177 	STAILQ_FOREACH(bf, &sc->sc_rxbuf, bf_list) {
4178 		int error = ath_rxbuf_init(sc, bf);
4179 		if (error != 0) {
4180 			DPRINTF(sc, ATH_DEBUG_RECV,
4181 				"%s: ath_rxbuf_init failed %d\n",
4182 				__func__, error);
4183 			return error;
4184 		}
4185 	}
4186 
4187 	bf = STAILQ_FIRST(&sc->sc_rxbuf);
4188 	ath_hal_putrxbuf(ah, bf->bf_daddr);
4189 	ath_hal_rxena(ah);		/* enable recv descriptors */
4190 	ath_mode_init(sc);		/* set filters, etc. */
4191 	ath_hal_startpcurecv(ah);	/* re-enable PCU/DMA engine */
4192 	return 0;
4193 }
4194 
4195 /*
4196  * Update internal state after a channel change.
4197  */
4198 static void
4199 ath_chan_change(struct ath_softc *sc, struct ieee80211_channel *chan)
4200 {
4201 	struct ieee80211com *ic = &sc->sc_ic;
4202 	enum ieee80211_phymode mode;
4203 	u_int16_t flags;
4204 
4205 	/*
4206 	 * Change channels and update the h/w rate map
4207 	 * if we're switching; e.g. 11a to 11b/g.
4208 	 */
4209 	mode = ieee80211_chan2mode(ic, chan);
4210 	if (mode != sc->sc_curmode)
4211 		ath_setcurmode(sc, mode);
4212 	/*
4213 	 * Update BPF state.  NB: ethereal et. al. don't handle
4214 	 * merged flags well so pick a unique mode for their use.
4215 	 */
4216 	if (IEEE80211_IS_CHAN_A(chan))
4217 		flags = IEEE80211_CHAN_A;
4218 	/* XXX 11g schizophrenia */
4219 	else if (IEEE80211_IS_CHAN_G(chan) ||
4220 	    IEEE80211_IS_CHAN_PUREG(chan))
4221 		flags = IEEE80211_CHAN_G;
4222 	else
4223 		flags = IEEE80211_CHAN_B;
4224 	if (IEEE80211_IS_CHAN_T(chan))
4225 		flags |= IEEE80211_CHAN_TURBO;
4226 	sc->sc_tx_th.wt_chan_freq = sc->sc_rx_th.wr_chan_freq =
4227 		htole16(chan->ic_freq);
4228 	sc->sc_tx_th.wt_chan_flags = sc->sc_rx_th.wr_chan_flags =
4229 		htole16(flags);
4230 }
4231 
4232 /*
4233  * Poll for a channel clear indication; this is required
4234  * for channels requiring DFS and not previously visited
4235  * and/or with a recent radar detection.
4236  */
4237 static void
4238 ath_dfswait(void *arg)
4239 {
4240 	struct ath_softc *sc = arg;
4241 	struct ath_hal *ah = sc->sc_ah;
4242 	HAL_CHANNEL hchan;
4243 
4244 	ath_hal_radar_wait(ah, &hchan);
4245 	DPRINTF(sc, ATH_DEBUG_DFS, "%s: radar_wait %u/%x/%x\n",
4246 	    __func__, hchan.channel, hchan.channelFlags, hchan.privFlags);
4247 
4248 	if (hchan.privFlags & CHANNEL_INTERFERENCE) {
4249 		if_printf(sc->sc_ifp,
4250 		    "channel %u/0x%x/0x%x has interference\n",
4251 		    hchan.channel, hchan.channelFlags, hchan.privFlags);
4252 		return;
4253 	}
4254 	if ((hchan.privFlags & CHANNEL_DFS) == 0) {
4255 		/* XXX should not happen */
4256 		return;
4257 	}
4258 	if (hchan.privFlags & CHANNEL_DFS_CLEAR) {
4259 		sc->sc_curchan.privFlags |= CHANNEL_DFS_CLEAR;
4260 		sc->sc_ifp->if_drv_flags &= ~IFF_DRV_OACTIVE;
4261 		if_printf(sc->sc_ifp,
4262 		    "channel %u/0x%x/0x%x marked clear\n",
4263 		    hchan.channel, hchan.channelFlags, hchan.privFlags);
4264 	} else
4265 		callout_reset(&sc->sc_dfs_ch, 2 * hz, ath_dfswait, sc);
4266 }
4267 
4268 /*
4269  * Set/change channels.  If the channel is really being changed,
4270  * it's done by reseting the chip.  To accomplish this we must
4271  * first cleanup any pending DMA, then restart stuff after a la
4272  * ath_init.
4273  */
4274 static int
4275 ath_chan_set(struct ath_softc *sc, struct ieee80211_channel *chan)
4276 {
4277 	struct ath_hal *ah = sc->sc_ah;
4278 	struct ieee80211com *ic = &sc->sc_ic;
4279 	HAL_CHANNEL hchan;
4280 
4281 	/*
4282 	 * Convert to a HAL channel description with
4283 	 * the flags constrained to reflect the current
4284 	 * operating mode.
4285 	 */
4286 	hchan.channel = chan->ic_freq;
4287 	hchan.channelFlags = ath_chan2flags(ic, chan);
4288 
4289 	DPRINTF(sc, ATH_DEBUG_RESET,
4290 	    "%s: %u (%u MHz, hal flags 0x%x) -> %u (%u MHz, hal flags 0x%x)\n",
4291 	    __func__,
4292 	    ath_hal_mhz2ieee(ah, sc->sc_curchan.channel,
4293 		sc->sc_curchan.channelFlags),
4294 	    	sc->sc_curchan.channel, sc->sc_curchan.channelFlags,
4295 	    ath_hal_mhz2ieee(ah, hchan.channel, hchan.channelFlags),
4296 	        hchan.channel, hchan.channelFlags);
4297 	if (hchan.channel != sc->sc_curchan.channel ||
4298 	    hchan.channelFlags != sc->sc_curchan.channelFlags) {
4299 		HAL_STATUS status;
4300 
4301 		/*
4302 		 * To switch channels clear any pending DMA operations;
4303 		 * wait long enough for the RX fifo to drain, reset the
4304 		 * hardware at the new frequency, and then re-enable
4305 		 * the relevant bits of the h/w.
4306 		 */
4307 		ath_hal_intrset(ah, 0);		/* disable interrupts */
4308 		ath_draintxq(sc);		/* clear pending tx frames */
4309 		ath_stoprecv(sc);		/* turn off frame recv */
4310 		if (!ath_hal_reset(ah, sc->sc_opmode, &hchan, AH_TRUE, &status)) {
4311 			if_printf(ic->ic_ifp, "%s: unable to reset "
4312 			    "channel %u (%u Mhz, flags 0x%x hal flags 0x%x)\n",
4313 			    __func__, ieee80211_chan2ieee(ic, chan),
4314 			    chan->ic_freq, chan->ic_flags, hchan.channelFlags);
4315 			return EIO;
4316 		}
4317 		sc->sc_curchan = hchan;
4318 		ath_update_txpow(sc);		/* update tx power state */
4319 		sc->sc_diversity = ath_hal_getdiversity(ah);
4320 		sc->sc_calinterval = 1;
4321 		sc->sc_caltries = 0;
4322 
4323 		/*
4324 		 * Re-enable rx framework.
4325 		 */
4326 		if (ath_startrecv(sc) != 0) {
4327 			if_printf(ic->ic_ifp,
4328 				"%s: unable to restart recv logic\n", __func__);
4329 			return EIO;
4330 		}
4331 
4332 		/*
4333 		 * Change channels and update the h/w rate map
4334 		 * if we're switching; e.g. 11a to 11b/g.
4335 		 */
4336 		ic->ic_ibss_chan = chan;
4337 		ath_chan_change(sc, chan);
4338 
4339 		/*
4340 		 * Handle DFS required waiting period to determine
4341 		 * if channel is clear of radar traffic.
4342 		 */
4343 		if (ic->ic_opmode == IEEE80211_M_HOSTAP) {
4344 #define	DFS_AND_NOT_CLEAR(_c) \
4345 	(((_c)->privFlags & (CHANNEL_DFS | CHANNEL_DFS_CLEAR)) == CHANNEL_DFS)
4346 			if (DFS_AND_NOT_CLEAR(&sc->sc_curchan)) {
4347 				if_printf(sc->sc_ifp,
4348 					"wait for DFS clear channel signal\n");
4349 				/* XXX stop sndq */
4350 				sc->sc_ifp->if_drv_flags |= IFF_DRV_OACTIVE;
4351 				callout_reset(&sc->sc_dfs_ch,
4352 					2 * hz, ath_dfswait, sc);
4353 			} else
4354 				callout_stop(&sc->sc_dfs_ch);
4355 #undef DFS_NOT_CLEAR
4356 		}
4357 
4358 		/*
4359 		 * Re-enable interrupts.
4360 		 */
4361 		ath_hal_intrset(ah, sc->sc_imask);
4362 	}
4363 	return 0;
4364 }
4365 
4366 static void
4367 ath_next_scan(void *arg)
4368 {
4369 	struct ath_softc *sc = arg;
4370 	struct ieee80211com *ic = &sc->sc_ic;
4371 
4372 	if (ic->ic_state == IEEE80211_S_SCAN)
4373 		ieee80211_next_scan(ic);
4374 }
4375 
4376 /*
4377  * Periodically recalibrate the PHY to account
4378  * for temperature/environment changes.
4379  */
4380 static void
4381 ath_calibrate(void *arg)
4382 {
4383 	struct ath_softc *sc = arg;
4384 	struct ath_hal *ah = sc->sc_ah;
4385 	HAL_BOOL iqCalDone;
4386 
4387 	sc->sc_stats.ast_per_cal++;
4388 
4389 	if (ath_hal_getrfgain(ah) == HAL_RFGAIN_NEED_CHANGE) {
4390 		/*
4391 		 * Rfgain is out of bounds, reset the chip
4392 		 * to load new gain values.
4393 		 */
4394 		DPRINTF(sc, ATH_DEBUG_CALIBRATE,
4395 			"%s: rfgain change\n", __func__);
4396 		sc->sc_stats.ast_per_rfgain++;
4397 		ath_reset(sc->sc_ifp);
4398 	}
4399 	if (!ath_hal_calibrate(ah, &sc->sc_curchan, &iqCalDone)) {
4400 		DPRINTF(sc, ATH_DEBUG_ANY,
4401 			"%s: calibration of channel %u failed\n",
4402 			__func__, sc->sc_curchan.channel);
4403 		sc->sc_stats.ast_per_calfail++;
4404 	}
4405 	/*
4406 	 * Calibrate noise floor data again in case of change.
4407 	 */
4408 	ath_hal_process_noisefloor(ah);
4409 	/*
4410 	 * Poll more frequently when the IQ calibration is in
4411 	 * progress to speedup loading the final settings.
4412 	 * We temper this aggressive polling with an exponential
4413 	 * back off after 4 tries up to ath_calinterval.
4414 	 */
4415 	if (iqCalDone || sc->sc_calinterval >= ath_calinterval) {
4416 		sc->sc_caltries = 0;
4417 		sc->sc_calinterval = ath_calinterval;
4418 	} else if (sc->sc_caltries > 4) {
4419 		sc->sc_caltries = 0;
4420 		sc->sc_calinterval <<= 1;
4421 		if (sc->sc_calinterval > ath_calinterval)
4422 			sc->sc_calinterval = ath_calinterval;
4423 	}
4424 	KASSERT(0 < sc->sc_calinterval && sc->sc_calinterval <= ath_calinterval,
4425 		("bad calibration interval %u", sc->sc_calinterval));
4426 
4427 	DPRINTF(sc, ATH_DEBUG_CALIBRATE,
4428 		"%s: next +%u (%siqCalDone tries %u)\n", __func__,
4429 		sc->sc_calinterval, iqCalDone ? "" : "!", sc->sc_caltries);
4430 	sc->sc_caltries++;
4431 	callout_reset(&sc->sc_cal_ch, sc->sc_calinterval * hz,
4432 		ath_calibrate, sc);
4433 }
4434 
4435 static int
4436 ath_newstate(struct ieee80211com *ic, enum ieee80211_state nstate, int arg)
4437 {
4438 	struct ifnet *ifp = ic->ic_ifp;
4439 	struct ath_softc *sc = ifp->if_softc;
4440 	struct ath_hal *ah = sc->sc_ah;
4441 	struct ieee80211_node *ni;
4442 	int i, error;
4443 	const u_int8_t *bssid;
4444 	u_int32_t rfilt;
4445 	static const HAL_LED_STATE leds[] = {
4446 	    HAL_LED_INIT,	/* IEEE80211_S_INIT */
4447 	    HAL_LED_SCAN,	/* IEEE80211_S_SCAN */
4448 	    HAL_LED_AUTH,	/* IEEE80211_S_AUTH */
4449 	    HAL_LED_ASSOC, 	/* IEEE80211_S_ASSOC */
4450 	    HAL_LED_RUN, 	/* IEEE80211_S_RUN */
4451 	};
4452 
4453 	DPRINTF(sc, ATH_DEBUG_STATE, "%s: %s -> %s\n", __func__,
4454 		ieee80211_state_name[ic->ic_state],
4455 		ieee80211_state_name[nstate]);
4456 
4457 	callout_stop(&sc->sc_scan_ch);
4458 	callout_stop(&sc->sc_cal_ch);
4459 	callout_stop(&sc->sc_dfs_ch);
4460 	ath_hal_setledstate(ah, leds[nstate]);	/* set LED */
4461 
4462 	if (nstate == IEEE80211_S_INIT) {
4463 		sc->sc_imask &= ~(HAL_INT_SWBA | HAL_INT_BMISS);
4464 		/*
4465 		 * NB: disable interrupts so we don't rx frames.
4466 		 */
4467 		ath_hal_intrset(ah, sc->sc_imask &~ HAL_INT_GLOBAL);
4468 		/*
4469 		 * Notify the rate control algorithm.
4470 		 */
4471 		ath_rate_newstate(sc, nstate);
4472 		goto done;
4473 	}
4474 	ni = ic->ic_bss;
4475 	error = ath_chan_set(sc, ic->ic_curchan);
4476 	if (error != 0)
4477 		goto bad;
4478 	rfilt = ath_calcrxfilter(sc, nstate);
4479 	if (nstate == IEEE80211_S_SCAN)
4480 		bssid = ifp->if_broadcastaddr;
4481 	else
4482 		bssid = ni->ni_bssid;
4483 	ath_hal_setrxfilter(ah, rfilt);
4484 	DPRINTF(sc, ATH_DEBUG_STATE, "%s: RX filter 0x%x bssid %s\n",
4485 		 __func__, rfilt, ether_sprintf(bssid));
4486 
4487 	if (nstate == IEEE80211_S_RUN && ic->ic_opmode == IEEE80211_M_STA)
4488 		ath_hal_setassocid(ah, bssid, ni->ni_associd);
4489 	else
4490 		ath_hal_setassocid(ah, bssid, 0);
4491 	if (ic->ic_flags & IEEE80211_F_PRIVACY) {
4492 		for (i = 0; i < IEEE80211_WEP_NKID; i++)
4493 			if (ath_hal_keyisvalid(ah, i))
4494 				ath_hal_keysetmac(ah, i, bssid);
4495 	}
4496 
4497 	/*
4498 	 * Notify the rate control algorithm so rates
4499 	 * are setup should ath_beacon_alloc be called.
4500 	 */
4501 	ath_rate_newstate(sc, nstate);
4502 
4503 	if (ic->ic_opmode == IEEE80211_M_MONITOR) {
4504 		/* nothing to do */;
4505 	} else if (nstate == IEEE80211_S_RUN) {
4506 		DPRINTF(sc, ATH_DEBUG_STATE,
4507 			"%s(RUN): ic_flags=0x%08x iv=%d bssid=%s "
4508 			"capinfo=0x%04x chan=%d\n"
4509 			 , __func__
4510 			 , ic->ic_flags
4511 			 , ni->ni_intval
4512 			 , ether_sprintf(ni->ni_bssid)
4513 			 , ni->ni_capinfo
4514 			 , ieee80211_chan2ieee(ic, ic->ic_curchan));
4515 
4516 		switch (ic->ic_opmode) {
4517 		case IEEE80211_M_HOSTAP:
4518 		case IEEE80211_M_IBSS:
4519 			/*
4520 			 * Allocate and setup the beacon frame.
4521 			 *
4522 			 * Stop any previous beacon DMA.  This may be
4523 			 * necessary, for example, when an ibss merge
4524 			 * causes reconfiguration; there will be a state
4525 			 * transition from RUN->RUN that means we may
4526 			 * be called with beacon transmission active.
4527 			 */
4528 			ath_hal_stoptxdma(ah, sc->sc_bhalq);
4529 			ath_beacon_free(sc);
4530 			error = ath_beacon_alloc(sc, ni);
4531 			if (error != 0)
4532 				goto bad;
4533 			/*
4534 			 * If joining an adhoc network defer beacon timer
4535 			 * configuration to the next beacon frame so we
4536 			 * have a current TSF to use.  Otherwise we're
4537 			 * starting an ibss/bss so there's no need to delay.
4538 			 */
4539 			if (ic->ic_opmode == IEEE80211_M_IBSS &&
4540 			    ic->ic_bss->ni_tstamp.tsf != 0)
4541 				sc->sc_syncbeacon = 1;
4542 			else
4543 				ath_beacon_config(sc);
4544 			break;
4545 		case IEEE80211_M_STA:
4546 			/*
4547 			 * Allocate a key cache slot to the station.
4548 			 */
4549 			if ((ic->ic_flags & IEEE80211_F_PRIVACY) == 0 &&
4550 			    sc->sc_hasclrkey &&
4551 			    ni->ni_ucastkey.wk_keyix == IEEE80211_KEYIX_NONE)
4552 				ath_setup_stationkey(ni);
4553 			/*
4554 			 * Defer beacon timer configuration to the next
4555 			 * beacon frame so we have a current TSF to use
4556 			 * (any TSF collected when scanning is likely old).
4557 			 */
4558 			sc->sc_syncbeacon = 1;
4559 			break;
4560 		default:
4561 			break;
4562 		}
4563 
4564 		/*
4565 		 * Let the hal process statistics collected during a
4566 		 * scan so it can provide calibrated noise floor data.
4567 		 */
4568 		ath_hal_process_noisefloor(ah);
4569 		/*
4570 		 * Reset rssi stats; maybe not the best place...
4571 		 */
4572 		sc->sc_halstats.ns_avgbrssi = ATH_RSSI_DUMMY_MARKER;
4573 		sc->sc_halstats.ns_avgrssi = ATH_RSSI_DUMMY_MARKER;
4574 		sc->sc_halstats.ns_avgtxrssi = ATH_RSSI_DUMMY_MARKER;
4575 	} else {
4576 		ath_hal_intrset(ah,
4577 			sc->sc_imask &~ (HAL_INT_SWBA | HAL_INT_BMISS));
4578 		sc->sc_imask &= ~(HAL_INT_SWBA | HAL_INT_BMISS);
4579 	}
4580 done:
4581 	/*
4582 	 * Invoke the parent method to complete the work.
4583 	 */
4584 	error = sc->sc_newstate(ic, nstate, arg);
4585 	/*
4586 	 * Finally, start any timers.
4587 	 */
4588 	if (nstate == IEEE80211_S_RUN) {
4589 		/* start periodic recalibration timer */
4590 		callout_reset(&sc->sc_cal_ch, sc->sc_calinterval * hz,
4591 			ath_calibrate, sc);
4592 	} else if (nstate == IEEE80211_S_SCAN) {
4593 		/* start ap/neighbor scan timer */
4594 		callout_reset(&sc->sc_scan_ch, (ath_dwelltime * hz) / 1000,
4595 			ath_next_scan, sc);
4596 	}
4597 bad:
4598 	return error;
4599 }
4600 
4601 /*
4602  * Allocate a key cache slot to the station so we can
4603  * setup a mapping from key index to node. The key cache
4604  * slot is needed for managing antenna state and for
4605  * compression when stations do not use crypto.  We do
4606  * it uniliaterally here; if crypto is employed this slot
4607  * will be reassigned.
4608  */
4609 static void
4610 ath_setup_stationkey(struct ieee80211_node *ni)
4611 {
4612 	struct ieee80211com *ic = ni->ni_ic;
4613 	struct ath_softc *sc = ic->ic_ifp->if_softc;
4614 	ieee80211_keyix keyix, rxkeyix;
4615 
4616 	if (!ath_key_alloc(ic, &ni->ni_ucastkey, &keyix, &rxkeyix)) {
4617 		/*
4618 		 * Key cache is full; we'll fall back to doing
4619 		 * the more expensive lookup in software.  Note
4620 		 * this also means no h/w compression.
4621 		 */
4622 		/* XXX msg+statistic */
4623 	} else {
4624 		/* XXX locking? */
4625 		ni->ni_ucastkey.wk_keyix = keyix;
4626 		ni->ni_ucastkey.wk_rxkeyix = rxkeyix;
4627 		/* NB: this will create a pass-thru key entry */
4628 		ath_keyset(sc, &ni->ni_ucastkey, ni->ni_macaddr, ic->ic_bss);
4629 	}
4630 }
4631 
4632 /*
4633  * Setup driver-specific state for a newly associated node.
4634  * Note that we're called also on a re-associate, the isnew
4635  * param tells us if this is the first time or not.
4636  */
4637 static void
4638 ath_newassoc(struct ieee80211_node *ni, int isnew)
4639 {
4640 	struct ieee80211com *ic = ni->ni_ic;
4641 	struct ath_softc *sc = ic->ic_ifp->if_softc;
4642 
4643 	ath_rate_newassoc(sc, ATH_NODE(ni), isnew);
4644 	if (isnew &&
4645 	    (ic->ic_flags & IEEE80211_F_PRIVACY) == 0 && sc->sc_hasclrkey) {
4646 		KASSERT(ni->ni_ucastkey.wk_keyix == IEEE80211_KEYIX_NONE,
4647 		    ("new assoc with a unicast key already setup (keyix %u)",
4648 		    ni->ni_ucastkey.wk_keyix));
4649 		ath_setup_stationkey(ni);
4650 	}
4651 }
4652 
4653 static int
4654 ath_getchannels(struct ath_softc *sc, u_int cc,
4655 	HAL_BOOL outdoor, HAL_BOOL xchanmode)
4656 {
4657 #define	COMPAT	(CHANNEL_ALL_NOTURBO|CHANNEL_PASSIVE)
4658 #define IS_CHAN_PUBLIC_SAFETY(_c) \
4659 	(((_c)->channelFlags & CHANNEL_5GHZ) && \
4660 	 ((_c)->channel > 4940 && (_c)->channel < 4990))
4661 	struct ieee80211com *ic = &sc->sc_ic;
4662 	struct ifnet *ifp = sc->sc_ifp;
4663 	struct ath_hal *ah = sc->sc_ah;
4664 	HAL_CHANNEL *chans;
4665 	int i, ix, nchan;
4666 
4667 	chans = malloc(IEEE80211_CHAN_MAX * sizeof(HAL_CHANNEL),
4668 			M_TEMP, M_NOWAIT);
4669 	if (chans == NULL) {
4670 		if_printf(ifp, "unable to allocate channel table\n");
4671 		return ENOMEM;
4672 	}
4673 	if (!ath_hal_init_channels(ah, chans, IEEE80211_CHAN_MAX, &nchan,
4674 	    NULL, 0, NULL,
4675 	    cc, HAL_MODE_ALL, outdoor, xchanmode)) {
4676 		u_int32_t rd;
4677 
4678 		ath_hal_getregdomain(ah, &rd);
4679 		if_printf(ifp, "unable to collect channel list from hal; "
4680 			"regdomain likely %u country code %u\n", rd, cc);
4681 		free(chans, M_TEMP);
4682 		return EINVAL;
4683 	}
4684 
4685 	/*
4686 	 * Convert HAL channels to ieee80211 ones and insert
4687 	 * them in the table according to their channel number.
4688 	 */
4689 	for (i = 0; i < nchan; i++) {
4690 		HAL_CHANNEL *c = &chans[i];
4691 		u_int16_t flags;
4692 
4693 		/*
4694 		 * XXX we're not ready to handle the ieee number mapping
4695 		 * for public safety channels as they overlap with any
4696 		 * 2GHz channels; for now use the non-public safety
4697 		 * numbering which is non-overlapping.
4698 		 */
4699 		if (IS_CHAN_PUBLIC_SAFETY(c))
4700 			ix = (c->channel - 4000) / 5;
4701 		else
4702 			ix = ath_hal_mhz2ieee(ah, c->channel, c->channelFlags);
4703 		if (ix > IEEE80211_CHAN_MAX) {
4704 			if_printf(ifp, "bad hal channel %d (%u/%x) ignored\n",
4705 				ix, c->channel, c->channelFlags);
4706 			continue;
4707 		}
4708 		if (ix < 0) {
4709 			/* XXX can't handle stuff <2400 right now */
4710 			if (bootverbose)
4711 				if_printf(ifp, "hal channel %d (%u/%x) "
4712 				    "cannot be handled; ignored\n",
4713 				    ix, c->channel, c->channelFlags);
4714 			continue;
4715 		}
4716 		/*
4717 		 * Calculate net80211 flags; most are compatible
4718 		 * but some need massaging.  Note the static turbo
4719 		 * conversion can be removed once net80211 is updated
4720 		 * to understand static vs. dynamic turbo.
4721 		 */
4722 		flags = c->channelFlags & COMPAT;
4723 		if (c->channelFlags & CHANNEL_STURBO)
4724 			flags |= IEEE80211_CHAN_TURBO;
4725 		if (ic->ic_channels[ix].ic_freq == 0) {
4726 			ic->ic_channels[ix].ic_freq = c->channel;
4727 			ic->ic_channels[ix].ic_flags = flags;
4728 		} else {
4729 			/* channels overlap; e.g. 11g and 11b */
4730 			ic->ic_channels[ix].ic_flags |= flags;
4731 		}
4732 	}
4733 	free(chans, M_TEMP);
4734 	return 0;
4735 #undef IS_CHAN_PUBLIC_SAFETY
4736 #undef COMPAT
4737 }
4738 
4739 static void
4740 ath_led_done(void *arg)
4741 {
4742 	struct ath_softc *sc = arg;
4743 
4744 	sc->sc_blinking = 0;
4745 }
4746 
4747 /*
4748  * Turn the LED off: flip the pin and then set a timer so no
4749  * update will happen for the specified duration.
4750  */
4751 static void
4752 ath_led_off(void *arg)
4753 {
4754 	struct ath_softc *sc = arg;
4755 
4756 	ath_hal_gpioset(sc->sc_ah, sc->sc_ledpin, !sc->sc_ledon);
4757 	callout_reset(&sc->sc_ledtimer, sc->sc_ledoff, ath_led_done, sc);
4758 }
4759 
4760 /*
4761  * Blink the LED according to the specified on/off times.
4762  */
4763 static void
4764 ath_led_blink(struct ath_softc *sc, int on, int off)
4765 {
4766 	DPRINTF(sc, ATH_DEBUG_LED, "%s: on %u off %u\n", __func__, on, off);
4767 	ath_hal_gpioset(sc->sc_ah, sc->sc_ledpin, sc->sc_ledon);
4768 	sc->sc_blinking = 1;
4769 	sc->sc_ledoff = off;
4770 	callout_reset(&sc->sc_ledtimer, on, ath_led_off, sc);
4771 }
4772 
4773 static void
4774 ath_led_event(struct ath_softc *sc, int event)
4775 {
4776 
4777 	sc->sc_ledevent = ticks;	/* time of last event */
4778 	if (sc->sc_blinking)		/* don't interrupt active blink */
4779 		return;
4780 	switch (event) {
4781 	case ATH_LED_POLL:
4782 		ath_led_blink(sc, sc->sc_hwmap[0].ledon,
4783 			sc->sc_hwmap[0].ledoff);
4784 		break;
4785 	case ATH_LED_TX:
4786 		ath_led_blink(sc, sc->sc_hwmap[sc->sc_txrate].ledon,
4787 			sc->sc_hwmap[sc->sc_txrate].ledoff);
4788 		break;
4789 	case ATH_LED_RX:
4790 		ath_led_blink(sc, sc->sc_hwmap[sc->sc_rxrate].ledon,
4791 			sc->sc_hwmap[sc->sc_rxrate].ledoff);
4792 		break;
4793 	}
4794 }
4795 
4796 static void
4797 ath_update_txpow(struct ath_softc *sc)
4798 {
4799 	struct ieee80211com *ic = &sc->sc_ic;
4800 	struct ath_hal *ah = sc->sc_ah;
4801 	u_int32_t txpow;
4802 
4803 	if (sc->sc_curtxpow != ic->ic_txpowlimit) {
4804 		ath_hal_settxpowlimit(ah, ic->ic_txpowlimit);
4805 		/* read back in case value is clamped */
4806 		ath_hal_gettxpowlimit(ah, &txpow);
4807 		ic->ic_txpowlimit = sc->sc_curtxpow = txpow;
4808 	}
4809 	/*
4810 	 * Fetch max tx power level for status requests.
4811 	 */
4812 	ath_hal_getmaxtxpow(sc->sc_ah, &txpow);
4813 	ic->ic_bss->ni_txpower = txpow;
4814 }
4815 
4816 static void
4817 rate_setup(struct ath_softc *sc,
4818 	const HAL_RATE_TABLE *rt, struct ieee80211_rateset *rs)
4819 {
4820 	int i, maxrates;
4821 
4822 	if (rt->rateCount > IEEE80211_RATE_MAXSIZE) {
4823 		DPRINTF(sc, ATH_DEBUG_ANY,
4824 			"%s: rate table too small (%u > %u)\n",
4825 		       __func__, rt->rateCount, IEEE80211_RATE_MAXSIZE);
4826 		maxrates = IEEE80211_RATE_MAXSIZE;
4827 	} else
4828 		maxrates = rt->rateCount;
4829 	for (i = 0; i < maxrates; i++)
4830 		rs->rs_rates[i] = rt->info[i].dot11Rate;
4831 	rs->rs_nrates = maxrates;
4832 }
4833 
4834 static int
4835 ath_rate_setup(struct ath_softc *sc, u_int mode)
4836 {
4837 	struct ath_hal *ah = sc->sc_ah;
4838 	struct ieee80211com *ic = &sc->sc_ic;
4839 	const HAL_RATE_TABLE *rt;
4840 
4841 	switch (mode) {
4842 	case IEEE80211_MODE_11A:
4843 		rt = ath_hal_getratetable(ah, HAL_MODE_11A);
4844 		break;
4845 	case IEEE80211_MODE_11B:
4846 		rt = ath_hal_getratetable(ah, HAL_MODE_11B);
4847 		break;
4848 	case IEEE80211_MODE_11G:
4849 		rt = ath_hal_getratetable(ah, HAL_MODE_11G);
4850 		break;
4851 	case IEEE80211_MODE_TURBO_A:
4852 		/* XXX until static/dynamic turbo is fixed */
4853 		rt = ath_hal_getratetable(ah, HAL_MODE_TURBO);
4854 		break;
4855 	case IEEE80211_MODE_TURBO_G:
4856 		rt = ath_hal_getratetable(ah, HAL_MODE_108G);
4857 		break;
4858 	default:
4859 		DPRINTF(sc, ATH_DEBUG_ANY, "%s: invalid mode %u\n",
4860 			__func__, mode);
4861 		return 0;
4862 	}
4863 	sc->sc_rates[mode] = rt;
4864 	if (rt != NULL) {
4865 		rate_setup(sc, rt, &ic->ic_sup_rates[mode]);
4866 		return 1;
4867 	} else
4868 		return 0;
4869 }
4870 
4871 static void
4872 ath_setcurmode(struct ath_softc *sc, enum ieee80211_phymode mode)
4873 {
4874 #define	N(a)	(sizeof(a)/sizeof(a[0]))
4875 	/* NB: on/off times from the Atheros NDIS driver, w/ permission */
4876 	static const struct {
4877 		u_int		rate;		/* tx/rx 802.11 rate */
4878 		u_int16_t	timeOn;		/* LED on time (ms) */
4879 		u_int16_t	timeOff;	/* LED off time (ms) */
4880 	} blinkrates[] = {
4881 		{ 108,  40,  10 },
4882 		{  96,  44,  11 },
4883 		{  72,  50,  13 },
4884 		{  48,  57,  14 },
4885 		{  36,  67,  16 },
4886 		{  24,  80,  20 },
4887 		{  22, 100,  25 },
4888 		{  18, 133,  34 },
4889 		{  12, 160,  40 },
4890 		{  10, 200,  50 },
4891 		{   6, 240,  58 },
4892 		{   4, 267,  66 },
4893 		{   2, 400, 100 },
4894 		{   0, 500, 130 },
4895 	};
4896 	const HAL_RATE_TABLE *rt;
4897 	int i, j;
4898 
4899 	memset(sc->sc_rixmap, 0xff, sizeof(sc->sc_rixmap));
4900 	rt = sc->sc_rates[mode];
4901 	KASSERT(rt != NULL, ("no h/w rate set for phy mode %u", mode));
4902 	for (i = 0; i < rt->rateCount; i++)
4903 		sc->sc_rixmap[rt->info[i].dot11Rate & IEEE80211_RATE_VAL] = i;
4904 	memset(sc->sc_hwmap, 0, sizeof(sc->sc_hwmap));
4905 	for (i = 0; i < 32; i++) {
4906 		u_int8_t ix = rt->rateCodeToIndex[i];
4907 		if (ix == 0xff) {
4908 			sc->sc_hwmap[i].ledon = (500 * hz) / 1000;
4909 			sc->sc_hwmap[i].ledoff = (130 * hz) / 1000;
4910 			continue;
4911 		}
4912 		sc->sc_hwmap[i].ieeerate =
4913 			rt->info[ix].dot11Rate & IEEE80211_RATE_VAL;
4914 		sc->sc_hwmap[i].txflags = IEEE80211_RADIOTAP_F_DATAPAD;
4915 		if (rt->info[ix].shortPreamble ||
4916 		    rt->info[ix].phy == IEEE80211_T_OFDM)
4917 			sc->sc_hwmap[i].txflags |= IEEE80211_RADIOTAP_F_SHORTPRE;
4918 		/* NB: receive frames include FCS */
4919 		sc->sc_hwmap[i].rxflags = sc->sc_hwmap[i].txflags |
4920 			IEEE80211_RADIOTAP_F_FCS;
4921 		/* setup blink rate table to avoid per-packet lookup */
4922 		for (j = 0; j < N(blinkrates)-1; j++)
4923 			if (blinkrates[j].rate == sc->sc_hwmap[i].ieeerate)
4924 				break;
4925 		/* NB: this uses the last entry if the rate isn't found */
4926 		/* XXX beware of overlow */
4927 		sc->sc_hwmap[i].ledon = (blinkrates[j].timeOn * hz) / 1000;
4928 		sc->sc_hwmap[i].ledoff = (blinkrates[j].timeOff * hz) / 1000;
4929 	}
4930 	sc->sc_currates = rt;
4931 	sc->sc_curmode = mode;
4932 	/*
4933 	 * All protection frames are transmited at 2Mb/s for
4934 	 * 11g, otherwise at 1Mb/s.
4935 	 */
4936 	if (mode == IEEE80211_MODE_11G)
4937 		sc->sc_protrix = ath_tx_findrix(rt, 2*2);
4938 	else
4939 		sc->sc_protrix = ath_tx_findrix(rt, 2*1);
4940 	/* rate index used to send management frames */
4941 	sc->sc_minrateix = 0;
4942 	/*
4943 	 * Setup multicast rate state.
4944 	 */
4945 	/* XXX layering violation */
4946 	sc->sc_mcastrix = ath_tx_findrix(rt, sc->sc_ic.ic_mcast_rate);
4947 	sc->sc_mcastrate = sc->sc_ic.ic_mcast_rate;
4948 	/* NB: caller is responsible for reseting rate control state */
4949 #undef N
4950 }
4951 
4952 #ifdef ATH_DEBUG
4953 static void
4954 ath_printrxbuf(struct ath_buf *bf, u_int ix, int done)
4955 {
4956 	struct ath_desc *ds;
4957 	int i;
4958 
4959 	for (i = 0, ds = bf->bf_desc; i < bf->bf_nseg; i++, ds++) {
4960 		printf("R[%2u] (DS.V:%p DS.P:%p) L:%08x D:%08x%s\n"
4961 		       "      %08x %08x %08x %08x\n",
4962 		    ix, ds, (struct ath_desc *)bf->bf_daddr + i,
4963 		    ds->ds_link, ds->ds_data,
4964 		    !done ? "" : (ds->ds_rxstat.rs_status == 0) ? " *" : " !",
4965 		    ds->ds_ctl0, ds->ds_ctl1,
4966 		    ds->ds_hw[0], ds->ds_hw[1]);
4967 	}
4968 }
4969 
4970 static void
4971 ath_printtxbuf(struct ath_buf *bf, u_int qnum, u_int ix, int done)
4972 {
4973 	struct ath_desc *ds;
4974 	int i;
4975 
4976 	printf("Q%u[%3u]", qnum, ix);
4977 	for (i = 0, ds = bf->bf_desc; i < bf->bf_nseg; i++, ds++) {
4978 		printf(" (DS.V:%p DS.P:%p) L:%08x D:%08x F:04%x%s\n"
4979 		       "        %08x %08x %08x %08x %08x %08x\n",
4980 		    ds, (struct ath_desc *)bf->bf_daddr + i,
4981 		    ds->ds_link, ds->ds_data, bf->bf_flags,
4982 		    !done ? "" : (ds->ds_txstat.ts_status == 0) ? " *" : " !",
4983 		    ds->ds_ctl0, ds->ds_ctl1,
4984 		    ds->ds_hw[0], ds->ds_hw[1], ds->ds_hw[2], ds->ds_hw[3]);
4985 	}
4986 }
4987 #endif /* ATH_DEBUG */
4988 
4989 static void
4990 ath_watchdog(struct ifnet *ifp)
4991 {
4992 	struct ath_softc *sc = ifp->if_softc;
4993 	struct ieee80211com *ic = &sc->sc_ic;
4994 
4995 	ifp->if_timer = 0;
4996 	if ((ifp->if_drv_flags & IFF_DRV_RUNNING) == 0 || sc->sc_invalid)
4997 		return;
4998 	if (sc->sc_tx_timer) {
4999 		if (--sc->sc_tx_timer == 0) {
5000 			if_printf(ifp, "device timeout\n");
5001 			ath_reset(ifp);
5002 			ifp->if_oerrors++;
5003 			sc->sc_stats.ast_watchdog++;
5004 		} else
5005 			ifp->if_timer = 1;
5006 	}
5007 	ieee80211_watchdog(ic);
5008 }
5009 
5010 #ifdef ATH_DIAGAPI
5011 /*
5012  * Diagnostic interface to the HAL.  This is used by various
5013  * tools to do things like retrieve register contents for
5014  * debugging.  The mechanism is intentionally opaque so that
5015  * it can change frequently w/o concern for compatiblity.
5016  */
5017 static int
5018 ath_ioctl_diag(struct ath_softc *sc, struct ath_diag *ad)
5019 {
5020 	struct ath_hal *ah = sc->sc_ah;
5021 	u_int id = ad->ad_id & ATH_DIAG_ID;
5022 	void *indata = NULL;
5023 	void *outdata = NULL;
5024 	u_int32_t insize = ad->ad_in_size;
5025 	u_int32_t outsize = ad->ad_out_size;
5026 	int error = 0;
5027 
5028 	if (ad->ad_id & ATH_DIAG_IN) {
5029 		/*
5030 		 * Copy in data.
5031 		 */
5032 		indata = malloc(insize, M_TEMP, M_NOWAIT);
5033 		if (indata == NULL) {
5034 			error = ENOMEM;
5035 			goto bad;
5036 		}
5037 		error = copyin(ad->ad_in_data, indata, insize);
5038 		if (error)
5039 			goto bad;
5040 	}
5041 	if (ad->ad_id & ATH_DIAG_DYN) {
5042 		/*
5043 		 * Allocate a buffer for the results (otherwise the HAL
5044 		 * returns a pointer to a buffer where we can read the
5045 		 * results).  Note that we depend on the HAL leaving this
5046 		 * pointer for us to use below in reclaiming the buffer;
5047 		 * may want to be more defensive.
5048 		 */
5049 		outdata = malloc(outsize, M_TEMP, M_NOWAIT);
5050 		if (outdata == NULL) {
5051 			error = ENOMEM;
5052 			goto bad;
5053 		}
5054 	}
5055 	if (ath_hal_getdiagstate(ah, id, indata, insize, &outdata, &outsize)) {
5056 		if (outsize < ad->ad_out_size)
5057 			ad->ad_out_size = outsize;
5058 		if (outdata != NULL)
5059 			error = copyout(outdata, ad->ad_out_data,
5060 					ad->ad_out_size);
5061 	} else {
5062 		error = EINVAL;
5063 	}
5064 bad:
5065 	if ((ad->ad_id & ATH_DIAG_IN) && indata != NULL)
5066 		free(indata, M_TEMP);
5067 	if ((ad->ad_id & ATH_DIAG_DYN) && outdata != NULL)
5068 		free(outdata, M_TEMP);
5069 	return error;
5070 }
5071 #endif /* ATH_DIAGAPI */
5072 
5073 static int
5074 ath_ioctl(struct ifnet *ifp, u_long cmd, caddr_t data)
5075 {
5076 #define	IS_RUNNING(ifp) \
5077 	((ifp->if_flags & IFF_UP) && (ifp->if_drv_flags & IFF_DRV_RUNNING))
5078 	struct ath_softc *sc = ifp->if_softc;
5079 	struct ieee80211com *ic = &sc->sc_ic;
5080 	struct ifreq *ifr = (struct ifreq *)data;
5081 	int error = 0;
5082 
5083 	ATH_LOCK(sc);
5084 	switch (cmd) {
5085 	case SIOCSIFFLAGS:
5086 		if (IS_RUNNING(ifp)) {
5087 			/*
5088 			 * To avoid rescanning another access point,
5089 			 * do not call ath_init() here.  Instead,
5090 			 * only reflect promisc mode settings.
5091 			 */
5092 			ath_mode_init(sc);
5093 		} else if (ifp->if_flags & IFF_UP) {
5094 			/*
5095 			 * Beware of being called during attach/detach
5096 			 * to reset promiscuous mode.  In that case we
5097 			 * will still be marked UP but not RUNNING.
5098 			 * However trying to re-init the interface
5099 			 * is the wrong thing to do as we've already
5100 			 * torn down much of our state.  There's
5101 			 * probably a better way to deal with this.
5102 			 */
5103 			if (!sc->sc_invalid && ic->ic_bss != NULL)
5104 				ath_init(sc);	/* XXX lose error */
5105 		} else
5106 			ath_stop_locked(ifp);
5107 		break;
5108 	case SIOCADDMULTI:
5109 	case SIOCDELMULTI:
5110 		/*
5111 		 * The upper layer has already installed/removed
5112 		 * the multicast address(es), just recalculate the
5113 		 * multicast filter for the card.
5114 		 */
5115 		if (ifp->if_drv_flags & IFF_DRV_RUNNING)
5116 			ath_mode_init(sc);
5117 		break;
5118 	case SIOCGATHSTATS:
5119 		/* NB: embed these numbers to get a consistent view */
5120 		sc->sc_stats.ast_tx_packets = ifp->if_opackets;
5121 		sc->sc_stats.ast_rx_packets = ifp->if_ipackets;
5122 		sc->sc_stats.ast_rx_rssi = ieee80211_getrssi(ic);
5123 		ATH_UNLOCK(sc);
5124 		/*
5125 		 * NB: Drop the softc lock in case of a page fault;
5126 		 * we'll accept any potential inconsisentcy in the
5127 		 * statistics.  The alternative is to copy the data
5128 		 * to a local structure.
5129 		 */
5130 		return copyout(&sc->sc_stats,
5131 				ifr->ifr_data, sizeof (sc->sc_stats));
5132 #ifdef ATH_DIAGAPI
5133 	case SIOCGATHDIAG:
5134 		ATH_UNLOCK(sc);
5135 		error = ath_ioctl_diag(sc, (struct ath_diag *) ifr);
5136 		ATH_LOCK(sc);
5137 		break;
5138 #endif
5139 	default:
5140 		error = ieee80211_ioctl(ic, cmd, data);
5141 		if (error == ENETRESET) {
5142 			if (IS_RUNNING(ifp) &&
5143 			    ic->ic_roaming != IEEE80211_ROAMING_MANUAL)
5144 				ath_init(sc);	/* XXX lose error */
5145 			error = 0;
5146 		}
5147 		if (error == ERESTART)
5148 			error = IS_RUNNING(ifp) ? ath_reset(ifp) : 0;
5149 		break;
5150 	}
5151 	ATH_UNLOCK(sc);
5152 	return error;
5153 #undef IS_RUNNING
5154 }
5155 
5156 static int
5157 ath_sysctl_slottime(SYSCTL_HANDLER_ARGS)
5158 {
5159 	struct ath_softc *sc = arg1;
5160 	u_int slottime = ath_hal_getslottime(sc->sc_ah);
5161 	int error;
5162 
5163 	error = sysctl_handle_int(oidp, &slottime, 0, req);
5164 	if (error || !req->newptr)
5165 		return error;
5166 	return !ath_hal_setslottime(sc->sc_ah, slottime) ? EINVAL : 0;
5167 }
5168 
5169 static int
5170 ath_sysctl_acktimeout(SYSCTL_HANDLER_ARGS)
5171 {
5172 	struct ath_softc *sc = arg1;
5173 	u_int acktimeout = ath_hal_getacktimeout(sc->sc_ah);
5174 	int error;
5175 
5176 	error = sysctl_handle_int(oidp, &acktimeout, 0, req);
5177 	if (error || !req->newptr)
5178 		return error;
5179 	return !ath_hal_setacktimeout(sc->sc_ah, acktimeout) ? EINVAL : 0;
5180 }
5181 
5182 static int
5183 ath_sysctl_ctstimeout(SYSCTL_HANDLER_ARGS)
5184 {
5185 	struct ath_softc *sc = arg1;
5186 	u_int ctstimeout = ath_hal_getctstimeout(sc->sc_ah);
5187 	int error;
5188 
5189 	error = sysctl_handle_int(oidp, &ctstimeout, 0, req);
5190 	if (error || !req->newptr)
5191 		return error;
5192 	return !ath_hal_setctstimeout(sc->sc_ah, ctstimeout) ? EINVAL : 0;
5193 }
5194 
5195 static int
5196 ath_sysctl_softled(SYSCTL_HANDLER_ARGS)
5197 {
5198 	struct ath_softc *sc = arg1;
5199 	int softled = sc->sc_softled;
5200 	int error;
5201 
5202 	error = sysctl_handle_int(oidp, &softled, 0, req);
5203 	if (error || !req->newptr)
5204 		return error;
5205 	softled = (softled != 0);
5206 	if (softled != sc->sc_softled) {
5207 		if (softled) {
5208 			/* NB: handle any sc_ledpin change */
5209 			ath_hal_gpioCfgOutput(sc->sc_ah, sc->sc_ledpin);
5210 			ath_hal_gpioset(sc->sc_ah, sc->sc_ledpin,
5211 				!sc->sc_ledon);
5212 		}
5213 		sc->sc_softled = softled;
5214 	}
5215 	return 0;
5216 }
5217 
5218 static int
5219 ath_sysctl_rxantenna(SYSCTL_HANDLER_ARGS)
5220 {
5221 	struct ath_softc *sc = arg1;
5222 	u_int defantenna = ath_hal_getdefantenna(sc->sc_ah);
5223 	int error;
5224 
5225 	error = sysctl_handle_int(oidp, &defantenna, 0, req);
5226 	if (!error && req->newptr)
5227 		ath_hal_setdefantenna(sc->sc_ah, defantenna);
5228 	return error;
5229 }
5230 
5231 static int
5232 ath_sysctl_diversity(SYSCTL_HANDLER_ARGS)
5233 {
5234 	struct ath_softc *sc = arg1;
5235 	u_int diversity = ath_hal_getdiversity(sc->sc_ah);
5236 	int error;
5237 
5238 	error = sysctl_handle_int(oidp, &diversity, 0, req);
5239 	if (error || !req->newptr)
5240 		return error;
5241 	if (!ath_hal_setdiversity(sc->sc_ah, diversity))
5242 		return EINVAL;
5243 	sc->sc_diversity = diversity;
5244 	return 0;
5245 }
5246 
5247 static int
5248 ath_sysctl_diag(SYSCTL_HANDLER_ARGS)
5249 {
5250 	struct ath_softc *sc = arg1;
5251 	u_int32_t diag;
5252 	int error;
5253 
5254 	if (!ath_hal_getdiag(sc->sc_ah, &diag))
5255 		return EINVAL;
5256 	error = sysctl_handle_int(oidp, &diag, 0, req);
5257 	if (error || !req->newptr)
5258 		return error;
5259 	return !ath_hal_setdiag(sc->sc_ah, diag) ? EINVAL : 0;
5260 }
5261 
5262 static int
5263 ath_sysctl_tpscale(SYSCTL_HANDLER_ARGS)
5264 {
5265 	struct ath_softc *sc = arg1;
5266 	struct ifnet *ifp = sc->sc_ifp;
5267 	u_int32_t scale;
5268 	int error;
5269 
5270 	ath_hal_gettpscale(sc->sc_ah, &scale);
5271 	error = sysctl_handle_int(oidp, &scale, 0, req);
5272 	if (error || !req->newptr)
5273 		return error;
5274 	return !ath_hal_settpscale(sc->sc_ah, scale) ? EINVAL : ath_reset(ifp);
5275 }
5276 
5277 static int
5278 ath_sysctl_tpc(SYSCTL_HANDLER_ARGS)
5279 {
5280 	struct ath_softc *sc = arg1;
5281 	u_int tpc = ath_hal_gettpc(sc->sc_ah);
5282 	int error;
5283 
5284 	error = sysctl_handle_int(oidp, &tpc, 0, req);
5285 	if (error || !req->newptr)
5286 		return error;
5287 	return !ath_hal_settpc(sc->sc_ah, tpc) ? EINVAL : 0;
5288 }
5289 
5290 static int
5291 ath_sysctl_rfkill(SYSCTL_HANDLER_ARGS)
5292 {
5293 	struct ath_softc *sc = arg1;
5294 	struct ath_hal *ah = sc->sc_ah;
5295 	u_int rfkill = ath_hal_getrfkill(ah);
5296 	int error;
5297 
5298 	error = sysctl_handle_int(oidp, &rfkill, 0, req);
5299 	if (error || !req->newptr)
5300 		return error;
5301 	if (rfkill == ath_hal_getrfkill(ah))	/* unchanged */
5302 		return 0;
5303 	if (!ath_hal_setrfkill(ah, rfkill) || ath_reset(sc->sc_ifp) != 0)
5304 		return EINVAL;
5305 	else
5306 		return 0;
5307 }
5308 
5309 static int
5310 ath_sysctl_rfsilent(SYSCTL_HANDLER_ARGS)
5311 {
5312 	struct ath_softc *sc = arg1;
5313 	u_int rfsilent;
5314 	int error;
5315 
5316 	ath_hal_getrfsilent(sc->sc_ah, &rfsilent);
5317 	error = sysctl_handle_int(oidp, &rfsilent, 0, req);
5318 	if (error || !req->newptr)
5319 		return error;
5320 	if (!ath_hal_setrfsilent(sc->sc_ah, rfsilent))
5321 		return EINVAL;
5322 	sc->sc_rfsilentpin = rfsilent & 0x1c;
5323 	sc->sc_rfsilentpol = (rfsilent & 0x2) != 0;
5324 	return 0;
5325 }
5326 
5327 static int
5328 ath_sysctl_regdomain(SYSCTL_HANDLER_ARGS)
5329 {
5330 	struct ath_softc *sc = arg1;
5331 	u_int32_t rd;
5332 	int error;
5333 
5334 	if (!ath_hal_getregdomain(sc->sc_ah, &rd))
5335 		return EINVAL;
5336 	error = sysctl_handle_int(oidp, &rd, 0, req);
5337 	if (error || !req->newptr)
5338 		return error;
5339 	return !ath_hal_setregdomain(sc->sc_ah, rd) ? EINVAL : 0;
5340 }
5341 
5342 static int
5343 ath_sysctl_tpack(SYSCTL_HANDLER_ARGS)
5344 {
5345 	struct ath_softc *sc = arg1;
5346 	u_int32_t tpack;
5347 	int error;
5348 
5349 	ath_hal_gettpack(sc->sc_ah, &tpack);
5350 	error = sysctl_handle_int(oidp, &tpack, 0, req);
5351 	if (error || !req->newptr)
5352 		return error;
5353 	return !ath_hal_settpack(sc->sc_ah, tpack) ? EINVAL : 0;
5354 }
5355 
5356 static int
5357 ath_sysctl_tpcts(SYSCTL_HANDLER_ARGS)
5358 {
5359 	struct ath_softc *sc = arg1;
5360 	u_int32_t tpcts;
5361 	int error;
5362 
5363 	ath_hal_gettpcts(sc->sc_ah, &tpcts);
5364 	error = sysctl_handle_int(oidp, &tpcts, 0, req);
5365 	if (error || !req->newptr)
5366 		return error;
5367 	return !ath_hal_settpcts(sc->sc_ah, tpcts) ? EINVAL : 0;
5368 }
5369 
5370 static void
5371 ath_sysctlattach(struct ath_softc *sc)
5372 {
5373 	struct sysctl_ctx_list *ctx = device_get_sysctl_ctx(sc->sc_dev);
5374 	struct sysctl_oid *tree = device_get_sysctl_tree(sc->sc_dev);
5375 	struct ath_hal *ah = sc->sc_ah;
5376 
5377 	ath_hal_getcountrycode(sc->sc_ah, &sc->sc_countrycode);
5378 	SYSCTL_ADD_INT(ctx, SYSCTL_CHILDREN(tree), OID_AUTO,
5379 		"countrycode", CTLFLAG_RD, &sc->sc_countrycode, 0,
5380 		"EEPROM country code");
5381 	SYSCTL_ADD_PROC(ctx, SYSCTL_CHILDREN(tree), OID_AUTO,
5382 		"regdomain", CTLTYPE_INT | CTLFLAG_RW, sc, 0,
5383 		ath_sysctl_regdomain, "I", "EEPROM regdomain code");
5384 #ifdef	ATH_DEBUG
5385 	sc->sc_debug = ath_debug;
5386 	SYSCTL_ADD_INT(ctx, SYSCTL_CHILDREN(tree), OID_AUTO,
5387 		"debug", CTLFLAG_RW, &sc->sc_debug, 0,
5388 		"control debugging printfs");
5389 #endif
5390 	SYSCTL_ADD_PROC(ctx, SYSCTL_CHILDREN(tree), OID_AUTO,
5391 		"slottime", CTLTYPE_INT | CTLFLAG_RW, sc, 0,
5392 		ath_sysctl_slottime, "I", "802.11 slot time (us)");
5393 	SYSCTL_ADD_PROC(ctx, SYSCTL_CHILDREN(tree), OID_AUTO,
5394 		"acktimeout", CTLTYPE_INT | CTLFLAG_RW, sc, 0,
5395 		ath_sysctl_acktimeout, "I", "802.11 ACK timeout (us)");
5396 	SYSCTL_ADD_PROC(ctx, SYSCTL_CHILDREN(tree), OID_AUTO,
5397 		"ctstimeout", CTLTYPE_INT | CTLFLAG_RW, sc, 0,
5398 		ath_sysctl_ctstimeout, "I", "802.11 CTS timeout (us)");
5399 	SYSCTL_ADD_PROC(ctx, SYSCTL_CHILDREN(tree), OID_AUTO,
5400 		"softled", CTLTYPE_INT | CTLFLAG_RW, sc, 0,
5401 		ath_sysctl_softled, "I", "enable/disable software LED support");
5402 	SYSCTL_ADD_INT(ctx, SYSCTL_CHILDREN(tree), OID_AUTO,
5403 		"ledpin", CTLFLAG_RW, &sc->sc_ledpin, 0,
5404 		"GPIO pin connected to LED");
5405 	SYSCTL_ADD_INT(ctx, SYSCTL_CHILDREN(tree), OID_AUTO,
5406 		"ledon", CTLFLAG_RW, &sc->sc_ledon, 0,
5407 		"setting to turn LED on");
5408 	SYSCTL_ADD_INT(ctx, SYSCTL_CHILDREN(tree), OID_AUTO,
5409 		"ledidle", CTLFLAG_RW, &sc->sc_ledidle, 0,
5410 		"idle time for inactivity LED (ticks)");
5411 	SYSCTL_ADD_INT(ctx, SYSCTL_CHILDREN(tree), OID_AUTO,
5412 		"txantenna", CTLFLAG_RW, &sc->sc_txantenna, 0,
5413 		"tx antenna (0=auto)");
5414 	SYSCTL_ADD_PROC(ctx, SYSCTL_CHILDREN(tree), OID_AUTO,
5415 		"rxantenna", CTLTYPE_INT | CTLFLAG_RW, sc, 0,
5416 		ath_sysctl_rxantenna, "I", "default/rx antenna");
5417 	if (ath_hal_hasdiversity(ah))
5418 		SYSCTL_ADD_PROC(ctx, SYSCTL_CHILDREN(tree), OID_AUTO,
5419 			"diversity", CTLTYPE_INT | CTLFLAG_RW, sc, 0,
5420 			ath_sysctl_diversity, "I", "antenna diversity");
5421 	sc->sc_txintrperiod = ATH_TXINTR_PERIOD;
5422 	SYSCTL_ADD_INT(ctx, SYSCTL_CHILDREN(tree), OID_AUTO,
5423 		"txintrperiod", CTLFLAG_RW, &sc->sc_txintrperiod, 0,
5424 		"tx descriptor batching");
5425 	SYSCTL_ADD_PROC(ctx, SYSCTL_CHILDREN(tree), OID_AUTO,
5426 		"diag", CTLTYPE_INT | CTLFLAG_RW, sc, 0,
5427 		ath_sysctl_diag, "I", "h/w diagnostic control");
5428 	SYSCTL_ADD_PROC(ctx, SYSCTL_CHILDREN(tree), OID_AUTO,
5429 		"tpscale", CTLTYPE_INT | CTLFLAG_RW, sc, 0,
5430 		ath_sysctl_tpscale, "I", "tx power scaling");
5431 	if (ath_hal_hastpc(ah)) {
5432 		SYSCTL_ADD_PROC(ctx, SYSCTL_CHILDREN(tree), OID_AUTO,
5433 			"tpc", CTLTYPE_INT | CTLFLAG_RW, sc, 0,
5434 			ath_sysctl_tpc, "I", "enable/disable per-packet TPC");
5435 		SYSCTL_ADD_PROC(ctx, SYSCTL_CHILDREN(tree), OID_AUTO,
5436 			"tpack", CTLTYPE_INT | CTLFLAG_RW, sc, 0,
5437 			ath_sysctl_tpack, "I", "tx power for ack frames");
5438 		SYSCTL_ADD_PROC(ctx, SYSCTL_CHILDREN(tree), OID_AUTO,
5439 			"tpcts", CTLTYPE_INT | CTLFLAG_RW, sc, 0,
5440 			ath_sysctl_tpcts, "I", "tx power for cts frames");
5441 	}
5442 	if (ath_hal_hasrfsilent(ah)) {
5443 		SYSCTL_ADD_PROC(ctx, SYSCTL_CHILDREN(tree), OID_AUTO,
5444 			"rfsilent", CTLTYPE_INT | CTLFLAG_RW, sc, 0,
5445 			ath_sysctl_rfsilent, "I", "h/w RF silent config");
5446 		SYSCTL_ADD_PROC(ctx, SYSCTL_CHILDREN(tree), OID_AUTO,
5447 			"rfkill", CTLTYPE_INT | CTLFLAG_RW, sc, 0,
5448 			ath_sysctl_rfkill, "I", "enable/disable RF kill switch");
5449 	}
5450 	sc->sc_monpass = HAL_RXERR_DECRYPT | HAL_RXERR_MIC;
5451 	SYSCTL_ADD_INT(ctx, SYSCTL_CHILDREN(tree), OID_AUTO,
5452 		"monpass", CTLFLAG_RW, &sc->sc_monpass, 0,
5453 		"mask of error frames to pass when monitoring");
5454 }
5455 
5456 static void
5457 ath_bpfattach(struct ath_softc *sc)
5458 {
5459 	struct ifnet *ifp = sc->sc_ifp;
5460 
5461 	bpfattach2(ifp, DLT_IEEE802_11_RADIO,
5462 		sizeof(struct ieee80211_frame) + sizeof(sc->sc_tx_th),
5463 		&sc->sc_drvbpf);
5464 	/*
5465 	 * Initialize constant fields.
5466 	 * XXX make header lengths a multiple of 32-bits so subsequent
5467 	 *     headers are properly aligned; this is a kludge to keep
5468 	 *     certain applications happy.
5469 	 *
5470 	 * NB: the channel is setup each time we transition to the
5471 	 *     RUN state to avoid filling it in for each frame.
5472 	 */
5473 	sc->sc_tx_th_len = roundup(sizeof(sc->sc_tx_th), sizeof(u_int32_t));
5474 	sc->sc_tx_th.wt_ihdr.it_len = htole16(sc->sc_tx_th_len);
5475 	sc->sc_tx_th.wt_ihdr.it_present = htole32(ATH_TX_RADIOTAP_PRESENT);
5476 
5477 	sc->sc_rx_th_len = roundup(sizeof(sc->sc_rx_th), sizeof(u_int32_t));
5478 	sc->sc_rx_th.wr_ihdr.it_len = htole16(sc->sc_rx_th_len);
5479 	sc->sc_rx_th.wr_ihdr.it_present = htole32(ATH_RX_RADIOTAP_PRESENT);
5480 }
5481 
5482 /*
5483  * Announce various information on device/driver attach.
5484  */
5485 static void
5486 ath_announce(struct ath_softc *sc)
5487 {
5488 #define	HAL_MODE_DUALBAND	(HAL_MODE_11A|HAL_MODE_11B)
5489 	struct ifnet *ifp = sc->sc_ifp;
5490 	struct ath_hal *ah = sc->sc_ah;
5491 	u_int modes, cc;
5492 
5493 	if_printf(ifp, "mac %d.%d phy %d.%d",
5494 		ah->ah_macVersion, ah->ah_macRev,
5495 		ah->ah_phyRev >> 4, ah->ah_phyRev & 0xf);
5496 	/*
5497 	 * Print radio revision(s).  We check the wireless modes
5498 	 * to avoid falsely printing revs for inoperable parts.
5499 	 * Dual-band radio revs are returned in the 5Ghz rev number.
5500 	 */
5501 	ath_hal_getcountrycode(ah, &cc);
5502 	modes = ath_hal_getwirelessmodes(ah, cc);
5503 	if ((modes & HAL_MODE_DUALBAND) == HAL_MODE_DUALBAND) {
5504 		if (ah->ah_analog5GhzRev && ah->ah_analog2GhzRev)
5505 			printf(" 5ghz radio %d.%d 2ghz radio %d.%d",
5506 				ah->ah_analog5GhzRev >> 4,
5507 				ah->ah_analog5GhzRev & 0xf,
5508 				ah->ah_analog2GhzRev >> 4,
5509 				ah->ah_analog2GhzRev & 0xf);
5510 		else
5511 			printf(" radio %d.%d", ah->ah_analog5GhzRev >> 4,
5512 				ah->ah_analog5GhzRev & 0xf);
5513 	} else
5514 		printf(" radio %d.%d", ah->ah_analog5GhzRev >> 4,
5515 			ah->ah_analog5GhzRev & 0xf);
5516 	printf("\n");
5517 	if (bootverbose) {
5518 		int i;
5519 		for (i = 0; i <= WME_AC_VO; i++) {
5520 			struct ath_txq *txq = sc->sc_ac2q[i];
5521 			if_printf(ifp, "Use hw queue %u for %s traffic\n",
5522 				txq->axq_qnum, ieee80211_wme_acnames[i]);
5523 		}
5524 		if_printf(ifp, "Use hw queue %u for CAB traffic\n",
5525 			sc->sc_cabq->axq_qnum);
5526 		if_printf(ifp, "Use hw queue %u for beacons\n", sc->sc_bhalq);
5527 	}
5528 	if (ath_rxbuf != ATH_RXBUF)
5529 		if_printf(ifp, "using %u rx buffers\n", ath_rxbuf);
5530 	if (ath_txbuf != ATH_TXBUF)
5531 		if_printf(ifp, "using %u tx buffers\n", ath_txbuf);
5532 #undef HAL_MODE_DUALBAND
5533 }
5534