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