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