xref: /freebsd/sys/dev/mwl/if_mwl.c (revision 8d20be1e22095c27faf8fe8b2f0d089739cc742e)
1 /*-
2  * Copyright (c) 2007-2009 Sam Leffler, Errno Consulting
3  * Copyright (c) 2007-2008 Marvell Semiconductor, Inc.
4  * All rights reserved.
5  *
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions
8  * are met:
9  * 1. Redistributions of source code must retain the above copyright
10  *    notice, this list of conditions and the following disclaimer,
11  *    without modification.
12  * 2. Redistributions in binary form must reproduce at minimum a disclaimer
13  *    similar to the "NO WARRANTY" disclaimer below ("Disclaimer") and any
14  *    redistribution must be conditioned upon including a substantially
15  *    similar Disclaimer requirement for further binary redistribution.
16  *
17  * NO WARRANTY
18  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20  * LIMITED TO, THE IMPLIED WARRANTIES OF NONINFRINGEMENT, MERCHANTIBILITY
21  * AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
22  * THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR SPECIAL, EXEMPLARY,
23  * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
24  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
25  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER
26  * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
27  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
28  * THE POSSIBILITY OF SUCH DAMAGES.
29  */
30 
31 #include <sys/cdefs.h>
32 __FBSDID("$FreeBSD$");
33 
34 /*
35  * Driver for the Marvell 88W8363 Wireless LAN controller.
36  */
37 
38 #include "opt_inet.h"
39 #include "opt_mwl.h"
40 #include "opt_wlan.h"
41 
42 #include <sys/param.h>
43 #include <sys/systm.h>
44 #include <sys/sysctl.h>
45 #include <sys/mbuf.h>
46 #include <sys/malloc.h>
47 #include <sys/lock.h>
48 #include <sys/mutex.h>
49 #include <sys/kernel.h>
50 #include <sys/socket.h>
51 #include <sys/sockio.h>
52 #include <sys/errno.h>
53 #include <sys/callout.h>
54 #include <sys/bus.h>
55 #include <sys/endian.h>
56 #include <sys/kthread.h>
57 #include <sys/taskqueue.h>
58 
59 #include <machine/bus.h>
60 
61 #include <net/if.h>
62 #include <net/if_var.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 <net/bpf.h>
71 
72 #include <net80211/ieee80211_var.h>
73 #include <net80211/ieee80211_regdomain.h>
74 
75 #ifdef INET
76 #include <netinet/in.h>
77 #include <netinet/if_ether.h>
78 #endif /* INET */
79 
80 #include <dev/mwl/if_mwlvar.h>
81 #include <dev/mwl/mwldiag.h>
82 
83 /* idiomatic shorthands: MS = mask+shift, SM = shift+mask */
84 #define	MS(v,x)	(((v) & x) >> x##_S)
85 #define	SM(v,x)	(((v) << x##_S) & x)
86 
87 static struct ieee80211vap *mwl_vap_create(struct ieee80211com *,
88 		    const char [IFNAMSIZ], int, enum ieee80211_opmode, int,
89 		    const uint8_t [IEEE80211_ADDR_LEN],
90 		    const uint8_t [IEEE80211_ADDR_LEN]);
91 static void	mwl_vap_delete(struct ieee80211vap *);
92 static int	mwl_setupdma(struct mwl_softc *);
93 static int	mwl_hal_reset(struct mwl_softc *sc);
94 static int	mwl_init_locked(struct mwl_softc *);
95 static void	mwl_init(void *);
96 static void	mwl_stop_locked(struct ifnet *, int);
97 static int	mwl_reset(struct ieee80211vap *, u_long);
98 static void	mwl_stop(struct ifnet *, int);
99 static void	mwl_start(struct ifnet *);
100 static int	mwl_raw_xmit(struct ieee80211_node *, struct mbuf *,
101 			const struct ieee80211_bpf_params *);
102 static int	mwl_media_change(struct ifnet *);
103 static void	mwl_watchdog(void *);
104 static int	mwl_ioctl(struct ifnet *, u_long, caddr_t);
105 static void	mwl_radar_proc(void *, int);
106 static void	mwl_chanswitch_proc(void *, int);
107 static void	mwl_bawatchdog_proc(void *, int);
108 static int	mwl_key_alloc(struct ieee80211vap *,
109 			struct ieee80211_key *,
110 			ieee80211_keyix *, ieee80211_keyix *);
111 static int	mwl_key_delete(struct ieee80211vap *,
112 			const struct ieee80211_key *);
113 static int	mwl_key_set(struct ieee80211vap *, const struct ieee80211_key *,
114 			const uint8_t mac[IEEE80211_ADDR_LEN]);
115 static int	mwl_mode_init(struct mwl_softc *);
116 static void	mwl_update_mcast(struct ifnet *);
117 static void	mwl_update_promisc(struct ifnet *);
118 static void	mwl_updateslot(struct ifnet *);
119 static int	mwl_beacon_setup(struct ieee80211vap *);
120 static void	mwl_beacon_update(struct ieee80211vap *, int);
121 #ifdef MWL_HOST_PS_SUPPORT
122 static void	mwl_update_ps(struct ieee80211vap *, int);
123 static int	mwl_set_tim(struct ieee80211_node *, int);
124 #endif
125 static int	mwl_dma_setup(struct mwl_softc *);
126 static void	mwl_dma_cleanup(struct mwl_softc *);
127 static struct ieee80211_node *mwl_node_alloc(struct ieee80211vap *,
128 		    const uint8_t [IEEE80211_ADDR_LEN]);
129 static void	mwl_node_cleanup(struct ieee80211_node *);
130 static void	mwl_node_drain(struct ieee80211_node *);
131 static void	mwl_node_getsignal(const struct ieee80211_node *,
132 			int8_t *, int8_t *);
133 static void	mwl_node_getmimoinfo(const struct ieee80211_node *,
134 			struct ieee80211_mimo_info *);
135 static int	mwl_rxbuf_init(struct mwl_softc *, struct mwl_rxbuf *);
136 static void	mwl_rx_proc(void *, int);
137 static void	mwl_txq_init(struct mwl_softc *sc, struct mwl_txq *, int);
138 static int	mwl_tx_setup(struct mwl_softc *, int, int);
139 static int	mwl_wme_update(struct ieee80211com *);
140 static void	mwl_tx_cleanupq(struct mwl_softc *, struct mwl_txq *);
141 static void	mwl_tx_cleanup(struct mwl_softc *);
142 static uint16_t	mwl_calcformat(uint8_t rate, const struct ieee80211_node *);
143 static int	mwl_tx_start(struct mwl_softc *, struct ieee80211_node *,
144 			     struct mwl_txbuf *, struct mbuf *);
145 static void	mwl_tx_proc(void *, int);
146 static int	mwl_chan_set(struct mwl_softc *, struct ieee80211_channel *);
147 static void	mwl_draintxq(struct mwl_softc *);
148 static void	mwl_cleartxq(struct mwl_softc *, struct ieee80211vap *);
149 static int	mwl_recv_action(struct ieee80211_node *,
150 			const struct ieee80211_frame *,
151 			const uint8_t *, const uint8_t *);
152 static int	mwl_addba_request(struct ieee80211_node *,
153 			struct ieee80211_tx_ampdu *, int dialogtoken,
154 			int baparamset, int batimeout);
155 static int	mwl_addba_response(struct ieee80211_node *,
156 			struct ieee80211_tx_ampdu *, int status,
157 			int baparamset, int batimeout);
158 static void	mwl_addba_stop(struct ieee80211_node *,
159 			struct ieee80211_tx_ampdu *);
160 static int	mwl_startrecv(struct mwl_softc *);
161 static MWL_HAL_APMODE mwl_getapmode(const struct ieee80211vap *,
162 			struct ieee80211_channel *);
163 static int	mwl_setapmode(struct ieee80211vap *, struct ieee80211_channel*);
164 static void	mwl_scan_start(struct ieee80211com *);
165 static void	mwl_scan_end(struct ieee80211com *);
166 static void	mwl_set_channel(struct ieee80211com *);
167 static int	mwl_peerstadb(struct ieee80211_node *,
168 			int aid, int staid, MWL_HAL_PEERINFO *pi);
169 static int	mwl_localstadb(struct ieee80211vap *);
170 static int	mwl_newstate(struct ieee80211vap *, enum ieee80211_state, int);
171 static int	allocstaid(struct mwl_softc *sc, int aid);
172 static void	delstaid(struct mwl_softc *sc, int staid);
173 static void	mwl_newassoc(struct ieee80211_node *, int);
174 static void	mwl_agestations(void *);
175 static int	mwl_setregdomain(struct ieee80211com *,
176 			struct ieee80211_regdomain *, int,
177 			struct ieee80211_channel []);
178 static void	mwl_getradiocaps(struct ieee80211com *, int, int *,
179 			struct ieee80211_channel []);
180 static int	mwl_getchannels(struct mwl_softc *);
181 
182 static void	mwl_sysctlattach(struct mwl_softc *);
183 static void	mwl_announce(struct mwl_softc *);
184 
185 SYSCTL_NODE(_hw, OID_AUTO, mwl, CTLFLAG_RD, 0, "Marvell driver parameters");
186 
187 static	int mwl_rxdesc = MWL_RXDESC;		/* # rx desc's to allocate */
188 SYSCTL_INT(_hw_mwl, OID_AUTO, rxdesc, CTLFLAG_RW, &mwl_rxdesc,
189 	    0, "rx descriptors allocated");
190 static	int mwl_rxbuf = MWL_RXBUF;		/* # rx buffers to allocate */
191 SYSCTL_INT(_hw_mwl, OID_AUTO, rxbuf, CTLFLAG_RW, &mwl_rxbuf,
192 	    0, "rx buffers allocated");
193 TUNABLE_INT("hw.mwl.rxbuf", &mwl_rxbuf);
194 static	int mwl_txbuf = MWL_TXBUF;		/* # tx buffers to allocate */
195 SYSCTL_INT(_hw_mwl, OID_AUTO, txbuf, CTLFLAG_RW, &mwl_txbuf,
196 	    0, "tx buffers allocated");
197 TUNABLE_INT("hw.mwl.txbuf", &mwl_txbuf);
198 static	int mwl_txcoalesce = 8;		/* # tx packets to q before poking f/w*/
199 SYSCTL_INT(_hw_mwl, OID_AUTO, txcoalesce, CTLFLAG_RW, &mwl_txcoalesce,
200 	    0, "tx buffers to send at once");
201 TUNABLE_INT("hw.mwl.txcoalesce", &mwl_txcoalesce);
202 static	int mwl_rxquota = MWL_RXBUF;		/* # max buffers to process */
203 SYSCTL_INT(_hw_mwl, OID_AUTO, rxquota, CTLFLAG_RW, &mwl_rxquota,
204 	    0, "max rx buffers to process per interrupt");
205 TUNABLE_INT("hw.mwl.rxquota", &mwl_rxquota);
206 static	int mwl_rxdmalow = 3;			/* # min buffers for wakeup */
207 SYSCTL_INT(_hw_mwl, OID_AUTO, rxdmalow, CTLFLAG_RW, &mwl_rxdmalow,
208 	    0, "min free rx buffers before restarting traffic");
209 TUNABLE_INT("hw.mwl.rxdmalow", &mwl_rxdmalow);
210 
211 #ifdef MWL_DEBUG
212 static	int mwl_debug = 0;
213 SYSCTL_INT(_hw_mwl, OID_AUTO, debug, CTLFLAG_RW, &mwl_debug,
214 	    0, "control debugging printfs");
215 TUNABLE_INT("hw.mwl.debug", &mwl_debug);
216 enum {
217 	MWL_DEBUG_XMIT		= 0x00000001,	/* basic xmit operation */
218 	MWL_DEBUG_XMIT_DESC	= 0x00000002,	/* xmit descriptors */
219 	MWL_DEBUG_RECV		= 0x00000004,	/* basic recv operation */
220 	MWL_DEBUG_RECV_DESC	= 0x00000008,	/* recv descriptors */
221 	MWL_DEBUG_RESET		= 0x00000010,	/* reset processing */
222 	MWL_DEBUG_BEACON 	= 0x00000020,	/* beacon handling */
223 	MWL_DEBUG_INTR		= 0x00000040,	/* ISR */
224 	MWL_DEBUG_TX_PROC	= 0x00000080,	/* tx ISR proc */
225 	MWL_DEBUG_RX_PROC	= 0x00000100,	/* rx ISR proc */
226 	MWL_DEBUG_KEYCACHE	= 0x00000200,	/* key cache management */
227 	MWL_DEBUG_STATE		= 0x00000400,	/* 802.11 state transitions */
228 	MWL_DEBUG_NODE		= 0x00000800,	/* node management */
229 	MWL_DEBUG_RECV_ALL	= 0x00001000,	/* trace all frames (beacons) */
230 	MWL_DEBUG_TSO		= 0x00002000,	/* TSO processing */
231 	MWL_DEBUG_AMPDU		= 0x00004000,	/* BA stream handling */
232 	MWL_DEBUG_ANY		= 0xffffffff
233 };
234 #define	IS_BEACON(wh) \
235     ((wh->i_fc[0] & (IEEE80211_FC0_TYPE_MASK|IEEE80211_FC0_SUBTYPE_MASK)) == \
236 	 (IEEE80211_FC0_TYPE_MGT|IEEE80211_FC0_SUBTYPE_BEACON))
237 #define	IFF_DUMPPKTS_RECV(sc, wh) \
238     (((sc->sc_debug & MWL_DEBUG_RECV) && \
239       ((sc->sc_debug & MWL_DEBUG_RECV_ALL) || !IS_BEACON(wh))) || \
240      (sc->sc_ifp->if_flags & (IFF_DEBUG|IFF_LINK2)) == (IFF_DEBUG|IFF_LINK2))
241 #define	IFF_DUMPPKTS_XMIT(sc) \
242 	((sc->sc_debug & MWL_DEBUG_XMIT) || \
243 	 (sc->sc_ifp->if_flags & (IFF_DEBUG|IFF_LINK2)) == (IFF_DEBUG|IFF_LINK2))
244 #define	DPRINTF(sc, m, fmt, ...) do {				\
245 	if (sc->sc_debug & (m))					\
246 		printf(fmt, __VA_ARGS__);			\
247 } while (0)
248 #define	KEYPRINTF(sc, hk, mac) do {				\
249 	if (sc->sc_debug & MWL_DEBUG_KEYCACHE)			\
250 		mwl_keyprint(sc, __func__, hk, mac);		\
251 } while (0)
252 static	void mwl_printrxbuf(const struct mwl_rxbuf *bf, u_int ix);
253 static	void mwl_printtxbuf(const struct mwl_txbuf *bf, u_int qnum, u_int ix);
254 #else
255 #define	IFF_DUMPPKTS_RECV(sc, wh) \
256 	((sc->sc_ifp->if_flags & (IFF_DEBUG|IFF_LINK2)) == (IFF_DEBUG|IFF_LINK2))
257 #define	IFF_DUMPPKTS_XMIT(sc) \
258 	((sc->sc_ifp->if_flags & (IFF_DEBUG|IFF_LINK2)) == (IFF_DEBUG|IFF_LINK2))
259 #define	DPRINTF(sc, m, fmt, ...) do {				\
260 	(void) sc;						\
261 } while (0)
262 #define	KEYPRINTF(sc, k, mac) do {				\
263 	(void) sc;						\
264 } while (0)
265 #endif
266 
267 static MALLOC_DEFINE(M_MWLDEV, "mwldev", "mwl driver dma buffers");
268 
269 /*
270  * Each packet has fixed front matter: a 2-byte length
271  * of the payload, followed by a 4-address 802.11 header
272  * (regardless of the actual header and always w/o any
273  * QoS header).  The payload then follows.
274  */
275 struct mwltxrec {
276 	uint16_t fwlen;
277 	struct ieee80211_frame_addr4 wh;
278 } __packed;
279 
280 /*
281  * Read/Write shorthands for accesses to BAR 0.  Note
282  * that all BAR 1 operations are done in the "hal" and
283  * there should be no reference to them here.
284  */
285 static __inline uint32_t
286 RD4(struct mwl_softc *sc, bus_size_t off)
287 {
288 	return bus_space_read_4(sc->sc_io0t, sc->sc_io0h, off);
289 }
290 
291 static __inline void
292 WR4(struct mwl_softc *sc, bus_size_t off, uint32_t val)
293 {
294 	bus_space_write_4(sc->sc_io0t, sc->sc_io0h, off, val);
295 }
296 
297 int
298 mwl_attach(uint16_t devid, struct mwl_softc *sc)
299 {
300 	struct ifnet *ifp;
301 	struct ieee80211com *ic;
302 	struct mwl_hal *mh;
303 	int error = 0;
304 
305 	DPRINTF(sc, MWL_DEBUG_ANY, "%s: devid 0x%x\n", __func__, devid);
306 
307 	ifp = sc->sc_ifp = if_alloc(IFT_IEEE80211);
308 	if (ifp == NULL) {
309 		device_printf(sc->sc_dev, "cannot if_alloc()\n");
310 		return ENOSPC;
311 	}
312 	ic = ifp->if_l2com;
313 
314 	/*
315 	 * Setup the RX free list lock early, so it can be consistently
316 	 * removed.
317 	 */
318 	MWL_RXFREE_INIT(sc);
319 
320 	/* set these up early for if_printf use */
321 	if_initname(ifp, device_get_name(sc->sc_dev),
322 		device_get_unit(sc->sc_dev));
323 
324 	mh = mwl_hal_attach(sc->sc_dev, devid,
325 	    sc->sc_io1h, sc->sc_io1t, sc->sc_dmat);
326 	if (mh == NULL) {
327 		if_printf(ifp, "unable to attach HAL\n");
328 		error = EIO;
329 		goto bad;
330 	}
331 	sc->sc_mh = mh;
332 	/*
333 	 * Load firmware so we can get setup.  We arbitrarily
334 	 * pick station firmware; we'll re-load firmware as
335 	 * needed so setting up the wrong mode isn't a big deal.
336 	 */
337 	if (mwl_hal_fwload(mh, NULL) != 0) {
338 		if_printf(ifp, "unable to setup builtin firmware\n");
339 		error = EIO;
340 		goto bad1;
341 	}
342 	if (mwl_hal_gethwspecs(mh, &sc->sc_hwspecs) != 0) {
343 		if_printf(ifp, "unable to fetch h/w specs\n");
344 		error = EIO;
345 		goto bad1;
346 	}
347 	error = mwl_getchannels(sc);
348 	if (error != 0)
349 		goto bad1;
350 
351 	sc->sc_txantenna = 0;		/* h/w default */
352 	sc->sc_rxantenna = 0;		/* h/w default */
353 	sc->sc_invalid = 0;		/* ready to go, enable int handling */
354 	sc->sc_ageinterval = MWL_AGEINTERVAL;
355 
356 	/*
357 	 * Allocate tx+rx descriptors and populate the lists.
358 	 * We immediately push the information to the firmware
359 	 * as otherwise it gets upset.
360 	 */
361 	error = mwl_dma_setup(sc);
362 	if (error != 0) {
363 		if_printf(ifp, "failed to setup descriptors: %d\n", error);
364 		goto bad1;
365 	}
366 	error = mwl_setupdma(sc);	/* push to firmware */
367 	if (error != 0)			/* NB: mwl_setupdma prints msg */
368 		goto bad1;
369 
370 	callout_init(&sc->sc_timer, CALLOUT_MPSAFE);
371 	callout_init_mtx(&sc->sc_watchdog, &sc->sc_mtx, 0);
372 
373 	sc->sc_tq = taskqueue_create("mwl_taskq", M_NOWAIT,
374 		taskqueue_thread_enqueue, &sc->sc_tq);
375 	taskqueue_start_threads(&sc->sc_tq, 1, PI_NET,
376 		"%s taskq", ifp->if_xname);
377 
378 	TASK_INIT(&sc->sc_rxtask, 0, mwl_rx_proc, sc);
379 	TASK_INIT(&sc->sc_radartask, 0, mwl_radar_proc, sc);
380 	TASK_INIT(&sc->sc_chanswitchtask, 0, mwl_chanswitch_proc, sc);
381 	TASK_INIT(&sc->sc_bawatchdogtask, 0, mwl_bawatchdog_proc, sc);
382 
383 	/* NB: insure BK queue is the lowest priority h/w queue */
384 	if (!mwl_tx_setup(sc, WME_AC_BK, MWL_WME_AC_BK)) {
385 		if_printf(ifp, "unable to setup xmit queue for %s traffic!\n",
386 			ieee80211_wme_acnames[WME_AC_BK]);
387 		error = EIO;
388 		goto bad2;
389 	}
390 	if (!mwl_tx_setup(sc, WME_AC_BE, MWL_WME_AC_BE) ||
391 	    !mwl_tx_setup(sc, WME_AC_VI, MWL_WME_AC_VI) ||
392 	    !mwl_tx_setup(sc, WME_AC_VO, MWL_WME_AC_VO)) {
393 		/*
394 		 * Not enough hardware tx queues to properly do WME;
395 		 * just punt and assign them all to the same h/w queue.
396 		 * We could do a better job of this if, for example,
397 		 * we allocate queues when we switch from station to
398 		 * AP mode.
399 		 */
400 		if (sc->sc_ac2q[WME_AC_VI] != NULL)
401 			mwl_tx_cleanupq(sc, sc->sc_ac2q[WME_AC_VI]);
402 		if (sc->sc_ac2q[WME_AC_BE] != NULL)
403 			mwl_tx_cleanupq(sc, sc->sc_ac2q[WME_AC_BE]);
404 		sc->sc_ac2q[WME_AC_BE] = sc->sc_ac2q[WME_AC_BK];
405 		sc->sc_ac2q[WME_AC_VI] = sc->sc_ac2q[WME_AC_BK];
406 		sc->sc_ac2q[WME_AC_VO] = sc->sc_ac2q[WME_AC_BK];
407 	}
408 	TASK_INIT(&sc->sc_txtask, 0, mwl_tx_proc, sc);
409 
410 	ifp->if_softc = sc;
411 	ifp->if_flags = IFF_SIMPLEX | IFF_BROADCAST | IFF_MULTICAST;
412 	ifp->if_start = mwl_start;
413 	ifp->if_ioctl = mwl_ioctl;
414 	ifp->if_init = mwl_init;
415 	IFQ_SET_MAXLEN(&ifp->if_snd, ifqmaxlen);
416 	ifp->if_snd.ifq_drv_maxlen = ifqmaxlen;
417 	IFQ_SET_READY(&ifp->if_snd);
418 
419 	ic->ic_ifp = ifp;
420 	/* XXX not right but it's not used anywhere important */
421 	ic->ic_phytype = IEEE80211_T_OFDM;
422 	ic->ic_opmode = IEEE80211_M_STA;
423 	ic->ic_caps =
424 		  IEEE80211_C_STA		/* station mode supported */
425 		| IEEE80211_C_HOSTAP		/* hostap mode */
426 		| IEEE80211_C_MONITOR		/* monitor mode */
427 #if 0
428 		| IEEE80211_C_IBSS		/* ibss, nee adhoc, mode */
429 		| IEEE80211_C_AHDEMO		/* adhoc demo mode */
430 #endif
431 		| IEEE80211_C_MBSS		/* mesh point link mode */
432 		| IEEE80211_C_WDS		/* WDS supported */
433 		| IEEE80211_C_SHPREAMBLE	/* short preamble supported */
434 		| IEEE80211_C_SHSLOT		/* short slot time supported */
435 		| IEEE80211_C_WME		/* WME/WMM supported */
436 		| IEEE80211_C_BURST		/* xmit bursting supported */
437 		| IEEE80211_C_WPA		/* capable of WPA1+WPA2 */
438 		| IEEE80211_C_BGSCAN		/* capable of bg scanning */
439 		| IEEE80211_C_TXFRAG		/* handle tx frags */
440 		| IEEE80211_C_TXPMGT		/* capable of txpow mgt */
441 		| IEEE80211_C_DFS		/* DFS supported */
442 		;
443 
444 	ic->ic_htcaps =
445 		  IEEE80211_HTCAP_SMPS_ENA	/* SM PS mode enabled */
446 		| IEEE80211_HTCAP_CHWIDTH40	/* 40MHz channel width */
447 		| IEEE80211_HTCAP_SHORTGI20	/* short GI in 20MHz */
448 		| IEEE80211_HTCAP_SHORTGI40	/* short GI in 40MHz */
449 		| IEEE80211_HTCAP_RXSTBC_2STREAM/* 1-2 spatial streams */
450 #if MWL_AGGR_SIZE == 7935
451 		| IEEE80211_HTCAP_MAXAMSDU_7935	/* max A-MSDU length */
452 #else
453 		| IEEE80211_HTCAP_MAXAMSDU_3839	/* max A-MSDU length */
454 #endif
455 #if 0
456 		| IEEE80211_HTCAP_PSMP		/* PSMP supported */
457 		| IEEE80211_HTCAP_40INTOLERANT	/* 40MHz intolerant */
458 #endif
459 		/* s/w capabilities */
460 		| IEEE80211_HTC_HT		/* HT operation */
461 		| IEEE80211_HTC_AMPDU		/* tx A-MPDU */
462 		| IEEE80211_HTC_AMSDU		/* tx A-MSDU */
463 		| IEEE80211_HTC_SMPS		/* SMPS available */
464 		;
465 
466 	/*
467 	 * Mark h/w crypto support.
468 	 * XXX no way to query h/w support.
469 	 */
470 	ic->ic_cryptocaps |= IEEE80211_CRYPTO_WEP
471 			  |  IEEE80211_CRYPTO_AES_CCM
472 			  |  IEEE80211_CRYPTO_TKIP
473 			  |  IEEE80211_CRYPTO_TKIPMIC
474 			  ;
475 	/*
476 	 * Transmit requires space in the packet for a special
477 	 * format transmit record and optional padding between
478 	 * this record and the payload.  Ask the net80211 layer
479 	 * to arrange this when encapsulating packets so we can
480 	 * add it efficiently.
481 	 */
482 	ic->ic_headroom = sizeof(struct mwltxrec) -
483 		sizeof(struct ieee80211_frame);
484 
485 	/* call MI attach routine. */
486 	ieee80211_ifattach(ic, sc->sc_hwspecs.macAddr);
487 	ic->ic_setregdomain = mwl_setregdomain;
488 	ic->ic_getradiocaps = mwl_getradiocaps;
489 	/* override default methods */
490 	ic->ic_raw_xmit = mwl_raw_xmit;
491 	ic->ic_newassoc = mwl_newassoc;
492 	ic->ic_updateslot = mwl_updateslot;
493 	ic->ic_update_mcast = mwl_update_mcast;
494 	ic->ic_update_promisc = mwl_update_promisc;
495 	ic->ic_wme.wme_update = mwl_wme_update;
496 
497 	ic->ic_node_alloc = mwl_node_alloc;
498 	sc->sc_node_cleanup = ic->ic_node_cleanup;
499 	ic->ic_node_cleanup = mwl_node_cleanup;
500 	sc->sc_node_drain = ic->ic_node_drain;
501 	ic->ic_node_drain = mwl_node_drain;
502 	ic->ic_node_getsignal = mwl_node_getsignal;
503 	ic->ic_node_getmimoinfo = mwl_node_getmimoinfo;
504 
505 	ic->ic_scan_start = mwl_scan_start;
506 	ic->ic_scan_end = mwl_scan_end;
507 	ic->ic_set_channel = mwl_set_channel;
508 
509 	sc->sc_recv_action = ic->ic_recv_action;
510 	ic->ic_recv_action = mwl_recv_action;
511 	sc->sc_addba_request = ic->ic_addba_request;
512 	ic->ic_addba_request = mwl_addba_request;
513 	sc->sc_addba_response = ic->ic_addba_response;
514 	ic->ic_addba_response = mwl_addba_response;
515 	sc->sc_addba_stop = ic->ic_addba_stop;
516 	ic->ic_addba_stop = mwl_addba_stop;
517 
518 	ic->ic_vap_create = mwl_vap_create;
519 	ic->ic_vap_delete = mwl_vap_delete;
520 
521 	ieee80211_radiotap_attach(ic,
522 	    &sc->sc_tx_th.wt_ihdr, sizeof(sc->sc_tx_th),
523 		MWL_TX_RADIOTAP_PRESENT,
524 	    &sc->sc_rx_th.wr_ihdr, sizeof(sc->sc_rx_th),
525 		MWL_RX_RADIOTAP_PRESENT);
526 	/*
527 	 * Setup dynamic sysctl's now that country code and
528 	 * regdomain are available from the hal.
529 	 */
530 	mwl_sysctlattach(sc);
531 
532 	if (bootverbose)
533 		ieee80211_announce(ic);
534 	mwl_announce(sc);
535 	return 0;
536 bad2:
537 	mwl_dma_cleanup(sc);
538 bad1:
539 	mwl_hal_detach(mh);
540 bad:
541 	MWL_RXFREE_DESTROY(sc);
542 	if_free(ifp);
543 	sc->sc_invalid = 1;
544 	return error;
545 }
546 
547 int
548 mwl_detach(struct mwl_softc *sc)
549 {
550 	struct ifnet *ifp = sc->sc_ifp;
551 	struct ieee80211com *ic = ifp->if_l2com;
552 
553 	DPRINTF(sc, MWL_DEBUG_ANY, "%s: if_flags %x\n",
554 		__func__, ifp->if_flags);
555 
556 	mwl_stop(ifp, 1);
557 	/*
558 	 * NB: the order of these is important:
559 	 * o call the 802.11 layer before detaching the hal to
560 	 *   insure callbacks into the driver to delete global
561 	 *   key cache entries can be handled
562 	 * o reclaim the tx queue data structures after calling
563 	 *   the 802.11 layer as we'll get called back to reclaim
564 	 *   node state and potentially want to use them
565 	 * o to cleanup the tx queues the hal is called, so detach
566 	 *   it last
567 	 * Other than that, it's straightforward...
568 	 */
569 	ieee80211_ifdetach(ic);
570 	callout_drain(&sc->sc_watchdog);
571 	mwl_dma_cleanup(sc);
572 	MWL_RXFREE_DESTROY(sc);
573 	mwl_tx_cleanup(sc);
574 	mwl_hal_detach(sc->sc_mh);
575 	if_free(ifp);
576 
577 	return 0;
578 }
579 
580 /*
581  * MAC address handling for multiple BSS on the same radio.
582  * The first vap uses the MAC address from the EEPROM.  For
583  * subsequent vap's we set the U/L bit (bit 1) in the MAC
584  * address and use the next six bits as an index.
585  */
586 static void
587 assign_address(struct mwl_softc *sc, uint8_t mac[IEEE80211_ADDR_LEN], int clone)
588 {
589 	int i;
590 
591 	if (clone && mwl_hal_ismbsscapable(sc->sc_mh)) {
592 		/* NB: we only do this if h/w supports multiple bssid */
593 		for (i = 0; i < 32; i++)
594 			if ((sc->sc_bssidmask & (1<<i)) == 0)
595 				break;
596 		if (i != 0)
597 			mac[0] |= (i << 2)|0x2;
598 	} else
599 		i = 0;
600 	sc->sc_bssidmask |= 1<<i;
601 	if (i == 0)
602 		sc->sc_nbssid0++;
603 }
604 
605 static void
606 reclaim_address(struct mwl_softc *sc, uint8_t mac[IEEE80211_ADDR_LEN])
607 {
608 	int i = mac[0] >> 2;
609 	if (i != 0 || --sc->sc_nbssid0 == 0)
610 		sc->sc_bssidmask &= ~(1<<i);
611 }
612 
613 static struct ieee80211vap *
614 mwl_vap_create(struct ieee80211com *ic, const char name[IFNAMSIZ], int unit,
615     enum ieee80211_opmode opmode, int flags,
616     const uint8_t bssid[IEEE80211_ADDR_LEN],
617     const uint8_t mac0[IEEE80211_ADDR_LEN])
618 {
619 	struct ifnet *ifp = ic->ic_ifp;
620 	struct mwl_softc *sc = ifp->if_softc;
621 	struct mwl_hal *mh = sc->sc_mh;
622 	struct ieee80211vap *vap, *apvap;
623 	struct mwl_hal_vap *hvap;
624 	struct mwl_vap *mvp;
625 	uint8_t mac[IEEE80211_ADDR_LEN];
626 
627 	IEEE80211_ADDR_COPY(mac, mac0);
628 	switch (opmode) {
629 	case IEEE80211_M_HOSTAP:
630 	case IEEE80211_M_MBSS:
631 		if ((flags & IEEE80211_CLONE_MACADDR) == 0)
632 			assign_address(sc, mac, flags & IEEE80211_CLONE_BSSID);
633 		hvap = mwl_hal_newvap(mh, MWL_HAL_AP, mac);
634 		if (hvap == NULL) {
635 			if ((flags & IEEE80211_CLONE_MACADDR) == 0)
636 				reclaim_address(sc, mac);
637 			return NULL;
638 		}
639 		break;
640 	case IEEE80211_M_STA:
641 		if ((flags & IEEE80211_CLONE_MACADDR) == 0)
642 			assign_address(sc, mac, flags & IEEE80211_CLONE_BSSID);
643 		hvap = mwl_hal_newvap(mh, MWL_HAL_STA, mac);
644 		if (hvap == NULL) {
645 			if ((flags & IEEE80211_CLONE_MACADDR) == 0)
646 				reclaim_address(sc, mac);
647 			return NULL;
648 		}
649 		/* no h/w beacon miss support; always use s/w */
650 		flags |= IEEE80211_CLONE_NOBEACONS;
651 		break;
652 	case IEEE80211_M_WDS:
653 		hvap = NULL;		/* NB: we use associated AP vap */
654 		if (sc->sc_napvaps == 0)
655 			return NULL;	/* no existing AP vap */
656 		break;
657 	case IEEE80211_M_MONITOR:
658 		hvap = NULL;
659 		break;
660 	case IEEE80211_M_IBSS:
661 	case IEEE80211_M_AHDEMO:
662 	default:
663 		return NULL;
664 	}
665 
666 	mvp = (struct mwl_vap *) malloc(sizeof(struct mwl_vap),
667 	    M_80211_VAP, M_NOWAIT | M_ZERO);
668 	if (mvp == NULL) {
669 		if (hvap != NULL) {
670 			mwl_hal_delvap(hvap);
671 			if ((flags & IEEE80211_CLONE_MACADDR) == 0)
672 				reclaim_address(sc, mac);
673 		}
674 		/* XXX msg */
675 		return NULL;
676 	}
677 	mvp->mv_hvap = hvap;
678 	if (opmode == IEEE80211_M_WDS) {
679 		/*
680 		 * WDS vaps must have an associated AP vap; find one.
681 		 * XXX not right.
682 		 */
683 		TAILQ_FOREACH(apvap, &ic->ic_vaps, iv_next)
684 			if (apvap->iv_opmode == IEEE80211_M_HOSTAP) {
685 				mvp->mv_ap_hvap = MWL_VAP(apvap)->mv_hvap;
686 				break;
687 			}
688 		KASSERT(mvp->mv_ap_hvap != NULL, ("no ap vap"));
689 	}
690 	vap = &mvp->mv_vap;
691 	ieee80211_vap_setup(ic, vap, name, unit, opmode, flags, bssid, mac);
692 	if (hvap != NULL)
693 		IEEE80211_ADDR_COPY(vap->iv_myaddr, mac);
694 	/* override with driver methods */
695 	mvp->mv_newstate = vap->iv_newstate;
696 	vap->iv_newstate = mwl_newstate;
697 	vap->iv_max_keyix = 0;	/* XXX */
698 	vap->iv_key_alloc = mwl_key_alloc;
699 	vap->iv_key_delete = mwl_key_delete;
700 	vap->iv_key_set = mwl_key_set;
701 #ifdef MWL_HOST_PS_SUPPORT
702 	if (opmode == IEEE80211_M_HOSTAP || opmode == IEEE80211_M_MBSS) {
703 		vap->iv_update_ps = mwl_update_ps;
704 		mvp->mv_set_tim = vap->iv_set_tim;
705 		vap->iv_set_tim = mwl_set_tim;
706 	}
707 #endif
708 	vap->iv_reset = mwl_reset;
709 	vap->iv_update_beacon = mwl_beacon_update;
710 
711 	/* override max aid so sta's cannot assoc when we're out of sta id's */
712 	vap->iv_max_aid = MWL_MAXSTAID;
713 	/* override default A-MPDU rx parameters */
714 	vap->iv_ampdu_rxmax = IEEE80211_HTCAP_MAXRXAMPDU_64K;
715 	vap->iv_ampdu_density = IEEE80211_HTCAP_MPDUDENSITY_4;
716 
717 	/* complete setup */
718 	ieee80211_vap_attach(vap, mwl_media_change, ieee80211_media_status);
719 
720 	switch (vap->iv_opmode) {
721 	case IEEE80211_M_HOSTAP:
722 	case IEEE80211_M_MBSS:
723 	case IEEE80211_M_STA:
724 		/*
725 		 * Setup sta db entry for local address.
726 		 */
727 		mwl_localstadb(vap);
728 		if (vap->iv_opmode == IEEE80211_M_HOSTAP ||
729 		    vap->iv_opmode == IEEE80211_M_MBSS)
730 			sc->sc_napvaps++;
731 		else
732 			sc->sc_nstavaps++;
733 		break;
734 	case IEEE80211_M_WDS:
735 		sc->sc_nwdsvaps++;
736 		break;
737 	default:
738 		break;
739 	}
740 	/*
741 	 * Setup overall operating mode.
742 	 */
743 	if (sc->sc_napvaps)
744 		ic->ic_opmode = IEEE80211_M_HOSTAP;
745 	else if (sc->sc_nstavaps)
746 		ic->ic_opmode = IEEE80211_M_STA;
747 	else
748 		ic->ic_opmode = opmode;
749 
750 	return vap;
751 }
752 
753 static void
754 mwl_vap_delete(struct ieee80211vap *vap)
755 {
756 	struct mwl_vap *mvp = MWL_VAP(vap);
757 	struct ifnet *parent = vap->iv_ic->ic_ifp;
758 	struct mwl_softc *sc = parent->if_softc;
759 	struct mwl_hal *mh = sc->sc_mh;
760 	struct mwl_hal_vap *hvap = mvp->mv_hvap;
761 	enum ieee80211_opmode opmode = vap->iv_opmode;
762 
763 	/* XXX disallow ap vap delete if WDS still present */
764 	if (parent->if_drv_flags & IFF_DRV_RUNNING) {
765 		/* quiesce h/w while we remove the vap */
766 		mwl_hal_intrset(mh, 0);		/* disable interrupts */
767 	}
768 	ieee80211_vap_detach(vap);
769 	switch (opmode) {
770 	case IEEE80211_M_HOSTAP:
771 	case IEEE80211_M_MBSS:
772 	case IEEE80211_M_STA:
773 		KASSERT(hvap != NULL, ("no hal vap handle"));
774 		(void) mwl_hal_delstation(hvap, vap->iv_myaddr);
775 		mwl_hal_delvap(hvap);
776 		if (opmode == IEEE80211_M_HOSTAP || opmode == IEEE80211_M_MBSS)
777 			sc->sc_napvaps--;
778 		else
779 			sc->sc_nstavaps--;
780 		/* XXX don't do it for IEEE80211_CLONE_MACADDR */
781 		reclaim_address(sc, vap->iv_myaddr);
782 		break;
783 	case IEEE80211_M_WDS:
784 		sc->sc_nwdsvaps--;
785 		break;
786 	default:
787 		break;
788 	}
789 	mwl_cleartxq(sc, vap);
790 	free(mvp, M_80211_VAP);
791 	if (parent->if_drv_flags & IFF_DRV_RUNNING)
792 		mwl_hal_intrset(mh, sc->sc_imask);
793 }
794 
795 void
796 mwl_suspend(struct mwl_softc *sc)
797 {
798 	struct ifnet *ifp = sc->sc_ifp;
799 
800 	DPRINTF(sc, MWL_DEBUG_ANY, "%s: if_flags %x\n",
801 		__func__, ifp->if_flags);
802 
803 	mwl_stop(ifp, 1);
804 }
805 
806 void
807 mwl_resume(struct mwl_softc *sc)
808 {
809 	struct ifnet *ifp = sc->sc_ifp;
810 
811 	DPRINTF(sc, MWL_DEBUG_ANY, "%s: if_flags %x\n",
812 		__func__, ifp->if_flags);
813 
814 	if (ifp->if_flags & IFF_UP)
815 		mwl_init(sc);
816 }
817 
818 void
819 mwl_shutdown(void *arg)
820 {
821 	struct mwl_softc *sc = arg;
822 
823 	mwl_stop(sc->sc_ifp, 1);
824 }
825 
826 /*
827  * Interrupt handler.  Most of the actual processing is deferred.
828  */
829 void
830 mwl_intr(void *arg)
831 {
832 	struct mwl_softc *sc = arg;
833 	struct mwl_hal *mh = sc->sc_mh;
834 	uint32_t status;
835 
836 	if (sc->sc_invalid) {
837 		/*
838 		 * The hardware is not ready/present, don't touch anything.
839 		 * Note this can happen early on if the IRQ is shared.
840 		 */
841 		DPRINTF(sc, MWL_DEBUG_ANY, "%s: invalid; ignored\n", __func__);
842 		return;
843 	}
844 	/*
845 	 * Figure out the reason(s) for the interrupt.
846 	 */
847 	mwl_hal_getisr(mh, &status);		/* NB: clears ISR too */
848 	if (status == 0)			/* must be a shared irq */
849 		return;
850 
851 	DPRINTF(sc, MWL_DEBUG_INTR, "%s: status 0x%x imask 0x%x\n",
852 	    __func__, status, sc->sc_imask);
853 	if (status & MACREG_A2HRIC_BIT_RX_RDY)
854 		taskqueue_enqueue(sc->sc_tq, &sc->sc_rxtask);
855 	if (status & MACREG_A2HRIC_BIT_TX_DONE)
856 		taskqueue_enqueue(sc->sc_tq, &sc->sc_txtask);
857 	if (status & MACREG_A2HRIC_BIT_BA_WATCHDOG)
858 		taskqueue_enqueue(sc->sc_tq, &sc->sc_bawatchdogtask);
859 	if (status & MACREG_A2HRIC_BIT_OPC_DONE)
860 		mwl_hal_cmddone(mh);
861 	if (status & MACREG_A2HRIC_BIT_MAC_EVENT) {
862 		;
863 	}
864 	if (status & MACREG_A2HRIC_BIT_ICV_ERROR) {
865 		/* TKIP ICV error */
866 		sc->sc_stats.mst_rx_badtkipicv++;
867 	}
868 	if (status & MACREG_A2HRIC_BIT_QUEUE_EMPTY) {
869 		/* 11n aggregation queue is empty, re-fill */
870 		;
871 	}
872 	if (status & MACREG_A2HRIC_BIT_QUEUE_FULL) {
873 		;
874 	}
875 	if (status & MACREG_A2HRIC_BIT_RADAR_DETECT) {
876 		/* radar detected, process event */
877 		taskqueue_enqueue(sc->sc_tq, &sc->sc_radartask);
878 	}
879 	if (status & MACREG_A2HRIC_BIT_CHAN_SWITCH) {
880 		/* DFS channel switch */
881 		taskqueue_enqueue(sc->sc_tq, &sc->sc_chanswitchtask);
882 	}
883 }
884 
885 static void
886 mwl_radar_proc(void *arg, int pending)
887 {
888 	struct mwl_softc *sc = arg;
889 	struct ifnet *ifp = sc->sc_ifp;
890 	struct ieee80211com *ic = ifp->if_l2com;
891 
892 	DPRINTF(sc, MWL_DEBUG_ANY, "%s: radar detected, pending %u\n",
893 	    __func__, pending);
894 
895 	sc->sc_stats.mst_radardetect++;
896 	/* XXX stop h/w BA streams? */
897 
898 	IEEE80211_LOCK(ic);
899 	ieee80211_dfs_notify_radar(ic, ic->ic_curchan);
900 	IEEE80211_UNLOCK(ic);
901 }
902 
903 static void
904 mwl_chanswitch_proc(void *arg, int pending)
905 {
906 	struct mwl_softc *sc = arg;
907 	struct ifnet *ifp = sc->sc_ifp;
908 	struct ieee80211com *ic = ifp->if_l2com;
909 
910 	DPRINTF(sc, MWL_DEBUG_ANY, "%s: channel switch notice, pending %u\n",
911 	    __func__, pending);
912 
913 	IEEE80211_LOCK(ic);
914 	sc->sc_csapending = 0;
915 	ieee80211_csa_completeswitch(ic);
916 	IEEE80211_UNLOCK(ic);
917 }
918 
919 static void
920 mwl_bawatchdog(const MWL_HAL_BASTREAM *sp)
921 {
922 	struct ieee80211_node *ni = sp->data[0];
923 
924 	/* send DELBA and drop the stream */
925 	ieee80211_ampdu_stop(ni, sp->data[1], IEEE80211_REASON_UNSPECIFIED);
926 }
927 
928 static void
929 mwl_bawatchdog_proc(void *arg, int pending)
930 {
931 	struct mwl_softc *sc = arg;
932 	struct mwl_hal *mh = sc->sc_mh;
933 	const MWL_HAL_BASTREAM *sp;
934 	uint8_t bitmap, n;
935 
936 	sc->sc_stats.mst_bawatchdog++;
937 
938 	if (mwl_hal_getwatchdogbitmap(mh, &bitmap) != 0) {
939 		DPRINTF(sc, MWL_DEBUG_AMPDU,
940 		    "%s: could not get bitmap\n", __func__);
941 		sc->sc_stats.mst_bawatchdog_failed++;
942 		return;
943 	}
944 	DPRINTF(sc, MWL_DEBUG_AMPDU, "%s: bitmap 0x%x\n", __func__, bitmap);
945 	if (bitmap == 0xff) {
946 		n = 0;
947 		/* disable all ba streams */
948 		for (bitmap = 0; bitmap < 8; bitmap++) {
949 			sp = mwl_hal_bastream_lookup(mh, bitmap);
950 			if (sp != NULL) {
951 				mwl_bawatchdog(sp);
952 				n++;
953 			}
954 		}
955 		if (n == 0) {
956 			DPRINTF(sc, MWL_DEBUG_AMPDU,
957 			    "%s: no BA streams found\n", __func__);
958 			sc->sc_stats.mst_bawatchdog_empty++;
959 		}
960 	} else if (bitmap != 0xaa) {
961 		/* disable a single ba stream */
962 		sp = mwl_hal_bastream_lookup(mh, bitmap);
963 		if (sp != NULL) {
964 			mwl_bawatchdog(sp);
965 		} else {
966 			DPRINTF(sc, MWL_DEBUG_AMPDU,
967 			    "%s: no BA stream %d\n", __func__, bitmap);
968 			sc->sc_stats.mst_bawatchdog_notfound++;
969 		}
970 	}
971 }
972 
973 /*
974  * Convert net80211 channel to a HAL channel.
975  */
976 static void
977 mwl_mapchan(MWL_HAL_CHANNEL *hc, const struct ieee80211_channel *chan)
978 {
979 	hc->channel = chan->ic_ieee;
980 
981 	*(uint32_t *)&hc->channelFlags = 0;
982 	if (IEEE80211_IS_CHAN_2GHZ(chan))
983 		hc->channelFlags.FreqBand = MWL_FREQ_BAND_2DOT4GHZ;
984 	else if (IEEE80211_IS_CHAN_5GHZ(chan))
985 		hc->channelFlags.FreqBand = MWL_FREQ_BAND_5GHZ;
986 	if (IEEE80211_IS_CHAN_HT40(chan)) {
987 		hc->channelFlags.ChnlWidth = MWL_CH_40_MHz_WIDTH;
988 		if (IEEE80211_IS_CHAN_HT40U(chan))
989 			hc->channelFlags.ExtChnlOffset = MWL_EXT_CH_ABOVE_CTRL_CH;
990 		else
991 			hc->channelFlags.ExtChnlOffset = MWL_EXT_CH_BELOW_CTRL_CH;
992 	} else
993 		hc->channelFlags.ChnlWidth = MWL_CH_20_MHz_WIDTH;
994 	/* XXX 10MHz channels */
995 }
996 
997 /*
998  * Inform firmware of our tx/rx dma setup.  The BAR 0
999  * writes below are for compatibility with older firmware.
1000  * For current firmware we send this information with a
1001  * cmd block via mwl_hal_sethwdma.
1002  */
1003 static int
1004 mwl_setupdma(struct mwl_softc *sc)
1005 {
1006 	int error, i;
1007 
1008 	sc->sc_hwdma.rxDescRead = sc->sc_rxdma.dd_desc_paddr;
1009 	WR4(sc, sc->sc_hwspecs.rxDescRead, sc->sc_hwdma.rxDescRead);
1010 	WR4(sc, sc->sc_hwspecs.rxDescWrite, sc->sc_hwdma.rxDescRead);
1011 
1012 	for (i = 0; i < MWL_NUM_TX_QUEUES-MWL_NUM_ACK_QUEUES; i++) {
1013 		struct mwl_txq *txq = &sc->sc_txq[i];
1014 		sc->sc_hwdma.wcbBase[i] = txq->dma.dd_desc_paddr;
1015 		WR4(sc, sc->sc_hwspecs.wcbBase[i], sc->sc_hwdma.wcbBase[i]);
1016 	}
1017 	sc->sc_hwdma.maxNumTxWcb = mwl_txbuf;
1018 	sc->sc_hwdma.maxNumWCB = MWL_NUM_TX_QUEUES-MWL_NUM_ACK_QUEUES;
1019 
1020 	error = mwl_hal_sethwdma(sc->sc_mh, &sc->sc_hwdma);
1021 	if (error != 0) {
1022 		device_printf(sc->sc_dev,
1023 		    "unable to setup tx/rx dma; hal status %u\n", error);
1024 		/* XXX */
1025 	}
1026 	return error;
1027 }
1028 
1029 /*
1030  * Inform firmware of tx rate parameters.
1031  * Called after a channel change.
1032  */
1033 static int
1034 mwl_setcurchanrates(struct mwl_softc *sc)
1035 {
1036 	struct ifnet *ifp = sc->sc_ifp;
1037 	struct ieee80211com *ic = ifp->if_l2com;
1038 	const struct ieee80211_rateset *rs;
1039 	MWL_HAL_TXRATE rates;
1040 
1041 	memset(&rates, 0, sizeof(rates));
1042 	rs = ieee80211_get_suprates(ic, ic->ic_curchan);
1043 	/* rate used to send management frames */
1044 	rates.MgtRate = rs->rs_rates[0] & IEEE80211_RATE_VAL;
1045 	/* rate used to send multicast frames */
1046 	rates.McastRate = rates.MgtRate;
1047 
1048 	return mwl_hal_settxrate_auto(sc->sc_mh, &rates);
1049 }
1050 
1051 /*
1052  * Inform firmware of tx rate parameters.  Called whenever
1053  * user-settable params change and after a channel change.
1054  */
1055 static int
1056 mwl_setrates(struct ieee80211vap *vap)
1057 {
1058 	struct mwl_vap *mvp = MWL_VAP(vap);
1059 	struct ieee80211_node *ni = vap->iv_bss;
1060 	const struct ieee80211_txparam *tp = ni->ni_txparms;
1061 	MWL_HAL_TXRATE rates;
1062 
1063 	KASSERT(vap->iv_state == IEEE80211_S_RUN, ("state %d", vap->iv_state));
1064 
1065 	/*
1066 	 * Update the h/w rate map.
1067 	 * NB: 0x80 for MCS is passed through unchanged
1068 	 */
1069 	memset(&rates, 0, sizeof(rates));
1070 	/* rate used to send management frames */
1071 	rates.MgtRate = tp->mgmtrate;
1072 	/* rate used to send multicast frames */
1073 	rates.McastRate = tp->mcastrate;
1074 
1075 	/* while here calculate EAPOL fixed rate cookie */
1076 	mvp->mv_eapolformat = htole16(mwl_calcformat(rates.MgtRate, ni));
1077 
1078 	return mwl_hal_settxrate(mvp->mv_hvap,
1079 	    tp->ucastrate != IEEE80211_FIXED_RATE_NONE ?
1080 		RATE_FIXED : RATE_AUTO, &rates);
1081 }
1082 
1083 /*
1084  * Setup a fixed xmit rate cookie for EAPOL frames.
1085  */
1086 static void
1087 mwl_seteapolformat(struct ieee80211vap *vap)
1088 {
1089 	struct mwl_vap *mvp = MWL_VAP(vap);
1090 	struct ieee80211_node *ni = vap->iv_bss;
1091 	enum ieee80211_phymode mode;
1092 	uint8_t rate;
1093 
1094 	KASSERT(vap->iv_state == IEEE80211_S_RUN, ("state %d", vap->iv_state));
1095 
1096 	mode = ieee80211_chan2mode(ni->ni_chan);
1097 	/*
1098 	 * Use legacy rates when operating a mixed HT+non-HT bss.
1099 	 * NB: this may violate POLA for sta and wds vap's.
1100 	 */
1101 	if (mode == IEEE80211_MODE_11NA &&
1102 	    (vap->iv_flags_ht & IEEE80211_FHT_PUREN) == 0)
1103 		rate = vap->iv_txparms[IEEE80211_MODE_11A].mgmtrate;
1104 	else if (mode == IEEE80211_MODE_11NG &&
1105 	    (vap->iv_flags_ht & IEEE80211_FHT_PUREN) == 0)
1106 		rate = vap->iv_txparms[IEEE80211_MODE_11G].mgmtrate;
1107 	else
1108 		rate = vap->iv_txparms[mode].mgmtrate;
1109 
1110 	mvp->mv_eapolformat = htole16(mwl_calcformat(rate, ni));
1111 }
1112 
1113 /*
1114  * Map SKU+country code to region code for radar bin'ing.
1115  */
1116 static int
1117 mwl_map2regioncode(const struct ieee80211_regdomain *rd)
1118 {
1119 	switch (rd->regdomain) {
1120 	case SKU_FCC:
1121 	case SKU_FCC3:
1122 		return DOMAIN_CODE_FCC;
1123 	case SKU_CA:
1124 		return DOMAIN_CODE_IC;
1125 	case SKU_ETSI:
1126 	case SKU_ETSI2:
1127 	case SKU_ETSI3:
1128 		if (rd->country == CTRY_SPAIN)
1129 			return DOMAIN_CODE_SPAIN;
1130 		if (rd->country == CTRY_FRANCE || rd->country == CTRY_FRANCE2)
1131 			return DOMAIN_CODE_FRANCE;
1132 		/* XXX force 1.3.1 radar type */
1133 		return DOMAIN_CODE_ETSI_131;
1134 	case SKU_JAPAN:
1135 		return DOMAIN_CODE_MKK;
1136 	case SKU_ROW:
1137 		return DOMAIN_CODE_DGT;	/* Taiwan */
1138 	case SKU_APAC:
1139 	case SKU_APAC2:
1140 	case SKU_APAC3:
1141 		return DOMAIN_CODE_AUS;	/* Australia */
1142 	}
1143 	/* XXX KOREA? */
1144 	return DOMAIN_CODE_FCC;			/* XXX? */
1145 }
1146 
1147 static int
1148 mwl_hal_reset(struct mwl_softc *sc)
1149 {
1150 	struct ifnet *ifp = sc->sc_ifp;
1151 	struct ieee80211com *ic = ifp->if_l2com;
1152 	struct mwl_hal *mh = sc->sc_mh;
1153 
1154 	mwl_hal_setantenna(mh, WL_ANTENNATYPE_RX, sc->sc_rxantenna);
1155 	mwl_hal_setantenna(mh, WL_ANTENNATYPE_TX, sc->sc_txantenna);
1156 	mwl_hal_setradio(mh, 1, WL_AUTO_PREAMBLE);
1157 	mwl_hal_setwmm(sc->sc_mh, (ic->ic_flags & IEEE80211_F_WME) != 0);
1158 	mwl_chan_set(sc, ic->ic_curchan);
1159 	/* NB: RF/RA performance tuned for indoor mode */
1160 	mwl_hal_setrateadaptmode(mh, 0);
1161 	mwl_hal_setoptimizationlevel(mh,
1162 	    (ic->ic_flags & IEEE80211_F_BURST) != 0);
1163 
1164 	mwl_hal_setregioncode(mh, mwl_map2regioncode(&ic->ic_regdomain));
1165 
1166 	mwl_hal_setaggampduratemode(mh, 1, 80);		/* XXX */
1167 	mwl_hal_setcfend(mh, 0);			/* XXX */
1168 
1169 	return 1;
1170 }
1171 
1172 static int
1173 mwl_init_locked(struct mwl_softc *sc)
1174 {
1175 	struct ifnet *ifp = sc->sc_ifp;
1176 	struct mwl_hal *mh = sc->sc_mh;
1177 	int error = 0;
1178 
1179 	DPRINTF(sc, MWL_DEBUG_ANY, "%s: if_flags 0x%x\n",
1180 		__func__, ifp->if_flags);
1181 
1182 	MWL_LOCK_ASSERT(sc);
1183 
1184 	/*
1185 	 * Stop anything previously setup.  This is safe
1186 	 * whether this is the first time through or not.
1187 	 */
1188 	mwl_stop_locked(ifp, 0);
1189 
1190 	/*
1191 	 * Push vap-independent state to the firmware.
1192 	 */
1193 	if (!mwl_hal_reset(sc)) {
1194 		if_printf(ifp, "unable to reset hardware\n");
1195 		return EIO;
1196 	}
1197 
1198 	/*
1199 	 * Setup recv (once); transmit is already good to go.
1200 	 */
1201 	error = mwl_startrecv(sc);
1202 	if (error != 0) {
1203 		if_printf(ifp, "unable to start recv logic\n");
1204 		return error;
1205 	}
1206 
1207 	/*
1208 	 * Enable interrupts.
1209 	 */
1210 	sc->sc_imask = MACREG_A2HRIC_BIT_RX_RDY
1211 		     | MACREG_A2HRIC_BIT_TX_DONE
1212 		     | MACREG_A2HRIC_BIT_OPC_DONE
1213 #if 0
1214 		     | MACREG_A2HRIC_BIT_MAC_EVENT
1215 #endif
1216 		     | MACREG_A2HRIC_BIT_ICV_ERROR
1217 		     | MACREG_A2HRIC_BIT_RADAR_DETECT
1218 		     | MACREG_A2HRIC_BIT_CHAN_SWITCH
1219 #if 0
1220 		     | MACREG_A2HRIC_BIT_QUEUE_EMPTY
1221 #endif
1222 		     | MACREG_A2HRIC_BIT_BA_WATCHDOG
1223 		     | MACREQ_A2HRIC_BIT_TX_ACK
1224 		     ;
1225 
1226 	ifp->if_drv_flags |= IFF_DRV_RUNNING;
1227 	mwl_hal_intrset(mh, sc->sc_imask);
1228 	callout_reset(&sc->sc_watchdog, hz, mwl_watchdog, sc);
1229 
1230 	return 0;
1231 }
1232 
1233 static void
1234 mwl_init(void *arg)
1235 {
1236 	struct mwl_softc *sc = arg;
1237 	struct ifnet *ifp = sc->sc_ifp;
1238 	struct ieee80211com *ic = ifp->if_l2com;
1239 	int error = 0;
1240 
1241 	DPRINTF(sc, MWL_DEBUG_ANY, "%s: if_flags 0x%x\n",
1242 		__func__, ifp->if_flags);
1243 
1244 	MWL_LOCK(sc);
1245 	error = mwl_init_locked(sc);
1246 	MWL_UNLOCK(sc);
1247 
1248 	if (error == 0)
1249 		ieee80211_start_all(ic);	/* start all vap's */
1250 }
1251 
1252 static void
1253 mwl_stop_locked(struct ifnet *ifp, int disable)
1254 {
1255 	struct mwl_softc *sc = ifp->if_softc;
1256 
1257 	DPRINTF(sc, MWL_DEBUG_ANY, "%s: invalid %u if_flags 0x%x\n",
1258 		__func__, sc->sc_invalid, ifp->if_flags);
1259 
1260 	MWL_LOCK_ASSERT(sc);
1261 	if (ifp->if_drv_flags & IFF_DRV_RUNNING) {
1262 		/*
1263 		 * Shutdown the hardware and driver.
1264 		 */
1265 		ifp->if_drv_flags &= ~IFF_DRV_RUNNING;
1266 		callout_stop(&sc->sc_watchdog);
1267 		sc->sc_tx_timer = 0;
1268 		mwl_draintxq(sc);
1269 	}
1270 }
1271 
1272 static void
1273 mwl_stop(struct ifnet *ifp, int disable)
1274 {
1275 	struct mwl_softc *sc = ifp->if_softc;
1276 
1277 	MWL_LOCK(sc);
1278 	mwl_stop_locked(ifp, disable);
1279 	MWL_UNLOCK(sc);
1280 }
1281 
1282 static int
1283 mwl_reset_vap(struct ieee80211vap *vap, int state)
1284 {
1285 	struct mwl_hal_vap *hvap = MWL_VAP(vap)->mv_hvap;
1286 	struct ieee80211com *ic = vap->iv_ic;
1287 
1288 	if (state == IEEE80211_S_RUN)
1289 		mwl_setrates(vap);
1290 	/* XXX off by 1? */
1291 	mwl_hal_setrtsthreshold(hvap, vap->iv_rtsthreshold);
1292 	/* XXX auto? 20/40 split? */
1293 	mwl_hal_sethtgi(hvap, (vap->iv_flags_ht &
1294 	    (IEEE80211_FHT_SHORTGI20|IEEE80211_FHT_SHORTGI40)) ? 1 : 0);
1295 	mwl_hal_setnprot(hvap, ic->ic_htprotmode == IEEE80211_PROT_NONE ?
1296 	    HTPROTECT_NONE : HTPROTECT_AUTO);
1297 	/* XXX txpower cap */
1298 
1299 	/* re-setup beacons */
1300 	if (state == IEEE80211_S_RUN &&
1301 	    (vap->iv_opmode == IEEE80211_M_HOSTAP ||
1302 	     vap->iv_opmode == IEEE80211_M_MBSS ||
1303 	     vap->iv_opmode == IEEE80211_M_IBSS)) {
1304 		mwl_setapmode(vap, vap->iv_bss->ni_chan);
1305 		mwl_hal_setnprotmode(hvap,
1306 		    MS(ic->ic_curhtprotmode, IEEE80211_HTINFO_OPMODE));
1307 		return mwl_beacon_setup(vap);
1308 	}
1309 	return 0;
1310 }
1311 
1312 /*
1313  * Reset the hardware w/o losing operational state.
1314  * Used to to reset or reload hardware state for a vap.
1315  */
1316 static int
1317 mwl_reset(struct ieee80211vap *vap, u_long cmd)
1318 {
1319 	struct mwl_hal_vap *hvap = MWL_VAP(vap)->mv_hvap;
1320 	int error = 0;
1321 
1322 	if (hvap != NULL) {			/* WDS, MONITOR, etc. */
1323 		struct ieee80211com *ic = vap->iv_ic;
1324 		struct ifnet *ifp = ic->ic_ifp;
1325 		struct mwl_softc *sc = ifp->if_softc;
1326 		struct mwl_hal *mh = sc->sc_mh;
1327 
1328 		/* XXX handle DWDS sta vap change */
1329 		/* XXX do we need to disable interrupts? */
1330 		mwl_hal_intrset(mh, 0);		/* disable interrupts */
1331 		error = mwl_reset_vap(vap, vap->iv_state);
1332 		mwl_hal_intrset(mh, sc->sc_imask);
1333 	}
1334 	return error;
1335 }
1336 
1337 /*
1338  * Allocate a tx buffer for sending a frame.  The
1339  * packet is assumed to have the WME AC stored so
1340  * we can use it to select the appropriate h/w queue.
1341  */
1342 static struct mwl_txbuf *
1343 mwl_gettxbuf(struct mwl_softc *sc, struct mwl_txq *txq)
1344 {
1345 	struct mwl_txbuf *bf;
1346 
1347 	/*
1348 	 * Grab a TX buffer and associated resources.
1349 	 */
1350 	MWL_TXQ_LOCK(txq);
1351 	bf = STAILQ_FIRST(&txq->free);
1352 	if (bf != NULL) {
1353 		STAILQ_REMOVE_HEAD(&txq->free, bf_list);
1354 		txq->nfree--;
1355 	}
1356 	MWL_TXQ_UNLOCK(txq);
1357 	if (bf == NULL)
1358 		DPRINTF(sc, MWL_DEBUG_XMIT,
1359 		    "%s: out of xmit buffers on q %d\n", __func__, txq->qnum);
1360 	return bf;
1361 }
1362 
1363 /*
1364  * Return a tx buffer to the queue it came from.  Note there
1365  * are two cases because we must preserve the order of buffers
1366  * as it reflects the fixed order of descriptors in memory
1367  * (the firmware pre-fetches descriptors so we cannot reorder).
1368  */
1369 static void
1370 mwl_puttxbuf_head(struct mwl_txq *txq, struct mwl_txbuf *bf)
1371 {
1372 	bf->bf_m = NULL;
1373 	bf->bf_node = NULL;
1374 	MWL_TXQ_LOCK(txq);
1375 	STAILQ_INSERT_HEAD(&txq->free, bf, bf_list);
1376 	txq->nfree++;
1377 	MWL_TXQ_UNLOCK(txq);
1378 }
1379 
1380 static void
1381 mwl_puttxbuf_tail(struct mwl_txq *txq, struct mwl_txbuf *bf)
1382 {
1383 	bf->bf_m = NULL;
1384 	bf->bf_node = NULL;
1385 	MWL_TXQ_LOCK(txq);
1386 	STAILQ_INSERT_TAIL(&txq->free, bf, bf_list);
1387 	txq->nfree++;
1388 	MWL_TXQ_UNLOCK(txq);
1389 }
1390 
1391 static void
1392 mwl_start(struct ifnet *ifp)
1393 {
1394 	struct mwl_softc *sc = ifp->if_softc;
1395 	struct ieee80211_node *ni;
1396 	struct mwl_txbuf *bf;
1397 	struct mbuf *m;
1398 	struct mwl_txq *txq = NULL;	/* XXX silence gcc */
1399 	int nqueued;
1400 
1401 	if ((ifp->if_drv_flags & IFF_DRV_RUNNING) == 0 || sc->sc_invalid)
1402 		return;
1403 	nqueued = 0;
1404 	for (;;) {
1405 		bf = NULL;
1406 		IFQ_DEQUEUE(&ifp->if_snd, m);
1407 		if (m == NULL)
1408 			break;
1409 		/*
1410 		 * Grab the node for the destination.
1411 		 */
1412 		ni = (struct ieee80211_node *) m->m_pkthdr.rcvif;
1413 		KASSERT(ni != NULL, ("no node"));
1414 		m->m_pkthdr.rcvif = NULL;	/* committed, clear ref */
1415 		/*
1416 		 * Grab a TX buffer and associated resources.
1417 		 * We honor the classification by the 802.11 layer.
1418 		 */
1419 		txq = sc->sc_ac2q[M_WME_GETAC(m)];
1420 		bf = mwl_gettxbuf(sc, txq);
1421 		if (bf == NULL) {
1422 			m_freem(m);
1423 			ieee80211_free_node(ni);
1424 #ifdef MWL_TX_NODROP
1425 			sc->sc_stats.mst_tx_qstop++;
1426 			/* XXX blocks other traffic */
1427 			ifp->if_drv_flags |= IFF_DRV_OACTIVE;
1428 			break;
1429 #else
1430 			DPRINTF(sc, MWL_DEBUG_XMIT,
1431 			    "%s: tail drop on q %d\n", __func__, txq->qnum);
1432 			sc->sc_stats.mst_tx_qdrop++;
1433 			continue;
1434 #endif /* MWL_TX_NODROP */
1435 		}
1436 
1437 		/*
1438 		 * Pass the frame to the h/w for transmission.
1439 		 */
1440 		if (mwl_tx_start(sc, ni, bf, m)) {
1441 			ifp->if_oerrors++;
1442 			mwl_puttxbuf_head(txq, bf);
1443 			ieee80211_free_node(ni);
1444 			continue;
1445 		}
1446 		nqueued++;
1447 		if (nqueued >= mwl_txcoalesce) {
1448 			/*
1449 			 * Poke the firmware to process queued frames;
1450 			 * see below about (lack of) locking.
1451 			 */
1452 			nqueued = 0;
1453 			mwl_hal_txstart(sc->sc_mh, 0/*XXX*/);
1454 		}
1455 	}
1456 	if (nqueued) {
1457 		/*
1458 		 * NB: We don't need to lock against tx done because
1459 		 * this just prods the firmware to check the transmit
1460 		 * descriptors.  The firmware will also start fetching
1461 		 * descriptors by itself if it notices new ones are
1462 		 * present when it goes to deliver a tx done interrupt
1463 		 * to the host. So if we race with tx done processing
1464 		 * it's ok.  Delivering the kick here rather than in
1465 		 * mwl_tx_start is an optimization to avoid poking the
1466 		 * firmware for each packet.
1467 		 *
1468 		 * NB: the queue id isn't used so 0 is ok.
1469 		 */
1470 		mwl_hal_txstart(sc->sc_mh, 0/*XXX*/);
1471 	}
1472 }
1473 
1474 static int
1475 mwl_raw_xmit(struct ieee80211_node *ni, struct mbuf *m,
1476 	const struct ieee80211_bpf_params *params)
1477 {
1478 	struct ieee80211com *ic = ni->ni_ic;
1479 	struct ifnet *ifp = ic->ic_ifp;
1480 	struct mwl_softc *sc = ifp->if_softc;
1481 	struct mwl_txbuf *bf;
1482 	struct mwl_txq *txq;
1483 
1484 	if ((ifp->if_drv_flags & IFF_DRV_RUNNING) == 0 || sc->sc_invalid) {
1485 		ieee80211_free_node(ni);
1486 		m_freem(m);
1487 		return ENETDOWN;
1488 	}
1489 	/*
1490 	 * Grab a TX buffer and associated resources.
1491 	 * Note that we depend on the classification
1492 	 * by the 802.11 layer to get to the right h/w
1493 	 * queue.  Management frames must ALWAYS go on
1494 	 * queue 1 but we cannot just force that here
1495 	 * because we may receive non-mgt frames.
1496 	 */
1497 	txq = sc->sc_ac2q[M_WME_GETAC(m)];
1498 	bf = mwl_gettxbuf(sc, txq);
1499 	if (bf == NULL) {
1500 		sc->sc_stats.mst_tx_qstop++;
1501 		/* XXX blocks other traffic */
1502 		ifp->if_drv_flags |= IFF_DRV_OACTIVE;
1503 		ieee80211_free_node(ni);
1504 		m_freem(m);
1505 		return ENOBUFS;
1506 	}
1507 	/*
1508 	 * Pass the frame to the h/w for transmission.
1509 	 */
1510 	if (mwl_tx_start(sc, ni, bf, m)) {
1511 		ifp->if_oerrors++;
1512 		mwl_puttxbuf_head(txq, bf);
1513 
1514 		ieee80211_free_node(ni);
1515 		return EIO;		/* XXX */
1516 	}
1517 	/*
1518 	 * NB: We don't need to lock against tx done because
1519 	 * this just prods the firmware to check the transmit
1520 	 * descriptors.  The firmware will also start fetching
1521 	 * descriptors by itself if it notices new ones are
1522 	 * present when it goes to deliver a tx done interrupt
1523 	 * to the host. So if we race with tx done processing
1524 	 * it's ok.  Delivering the kick here rather than in
1525 	 * mwl_tx_start is an optimization to avoid poking the
1526 	 * firmware for each packet.
1527 	 *
1528 	 * NB: the queue id isn't used so 0 is ok.
1529 	 */
1530 	mwl_hal_txstart(sc->sc_mh, 0/*XXX*/);
1531 	return 0;
1532 }
1533 
1534 static int
1535 mwl_media_change(struct ifnet *ifp)
1536 {
1537 	struct ieee80211vap *vap = ifp->if_softc;
1538 	int error;
1539 
1540 	error = ieee80211_media_change(ifp);
1541 	/* NB: only the fixed rate can change and that doesn't need a reset */
1542 	if (error == ENETRESET) {
1543 		mwl_setrates(vap);
1544 		error = 0;
1545 	}
1546 	return error;
1547 }
1548 
1549 #ifdef MWL_DEBUG
1550 static void
1551 mwl_keyprint(struct mwl_softc *sc, const char *tag,
1552 	const MWL_HAL_KEYVAL *hk, const uint8_t mac[IEEE80211_ADDR_LEN])
1553 {
1554 	static const char *ciphers[] = {
1555 		"WEP",
1556 		"TKIP",
1557 		"AES-CCM",
1558 	};
1559 	int i, n;
1560 
1561 	printf("%s: [%u] %-7s", tag, hk->keyIndex, ciphers[hk->keyTypeId]);
1562 	for (i = 0, n = hk->keyLen; i < n; i++)
1563 		printf(" %02x", hk->key.aes[i]);
1564 	printf(" mac %s", ether_sprintf(mac));
1565 	if (hk->keyTypeId == KEY_TYPE_ID_TKIP) {
1566 		printf(" %s", "rxmic");
1567 		for (i = 0; i < sizeof(hk->key.tkip.rxMic); i++)
1568 			printf(" %02x", hk->key.tkip.rxMic[i]);
1569 		printf(" txmic");
1570 		for (i = 0; i < sizeof(hk->key.tkip.txMic); i++)
1571 			printf(" %02x", hk->key.tkip.txMic[i]);
1572 	}
1573 	printf(" flags 0x%x\n", hk->keyFlags);
1574 }
1575 #endif
1576 
1577 /*
1578  * Allocate a key cache slot for a unicast key.  The
1579  * firmware handles key allocation and every station is
1580  * guaranteed key space so we are always successful.
1581  */
1582 static int
1583 mwl_key_alloc(struct ieee80211vap *vap, struct ieee80211_key *k,
1584 	ieee80211_keyix *keyix, ieee80211_keyix *rxkeyix)
1585 {
1586 	struct mwl_softc *sc = vap->iv_ic->ic_ifp->if_softc;
1587 
1588 	if (k->wk_keyix != IEEE80211_KEYIX_NONE ||
1589 	    (k->wk_flags & IEEE80211_KEY_GROUP)) {
1590 		if (!(&vap->iv_nw_keys[0] <= k &&
1591 		      k < &vap->iv_nw_keys[IEEE80211_WEP_NKID])) {
1592 			/* should not happen */
1593 			DPRINTF(sc, MWL_DEBUG_KEYCACHE,
1594 				"%s: bogus group key\n", __func__);
1595 			return 0;
1596 		}
1597 		/* give the caller what they requested */
1598 		*keyix = *rxkeyix = k - vap->iv_nw_keys;
1599 	} else {
1600 		/*
1601 		 * Firmware handles key allocation.
1602 		 */
1603 		*keyix = *rxkeyix = 0;
1604 	}
1605 	return 1;
1606 }
1607 
1608 /*
1609  * Delete a key entry allocated by mwl_key_alloc.
1610  */
1611 static int
1612 mwl_key_delete(struct ieee80211vap *vap, const struct ieee80211_key *k)
1613 {
1614 	struct mwl_softc *sc = vap->iv_ic->ic_ifp->if_softc;
1615 	struct mwl_hal_vap *hvap = MWL_VAP(vap)->mv_hvap;
1616 	MWL_HAL_KEYVAL hk;
1617 	const uint8_t bcastaddr[IEEE80211_ADDR_LEN] =
1618 	    { 0xff, 0xff, 0xff, 0xff, 0xff, 0xff };
1619 
1620 	if (hvap == NULL) {
1621 		if (vap->iv_opmode != IEEE80211_M_WDS) {
1622 			/* XXX monitor mode? */
1623 			DPRINTF(sc, MWL_DEBUG_KEYCACHE,
1624 			    "%s: no hvap for opmode %d\n", __func__,
1625 			    vap->iv_opmode);
1626 			return 0;
1627 		}
1628 		hvap = MWL_VAP(vap)->mv_ap_hvap;
1629 	}
1630 
1631 	DPRINTF(sc, MWL_DEBUG_KEYCACHE, "%s: delete key %u\n",
1632 	    __func__, k->wk_keyix);
1633 
1634 	memset(&hk, 0, sizeof(hk));
1635 	hk.keyIndex = k->wk_keyix;
1636 	switch (k->wk_cipher->ic_cipher) {
1637 	case IEEE80211_CIPHER_WEP:
1638 		hk.keyTypeId = KEY_TYPE_ID_WEP;
1639 		break;
1640 	case IEEE80211_CIPHER_TKIP:
1641 		hk.keyTypeId = KEY_TYPE_ID_TKIP;
1642 		break;
1643 	case IEEE80211_CIPHER_AES_CCM:
1644 		hk.keyTypeId = KEY_TYPE_ID_AES;
1645 		break;
1646 	default:
1647 		/* XXX should not happen */
1648 		DPRINTF(sc, MWL_DEBUG_KEYCACHE, "%s: unknown cipher %d\n",
1649 		    __func__, k->wk_cipher->ic_cipher);
1650 		return 0;
1651 	}
1652 	return (mwl_hal_keyreset(hvap, &hk, bcastaddr) == 0);	/*XXX*/
1653 }
1654 
1655 static __inline int
1656 addgroupflags(MWL_HAL_KEYVAL *hk, const struct ieee80211_key *k)
1657 {
1658 	if (k->wk_flags & IEEE80211_KEY_GROUP) {
1659 		if (k->wk_flags & IEEE80211_KEY_XMIT)
1660 			hk->keyFlags |= KEY_FLAG_TXGROUPKEY;
1661 		if (k->wk_flags & IEEE80211_KEY_RECV)
1662 			hk->keyFlags |= KEY_FLAG_RXGROUPKEY;
1663 		return 1;
1664 	} else
1665 		return 0;
1666 }
1667 
1668 /*
1669  * Set the key cache contents for the specified key.  Key cache
1670  * slot(s) must already have been allocated by mwl_key_alloc.
1671  */
1672 static int
1673 mwl_key_set(struct ieee80211vap *vap, const struct ieee80211_key *k,
1674 	const uint8_t mac[IEEE80211_ADDR_LEN])
1675 {
1676 #define	GRPXMIT	(IEEE80211_KEY_XMIT | IEEE80211_KEY_GROUP)
1677 /* NB: static wep keys are marked GROUP+tx/rx; GTK will be tx or rx */
1678 #define	IEEE80211_IS_STATICKEY(k) \
1679 	(((k)->wk_flags & (GRPXMIT|IEEE80211_KEY_RECV)) == \
1680 	 (GRPXMIT|IEEE80211_KEY_RECV))
1681 	struct mwl_softc *sc = vap->iv_ic->ic_ifp->if_softc;
1682 	struct mwl_hal_vap *hvap = MWL_VAP(vap)->mv_hvap;
1683 	const struct ieee80211_cipher *cip = k->wk_cipher;
1684 	const uint8_t *macaddr;
1685 	MWL_HAL_KEYVAL hk;
1686 
1687 	KASSERT((k->wk_flags & IEEE80211_KEY_SWCRYPT) == 0,
1688 		("s/w crypto set?"));
1689 
1690 	if (hvap == NULL) {
1691 		if (vap->iv_opmode != IEEE80211_M_WDS) {
1692 			/* XXX monitor mode? */
1693 			DPRINTF(sc, MWL_DEBUG_KEYCACHE,
1694 			    "%s: no hvap for opmode %d\n", __func__,
1695 			    vap->iv_opmode);
1696 			return 0;
1697 		}
1698 		hvap = MWL_VAP(vap)->mv_ap_hvap;
1699 	}
1700 	memset(&hk, 0, sizeof(hk));
1701 	hk.keyIndex = k->wk_keyix;
1702 	switch (cip->ic_cipher) {
1703 	case IEEE80211_CIPHER_WEP:
1704 		hk.keyTypeId = KEY_TYPE_ID_WEP;
1705 		hk.keyLen = k->wk_keylen;
1706 		if (k->wk_keyix == vap->iv_def_txkey)
1707 			hk.keyFlags = KEY_FLAG_WEP_TXKEY;
1708 		if (!IEEE80211_IS_STATICKEY(k)) {
1709 			/* NB: WEP is never used for the PTK */
1710 			(void) addgroupflags(&hk, k);
1711 		}
1712 		break;
1713 	case IEEE80211_CIPHER_TKIP:
1714 		hk.keyTypeId = KEY_TYPE_ID_TKIP;
1715 		hk.key.tkip.tsc.high = (uint32_t)(k->wk_keytsc >> 16);
1716 		hk.key.tkip.tsc.low = (uint16_t)k->wk_keytsc;
1717 		hk.keyFlags = KEY_FLAG_TSC_VALID | KEY_FLAG_MICKEY_VALID;
1718 		hk.keyLen = k->wk_keylen + IEEE80211_MICBUF_SIZE;
1719 		if (!addgroupflags(&hk, k))
1720 			hk.keyFlags |= KEY_FLAG_PAIRWISE;
1721 		break;
1722 	case IEEE80211_CIPHER_AES_CCM:
1723 		hk.keyTypeId = KEY_TYPE_ID_AES;
1724 		hk.keyLen = k->wk_keylen;
1725 		if (!addgroupflags(&hk, k))
1726 			hk.keyFlags |= KEY_FLAG_PAIRWISE;
1727 		break;
1728 	default:
1729 		/* XXX should not happen */
1730 		DPRINTF(sc, MWL_DEBUG_KEYCACHE, "%s: unknown cipher %d\n",
1731 		    __func__, k->wk_cipher->ic_cipher);
1732 		return 0;
1733 	}
1734 	/*
1735 	 * NB: tkip mic keys get copied here too; the layout
1736 	 *     just happens to match that in ieee80211_key.
1737 	 */
1738 	memcpy(hk.key.aes, k->wk_key, hk.keyLen);
1739 
1740 	/*
1741 	 * Locate address of sta db entry for writing key;
1742 	 * the convention unfortunately is somewhat different
1743 	 * than how net80211, hostapd, and wpa_supplicant think.
1744 	 */
1745 	if (vap->iv_opmode == IEEE80211_M_STA) {
1746 		/*
1747 		 * NB: keys plumbed before the sta reaches AUTH state
1748 		 * will be discarded or written to the wrong sta db
1749 		 * entry because iv_bss is meaningless.  This is ok
1750 		 * (right now) because we handle deferred plumbing of
1751 		 * WEP keys when the sta reaches AUTH state.
1752 		 */
1753 		macaddr = vap->iv_bss->ni_bssid;
1754 		if ((k->wk_flags & IEEE80211_KEY_GROUP) == 0) {
1755 			/* XXX plumb to local sta db too for static key wep */
1756 			mwl_hal_keyset(hvap, &hk, vap->iv_myaddr);
1757 		}
1758 	} else if (vap->iv_opmode == IEEE80211_M_WDS &&
1759 	    vap->iv_state != IEEE80211_S_RUN) {
1760 		/*
1761 		 * Prior to RUN state a WDS vap will not it's BSS node
1762 		 * setup so we will plumb the key to the wrong mac
1763 		 * address (it'll be our local address).  Workaround
1764 		 * this for the moment by grabbing the correct address.
1765 		 */
1766 		macaddr = vap->iv_des_bssid;
1767 	} else if ((k->wk_flags & GRPXMIT) == GRPXMIT)
1768 		macaddr = vap->iv_myaddr;
1769 	else
1770 		macaddr = mac;
1771 	KEYPRINTF(sc, &hk, macaddr);
1772 	return (mwl_hal_keyset(hvap, &hk, macaddr) == 0);
1773 #undef IEEE80211_IS_STATICKEY
1774 #undef GRPXMIT
1775 }
1776 
1777 /* unaligned little endian access */
1778 #define LE_READ_2(p)				\
1779 	((uint16_t)				\
1780 	 ((((const uint8_t *)(p))[0]      ) |	\
1781 	  (((const uint8_t *)(p))[1] <<  8)))
1782 #define LE_READ_4(p)				\
1783 	((uint32_t)				\
1784 	 ((((const uint8_t *)(p))[0]      ) |	\
1785 	  (((const uint8_t *)(p))[1] <<  8) |	\
1786 	  (((const uint8_t *)(p))[2] << 16) |	\
1787 	  (((const uint8_t *)(p))[3] << 24)))
1788 
1789 /*
1790  * Set the multicast filter contents into the hardware.
1791  * XXX f/w has no support; just defer to the os.
1792  */
1793 static void
1794 mwl_setmcastfilter(struct mwl_softc *sc)
1795 {
1796 	struct ifnet *ifp = sc->sc_ifp;
1797 #if 0
1798 	struct ether_multi *enm;
1799 	struct ether_multistep estep;
1800 	uint8_t macs[IEEE80211_ADDR_LEN*MWL_HAL_MCAST_MAX];/* XXX stack use */
1801 	uint8_t *mp;
1802 	int nmc;
1803 
1804 	mp = macs;
1805 	nmc = 0;
1806 	ETHER_FIRST_MULTI(estep, &sc->sc_ec, enm);
1807 	while (enm != NULL) {
1808 		/* XXX Punt on ranges. */
1809 		if (nmc == MWL_HAL_MCAST_MAX ||
1810 		    !IEEE80211_ADDR_EQ(enm->enm_addrlo, enm->enm_addrhi)) {
1811 			ifp->if_flags |= IFF_ALLMULTI;
1812 			return;
1813 		}
1814 		IEEE80211_ADDR_COPY(mp, enm->enm_addrlo);
1815 		mp += IEEE80211_ADDR_LEN, nmc++;
1816 		ETHER_NEXT_MULTI(estep, enm);
1817 	}
1818 	ifp->if_flags &= ~IFF_ALLMULTI;
1819 	mwl_hal_setmcast(sc->sc_mh, nmc, macs);
1820 #else
1821 	/* XXX no mcast filter support; we get everything */
1822 	ifp->if_flags |= IFF_ALLMULTI;
1823 #endif
1824 }
1825 
1826 static int
1827 mwl_mode_init(struct mwl_softc *sc)
1828 {
1829 	struct ifnet *ifp = sc->sc_ifp;
1830 	struct ieee80211com *ic = ifp->if_l2com;
1831 	struct mwl_hal *mh = sc->sc_mh;
1832 
1833 	/*
1834 	 * NB: Ignore promisc in hostap mode; it's set by the
1835 	 * bridge.  This is wrong but we have no way to
1836 	 * identify internal requests (from the bridge)
1837 	 * versus external requests such as for tcpdump.
1838 	 */
1839 	mwl_hal_setpromisc(mh, (ifp->if_flags & IFF_PROMISC) &&
1840 	    ic->ic_opmode != IEEE80211_M_HOSTAP);
1841 	mwl_setmcastfilter(sc);
1842 
1843 	return 0;
1844 }
1845 
1846 /*
1847  * Callback from the 802.11 layer after a multicast state change.
1848  */
1849 static void
1850 mwl_update_mcast(struct ifnet *ifp)
1851 {
1852 	struct mwl_softc *sc = ifp->if_softc;
1853 
1854 	mwl_setmcastfilter(sc);
1855 }
1856 
1857 /*
1858  * Callback from the 802.11 layer after a promiscuous mode change.
1859  * Note this interface does not check the operating mode as this
1860  * is an internal callback and we are expected to honor the current
1861  * state (e.g. this is used for setting the interface in promiscuous
1862  * mode when operating in hostap mode to do ACS).
1863  */
1864 static void
1865 mwl_update_promisc(struct ifnet *ifp)
1866 {
1867 	struct mwl_softc *sc = ifp->if_softc;
1868 
1869 	mwl_hal_setpromisc(sc->sc_mh, (ifp->if_flags & IFF_PROMISC) != 0);
1870 }
1871 
1872 /*
1873  * Callback from the 802.11 layer to update the slot time
1874  * based on the current setting.  We use it to notify the
1875  * firmware of ERP changes and the f/w takes care of things
1876  * like slot time and preamble.
1877  */
1878 static void
1879 mwl_updateslot(struct ifnet *ifp)
1880 {
1881 	struct mwl_softc *sc = ifp->if_softc;
1882 	struct ieee80211com *ic = ifp->if_l2com;
1883 	struct mwl_hal *mh = sc->sc_mh;
1884 	int prot;
1885 
1886 	/* NB: can be called early; suppress needless cmds */
1887 	if ((ifp->if_drv_flags & IFF_DRV_RUNNING) == 0)
1888 		return;
1889 
1890 	/*
1891 	 * Calculate the ERP flags.  The firwmare will use
1892 	 * this to carry out the appropriate measures.
1893 	 */
1894 	prot = 0;
1895 	if (IEEE80211_IS_CHAN_ANYG(ic->ic_curchan)) {
1896 		if ((ic->ic_flags & IEEE80211_F_SHSLOT) == 0)
1897 			prot |= IEEE80211_ERP_NON_ERP_PRESENT;
1898 		if (ic->ic_flags & IEEE80211_F_USEPROT)
1899 			prot |= IEEE80211_ERP_USE_PROTECTION;
1900 		if (ic->ic_flags & IEEE80211_F_USEBARKER)
1901 			prot |= IEEE80211_ERP_LONG_PREAMBLE;
1902 	}
1903 
1904 	DPRINTF(sc, MWL_DEBUG_RESET,
1905 	    "%s: chan %u MHz/flags 0x%x %s slot, (prot 0x%x ic_flags 0x%x)\n",
1906 	    __func__, ic->ic_curchan->ic_freq, ic->ic_curchan->ic_flags,
1907 	    ic->ic_flags & IEEE80211_F_SHSLOT ? "short" : "long", prot,
1908 	    ic->ic_flags);
1909 
1910 	mwl_hal_setgprot(mh, prot);
1911 }
1912 
1913 /*
1914  * Setup the beacon frame.
1915  */
1916 static int
1917 mwl_beacon_setup(struct ieee80211vap *vap)
1918 {
1919 	struct mwl_hal_vap *hvap = MWL_VAP(vap)->mv_hvap;
1920 	struct ieee80211_node *ni = vap->iv_bss;
1921 	struct ieee80211_beacon_offsets bo;
1922 	struct mbuf *m;
1923 
1924 	m = ieee80211_beacon_alloc(ni, &bo);
1925 	if (m == NULL)
1926 		return ENOBUFS;
1927 	mwl_hal_setbeacon(hvap, mtod(m, const void *), m->m_len);
1928 	m_free(m);
1929 
1930 	return 0;
1931 }
1932 
1933 /*
1934  * Update the beacon frame in response to a change.
1935  */
1936 static void
1937 mwl_beacon_update(struct ieee80211vap *vap, int item)
1938 {
1939 	struct mwl_hal_vap *hvap = MWL_VAP(vap)->mv_hvap;
1940 	struct ieee80211com *ic = vap->iv_ic;
1941 
1942 	KASSERT(hvap != NULL, ("no beacon"));
1943 	switch (item) {
1944 	case IEEE80211_BEACON_ERP:
1945 		mwl_updateslot(ic->ic_ifp);
1946 		break;
1947 	case IEEE80211_BEACON_HTINFO:
1948 		mwl_hal_setnprotmode(hvap,
1949 		    MS(ic->ic_curhtprotmode, IEEE80211_HTINFO_OPMODE));
1950 		break;
1951 	case IEEE80211_BEACON_CAPS:
1952 	case IEEE80211_BEACON_WME:
1953 	case IEEE80211_BEACON_APPIE:
1954 	case IEEE80211_BEACON_CSA:
1955 		break;
1956 	case IEEE80211_BEACON_TIM:
1957 		/* NB: firmware always forms TIM */
1958 		return;
1959 	}
1960 	/* XXX retain beacon frame and update */
1961 	mwl_beacon_setup(vap);
1962 }
1963 
1964 static void
1965 mwl_load_cb(void *arg, bus_dma_segment_t *segs, int nsegs, int error)
1966 {
1967 	bus_addr_t *paddr = (bus_addr_t*) arg;
1968 	KASSERT(error == 0, ("error %u on bus_dma callback", error));
1969 	*paddr = segs->ds_addr;
1970 }
1971 
1972 #ifdef MWL_HOST_PS_SUPPORT
1973 /*
1974  * Handle power save station occupancy changes.
1975  */
1976 static void
1977 mwl_update_ps(struct ieee80211vap *vap, int nsta)
1978 {
1979 	struct mwl_vap *mvp = MWL_VAP(vap);
1980 
1981 	if (nsta == 0 || mvp->mv_last_ps_sta == 0)
1982 		mwl_hal_setpowersave_bss(mvp->mv_hvap, nsta);
1983 	mvp->mv_last_ps_sta = nsta;
1984 }
1985 
1986 /*
1987  * Handle associated station power save state changes.
1988  */
1989 static int
1990 mwl_set_tim(struct ieee80211_node *ni, int set)
1991 {
1992 	struct ieee80211vap *vap = ni->ni_vap;
1993 	struct mwl_vap *mvp = MWL_VAP(vap);
1994 
1995 	if (mvp->mv_set_tim(ni, set)) {		/* NB: state change */
1996 		mwl_hal_setpowersave_sta(mvp->mv_hvap,
1997 		    IEEE80211_AID(ni->ni_associd), set);
1998 		return 1;
1999 	} else
2000 		return 0;
2001 }
2002 #endif /* MWL_HOST_PS_SUPPORT */
2003 
2004 static int
2005 mwl_desc_setup(struct mwl_softc *sc, const char *name,
2006 	struct mwl_descdma *dd,
2007 	int nbuf, size_t bufsize, int ndesc, size_t descsize)
2008 {
2009 	struct ifnet *ifp = sc->sc_ifp;
2010 	uint8_t *ds;
2011 	int error;
2012 
2013 	DPRINTF(sc, MWL_DEBUG_RESET,
2014 	    "%s: %s DMA: %u bufs (%ju) %u desc/buf (%ju)\n",
2015 	    __func__, name, nbuf, (uintmax_t) bufsize,
2016 	    ndesc, (uintmax_t) descsize);
2017 
2018 	dd->dd_name = name;
2019 	dd->dd_desc_len = nbuf * ndesc * descsize;
2020 
2021 	/*
2022 	 * Setup DMA descriptor area.
2023 	 */
2024 	error = bus_dma_tag_create(bus_get_dma_tag(sc->sc_dev),	/* parent */
2025 		       PAGE_SIZE, 0,		/* alignment, bounds */
2026 		       BUS_SPACE_MAXADDR_32BIT,	/* lowaddr */
2027 		       BUS_SPACE_MAXADDR,	/* highaddr */
2028 		       NULL, NULL,		/* filter, filterarg */
2029 		       dd->dd_desc_len,		/* maxsize */
2030 		       1,			/* nsegments */
2031 		       dd->dd_desc_len,		/* maxsegsize */
2032 		       BUS_DMA_ALLOCNOW,	/* flags */
2033 		       NULL,			/* lockfunc */
2034 		       NULL,			/* lockarg */
2035 		       &dd->dd_dmat);
2036 	if (error != 0) {
2037 		if_printf(ifp, "cannot allocate %s DMA tag\n", dd->dd_name);
2038 		return error;
2039 	}
2040 
2041 	/* allocate descriptors */
2042 	error = bus_dmamap_create(dd->dd_dmat, BUS_DMA_NOWAIT, &dd->dd_dmamap);
2043 	if (error != 0) {
2044 		if_printf(ifp, "unable to create dmamap for %s descriptors, "
2045 			"error %u\n", dd->dd_name, error);
2046 		goto fail0;
2047 	}
2048 
2049 	error = bus_dmamem_alloc(dd->dd_dmat, (void**) &dd->dd_desc,
2050 				 BUS_DMA_NOWAIT | BUS_DMA_COHERENT,
2051 				 &dd->dd_dmamap);
2052 	if (error != 0) {
2053 		if_printf(ifp, "unable to alloc memory for %u %s descriptors, "
2054 			"error %u\n", nbuf * ndesc, dd->dd_name, error);
2055 		goto fail1;
2056 	}
2057 
2058 	error = bus_dmamap_load(dd->dd_dmat, dd->dd_dmamap,
2059 				dd->dd_desc, dd->dd_desc_len,
2060 				mwl_load_cb, &dd->dd_desc_paddr,
2061 				BUS_DMA_NOWAIT);
2062 	if (error != 0) {
2063 		if_printf(ifp, "unable to map %s descriptors, error %u\n",
2064 			dd->dd_name, error);
2065 		goto fail2;
2066 	}
2067 
2068 	ds = dd->dd_desc;
2069 	memset(ds, 0, dd->dd_desc_len);
2070 	DPRINTF(sc, MWL_DEBUG_RESET, "%s: %s DMA map: %p (%lu) -> %p (%lu)\n",
2071 	    __func__, dd->dd_name, ds, (u_long) dd->dd_desc_len,
2072 	    (caddr_t) dd->dd_desc_paddr, /*XXX*/ (u_long) dd->dd_desc_len);
2073 
2074 	return 0;
2075 fail2:
2076 	bus_dmamem_free(dd->dd_dmat, dd->dd_desc, dd->dd_dmamap);
2077 fail1:
2078 	bus_dmamap_destroy(dd->dd_dmat, dd->dd_dmamap);
2079 fail0:
2080 	bus_dma_tag_destroy(dd->dd_dmat);
2081 	memset(dd, 0, sizeof(*dd));
2082 	return error;
2083 #undef DS2PHYS
2084 }
2085 
2086 static void
2087 mwl_desc_cleanup(struct mwl_softc *sc, struct mwl_descdma *dd)
2088 {
2089 	bus_dmamap_unload(dd->dd_dmat, dd->dd_dmamap);
2090 	bus_dmamem_free(dd->dd_dmat, dd->dd_desc, dd->dd_dmamap);
2091 	bus_dmamap_destroy(dd->dd_dmat, dd->dd_dmamap);
2092 	bus_dma_tag_destroy(dd->dd_dmat);
2093 
2094 	memset(dd, 0, sizeof(*dd));
2095 }
2096 
2097 /*
2098  * Construct a tx q's free list.  The order of entries on
2099  * the list must reflect the physical layout of tx descriptors
2100  * because the firmware pre-fetches descriptors.
2101  *
2102  * XXX might be better to use indices into the buffer array.
2103  */
2104 static void
2105 mwl_txq_reset(struct mwl_softc *sc, struct mwl_txq *txq)
2106 {
2107 	struct mwl_txbuf *bf;
2108 	int i;
2109 
2110 	bf = txq->dma.dd_bufptr;
2111 	STAILQ_INIT(&txq->free);
2112 	for (i = 0; i < mwl_txbuf; i++, bf++)
2113 		STAILQ_INSERT_TAIL(&txq->free, bf, bf_list);
2114 	txq->nfree = i;
2115 }
2116 
2117 #define	DS2PHYS(_dd, _ds) \
2118 	((_dd)->dd_desc_paddr + ((caddr_t)(_ds) - (caddr_t)(_dd)->dd_desc))
2119 
2120 static int
2121 mwl_txdma_setup(struct mwl_softc *sc, struct mwl_txq *txq)
2122 {
2123 	struct ifnet *ifp = sc->sc_ifp;
2124 	int error, bsize, i;
2125 	struct mwl_txbuf *bf;
2126 	struct mwl_txdesc *ds;
2127 
2128 	error = mwl_desc_setup(sc, "tx", &txq->dma,
2129 			mwl_txbuf, sizeof(struct mwl_txbuf),
2130 			MWL_TXDESC, sizeof(struct mwl_txdesc));
2131 	if (error != 0)
2132 		return error;
2133 
2134 	/* allocate and setup tx buffers */
2135 	bsize = mwl_txbuf * sizeof(struct mwl_txbuf);
2136 	bf = malloc(bsize, M_MWLDEV, M_NOWAIT | M_ZERO);
2137 	if (bf == NULL) {
2138 		if_printf(ifp, "malloc of %u tx buffers failed\n",
2139 			mwl_txbuf);
2140 		return ENOMEM;
2141 	}
2142 	txq->dma.dd_bufptr = bf;
2143 
2144 	ds = txq->dma.dd_desc;
2145 	for (i = 0; i < mwl_txbuf; i++, bf++, ds += MWL_TXDESC) {
2146 		bf->bf_desc = ds;
2147 		bf->bf_daddr = DS2PHYS(&txq->dma, ds);
2148 		error = bus_dmamap_create(sc->sc_dmat, BUS_DMA_NOWAIT,
2149 				&bf->bf_dmamap);
2150 		if (error != 0) {
2151 			if_printf(ifp, "unable to create dmamap for tx "
2152 				"buffer %u, error %u\n", i, error);
2153 			return error;
2154 		}
2155 	}
2156 	mwl_txq_reset(sc, txq);
2157 	return 0;
2158 }
2159 
2160 static void
2161 mwl_txdma_cleanup(struct mwl_softc *sc, struct mwl_txq *txq)
2162 {
2163 	struct mwl_txbuf *bf;
2164 	int i;
2165 
2166 	bf = txq->dma.dd_bufptr;
2167 	for (i = 0; i < mwl_txbuf; i++, bf++) {
2168 		KASSERT(bf->bf_m == NULL, ("mbuf on free list"));
2169 		KASSERT(bf->bf_node == NULL, ("node on free list"));
2170 		if (bf->bf_dmamap != NULL)
2171 			bus_dmamap_destroy(sc->sc_dmat, bf->bf_dmamap);
2172 	}
2173 	STAILQ_INIT(&txq->free);
2174 	txq->nfree = 0;
2175 	if (txq->dma.dd_bufptr != NULL) {
2176 		free(txq->dma.dd_bufptr, M_MWLDEV);
2177 		txq->dma.dd_bufptr = NULL;
2178 	}
2179 	if (txq->dma.dd_desc_len != 0)
2180 		mwl_desc_cleanup(sc, &txq->dma);
2181 }
2182 
2183 static int
2184 mwl_rxdma_setup(struct mwl_softc *sc)
2185 {
2186 	struct ifnet *ifp = sc->sc_ifp;
2187 	int error, jumbosize, bsize, i;
2188 	struct mwl_rxbuf *bf;
2189 	struct mwl_jumbo *rbuf;
2190 	struct mwl_rxdesc *ds;
2191 	caddr_t data;
2192 
2193 	error = mwl_desc_setup(sc, "rx", &sc->sc_rxdma,
2194 			mwl_rxdesc, sizeof(struct mwl_rxbuf),
2195 			1, sizeof(struct mwl_rxdesc));
2196 	if (error != 0)
2197 		return error;
2198 
2199 	/*
2200 	 * Receive is done to a private pool of jumbo buffers.
2201 	 * This allows us to attach to mbuf's and avoid re-mapping
2202 	 * memory on each rx we post.  We allocate a large chunk
2203 	 * of memory and manage it in the driver.  The mbuf free
2204 	 * callback method is used to reclaim frames after sending
2205 	 * them up the stack.  By default we allocate 2x the number of
2206 	 * rx descriptors configured so we have some slop to hold
2207 	 * us while frames are processed.
2208 	 */
2209 	if (mwl_rxbuf < 2*mwl_rxdesc) {
2210 		if_printf(ifp,
2211 		    "too few rx dma buffers (%d); increasing to %d\n",
2212 		    mwl_rxbuf, 2*mwl_rxdesc);
2213 		mwl_rxbuf = 2*mwl_rxdesc;
2214 	}
2215 	jumbosize = roundup(MWL_AGGR_SIZE, PAGE_SIZE);
2216 	sc->sc_rxmemsize = mwl_rxbuf*jumbosize;
2217 
2218 	error = bus_dma_tag_create(sc->sc_dmat,	/* parent */
2219 		       PAGE_SIZE, 0,		/* alignment, bounds */
2220 		       BUS_SPACE_MAXADDR_32BIT,	/* lowaddr */
2221 		       BUS_SPACE_MAXADDR,	/* highaddr */
2222 		       NULL, NULL,		/* filter, filterarg */
2223 		       sc->sc_rxmemsize,	/* maxsize */
2224 		       1,			/* nsegments */
2225 		       sc->sc_rxmemsize,	/* maxsegsize */
2226 		       BUS_DMA_ALLOCNOW,	/* flags */
2227 		       NULL,			/* lockfunc */
2228 		       NULL,			/* lockarg */
2229 		       &sc->sc_rxdmat);
2230 	error = bus_dmamap_create(sc->sc_rxdmat, BUS_DMA_NOWAIT, &sc->sc_rxmap);
2231 	if (error != 0) {
2232 		if_printf(ifp, "could not create rx DMA map\n");
2233 		return error;
2234 	}
2235 
2236 	error = bus_dmamem_alloc(sc->sc_rxdmat, (void**) &sc->sc_rxmem,
2237 				 BUS_DMA_NOWAIT | BUS_DMA_COHERENT,
2238 				 &sc->sc_rxmap);
2239 	if (error != 0) {
2240 		if_printf(ifp, "could not alloc %ju bytes of rx DMA memory\n",
2241 		    (uintmax_t) sc->sc_rxmemsize);
2242 		return error;
2243 	}
2244 
2245 	error = bus_dmamap_load(sc->sc_rxdmat, sc->sc_rxmap,
2246 				sc->sc_rxmem, sc->sc_rxmemsize,
2247 				mwl_load_cb, &sc->sc_rxmem_paddr,
2248 				BUS_DMA_NOWAIT);
2249 	if (error != 0) {
2250 		if_printf(ifp, "could not load rx DMA map\n");
2251 		return error;
2252 	}
2253 
2254 	/*
2255 	 * Allocate rx buffers and set them up.
2256 	 */
2257 	bsize = mwl_rxdesc * sizeof(struct mwl_rxbuf);
2258 	bf = malloc(bsize, M_MWLDEV, M_NOWAIT | M_ZERO);
2259 	if (bf == NULL) {
2260 		if_printf(ifp, "malloc of %u rx buffers failed\n", bsize);
2261 		return error;
2262 	}
2263 	sc->sc_rxdma.dd_bufptr = bf;
2264 
2265 	STAILQ_INIT(&sc->sc_rxbuf);
2266 	ds = sc->sc_rxdma.dd_desc;
2267 	for (i = 0; i < mwl_rxdesc; i++, bf++, ds++) {
2268 		bf->bf_desc = ds;
2269 		bf->bf_daddr = DS2PHYS(&sc->sc_rxdma, ds);
2270 		/* pre-assign dma buffer */
2271 		bf->bf_data = ((uint8_t *)sc->sc_rxmem) + (i*jumbosize);
2272 		/* NB: tail is intentional to preserve descriptor order */
2273 		STAILQ_INSERT_TAIL(&sc->sc_rxbuf, bf, bf_list);
2274 	}
2275 
2276 	/*
2277 	 * Place remainder of dma memory buffers on the free list.
2278 	 */
2279 	SLIST_INIT(&sc->sc_rxfree);
2280 	for (; i < mwl_rxbuf; i++) {
2281 		data = ((uint8_t *)sc->sc_rxmem) + (i*jumbosize);
2282 		rbuf = MWL_JUMBO_DATA2BUF(data);
2283 		SLIST_INSERT_HEAD(&sc->sc_rxfree, rbuf, next);
2284 		sc->sc_nrxfree++;
2285 	}
2286 	return 0;
2287 }
2288 #undef DS2PHYS
2289 
2290 static void
2291 mwl_rxdma_cleanup(struct mwl_softc *sc)
2292 {
2293 	if (sc->sc_rxmap != NULL)
2294 		bus_dmamap_unload(sc->sc_rxdmat, sc->sc_rxmap);
2295 	if (sc->sc_rxmem != NULL) {
2296 		bus_dmamem_free(sc->sc_rxdmat, sc->sc_rxmem, sc->sc_rxmap);
2297 		sc->sc_rxmem = NULL;
2298 	}
2299 	if (sc->sc_rxmap != NULL) {
2300 		bus_dmamap_destroy(sc->sc_rxdmat, sc->sc_rxmap);
2301 		sc->sc_rxmap = NULL;
2302 	}
2303 	if (sc->sc_rxdma.dd_bufptr != NULL) {
2304 		free(sc->sc_rxdma.dd_bufptr, M_MWLDEV);
2305 		sc->sc_rxdma.dd_bufptr = NULL;
2306 	}
2307 	if (sc->sc_rxdma.dd_desc_len != 0)
2308 		mwl_desc_cleanup(sc, &sc->sc_rxdma);
2309 }
2310 
2311 static int
2312 mwl_dma_setup(struct mwl_softc *sc)
2313 {
2314 	int error, i;
2315 
2316 	error = mwl_rxdma_setup(sc);
2317 	if (error != 0) {
2318 		mwl_rxdma_cleanup(sc);
2319 		return error;
2320 	}
2321 
2322 	for (i = 0; i < MWL_NUM_TX_QUEUES; i++) {
2323 		error = mwl_txdma_setup(sc, &sc->sc_txq[i]);
2324 		if (error != 0) {
2325 			mwl_dma_cleanup(sc);
2326 			return error;
2327 		}
2328 	}
2329 	return 0;
2330 }
2331 
2332 static void
2333 mwl_dma_cleanup(struct mwl_softc *sc)
2334 {
2335 	int i;
2336 
2337 	for (i = 0; i < MWL_NUM_TX_QUEUES; i++)
2338 		mwl_txdma_cleanup(sc, &sc->sc_txq[i]);
2339 	mwl_rxdma_cleanup(sc);
2340 }
2341 
2342 static struct ieee80211_node *
2343 mwl_node_alloc(struct ieee80211vap *vap, const uint8_t mac[IEEE80211_ADDR_LEN])
2344 {
2345 	struct ieee80211com *ic = vap->iv_ic;
2346 	struct mwl_softc *sc = ic->ic_ifp->if_softc;
2347 	const size_t space = sizeof(struct mwl_node);
2348 	struct mwl_node *mn;
2349 
2350 	mn = malloc(space, M_80211_NODE, M_NOWAIT|M_ZERO);
2351 	if (mn == NULL) {
2352 		/* XXX stat+msg */
2353 		return NULL;
2354 	}
2355 	DPRINTF(sc, MWL_DEBUG_NODE, "%s: mn %p\n", __func__, mn);
2356 	return &mn->mn_node;
2357 }
2358 
2359 static void
2360 mwl_node_cleanup(struct ieee80211_node *ni)
2361 {
2362 	struct ieee80211com *ic = ni->ni_ic;
2363         struct mwl_softc *sc = ic->ic_ifp->if_softc;
2364 	struct mwl_node *mn = MWL_NODE(ni);
2365 
2366 	DPRINTF(sc, MWL_DEBUG_NODE, "%s: ni %p ic %p staid %d\n",
2367 	    __func__, ni, ni->ni_ic, mn->mn_staid);
2368 
2369 	if (mn->mn_staid != 0) {
2370 		struct ieee80211vap *vap = ni->ni_vap;
2371 
2372 		if (mn->mn_hvap != NULL) {
2373 			if (vap->iv_opmode == IEEE80211_M_STA)
2374 				mwl_hal_delstation(mn->mn_hvap, vap->iv_myaddr);
2375 			else
2376 				mwl_hal_delstation(mn->mn_hvap, ni->ni_macaddr);
2377 		}
2378 		/*
2379 		 * NB: legacy WDS peer sta db entry is installed using
2380 		 * the associate ap's hvap; use it again to delete it.
2381 		 * XXX can vap be NULL?
2382 		 */
2383 		else if (vap->iv_opmode == IEEE80211_M_WDS &&
2384 		    MWL_VAP(vap)->mv_ap_hvap != NULL)
2385 			mwl_hal_delstation(MWL_VAP(vap)->mv_ap_hvap,
2386 			    ni->ni_macaddr);
2387 		delstaid(sc, mn->mn_staid);
2388 		mn->mn_staid = 0;
2389 	}
2390 	sc->sc_node_cleanup(ni);
2391 }
2392 
2393 /*
2394  * Reclaim rx dma buffers from packets sitting on the ampdu
2395  * reorder queue for a station.  We replace buffers with a
2396  * system cluster (if available).
2397  */
2398 static void
2399 mwl_ampdu_rxdma_reclaim(struct ieee80211_rx_ampdu *rap)
2400 {
2401 #if 0
2402 	int i, n, off;
2403 	struct mbuf *m;
2404 	void *cl;
2405 
2406 	n = rap->rxa_qframes;
2407 	for (i = 0; i < rap->rxa_wnd && n > 0; i++) {
2408 		m = rap->rxa_m[i];
2409 		if (m == NULL)
2410 			continue;
2411 		n--;
2412 		/* our dma buffers have a well-known free routine */
2413 		if ((m->m_flags & M_EXT) == 0 ||
2414 		    m->m_ext.ext_free != mwl_ext_free)
2415 			continue;
2416 		/*
2417 		 * Try to allocate a cluster and move the data.
2418 		 */
2419 		off = m->m_data - m->m_ext.ext_buf;
2420 		if (off + m->m_pkthdr.len > MCLBYTES) {
2421 			/* XXX no AMSDU for now */
2422 			continue;
2423 		}
2424 		cl = pool_cache_get_paddr(&mclpool_cache, 0,
2425 		    &m->m_ext.ext_paddr);
2426 		if (cl != NULL) {
2427 			/*
2428 			 * Copy the existing data to the cluster, remove
2429 			 * the rx dma buffer, and attach the cluster in
2430 			 * its place.  Note we preserve the offset to the
2431 			 * data so frames being bridged can still prepend
2432 			 * their headers without adding another mbuf.
2433 			 */
2434 			memcpy((caddr_t) cl + off, m->m_data, m->m_pkthdr.len);
2435 			MEXTREMOVE(m);
2436 			MEXTADD(m, cl, MCLBYTES, 0, NULL, &mclpool_cache);
2437 			/* setup mbuf like _MCLGET does */
2438 			m->m_flags |= M_CLUSTER | M_EXT_RW;
2439 			_MOWNERREF(m, M_EXT | M_CLUSTER);
2440 			/* NB: m_data is clobbered by MEXTADDR, adjust */
2441 			m->m_data += off;
2442 		}
2443 	}
2444 #endif
2445 }
2446 
2447 /*
2448  * Callback to reclaim resources.  We first let the
2449  * net80211 layer do it's thing, then if we are still
2450  * blocked by a lack of rx dma buffers we walk the ampdu
2451  * reorder q's to reclaim buffers by copying to a system
2452  * cluster.
2453  */
2454 static void
2455 mwl_node_drain(struct ieee80211_node *ni)
2456 {
2457 	struct ieee80211com *ic = ni->ni_ic;
2458         struct mwl_softc *sc = ic->ic_ifp->if_softc;
2459 	struct mwl_node *mn = MWL_NODE(ni);
2460 
2461 	DPRINTF(sc, MWL_DEBUG_NODE, "%s: ni %p vap %p staid %d\n",
2462 	    __func__, ni, ni->ni_vap, mn->mn_staid);
2463 
2464 	/* NB: call up first to age out ampdu q's */
2465 	sc->sc_node_drain(ni);
2466 
2467 	/* XXX better to not check low water mark? */
2468 	if (sc->sc_rxblocked && mn->mn_staid != 0 &&
2469 	    (ni->ni_flags & IEEE80211_NODE_HT)) {
2470 		uint8_t tid;
2471 		/*
2472 		 * Walk the reorder q and reclaim rx dma buffers by copying
2473 		 * the packet contents into clusters.
2474 		 */
2475 		for (tid = 0; tid < WME_NUM_TID; tid++) {
2476 			struct ieee80211_rx_ampdu *rap;
2477 
2478 			rap = &ni->ni_rx_ampdu[tid];
2479 			if ((rap->rxa_flags & IEEE80211_AGGR_XCHGPEND) == 0)
2480 				continue;
2481 			if (rap->rxa_qframes)
2482 				mwl_ampdu_rxdma_reclaim(rap);
2483 		}
2484 	}
2485 }
2486 
2487 static void
2488 mwl_node_getsignal(const struct ieee80211_node *ni, int8_t *rssi, int8_t *noise)
2489 {
2490 	*rssi = ni->ni_ic->ic_node_getrssi(ni);
2491 #ifdef MWL_ANT_INFO_SUPPORT
2492 #if 0
2493 	/* XXX need to smooth data */
2494 	*noise = -MWL_NODE_CONST(ni)->mn_ai.nf;
2495 #else
2496 	*noise = -95;		/* XXX */
2497 #endif
2498 #else
2499 	*noise = -95;		/* XXX */
2500 #endif
2501 }
2502 
2503 /*
2504  * Convert Hardware per-antenna rssi info to common format:
2505  * Let a1, a2, a3 represent the amplitudes per chain
2506  * Let amax represent max[a1, a2, a3]
2507  * Rssi1_dBm = RSSI_dBm + 20*log10(a1/amax)
2508  * Rssi1_dBm = RSSI_dBm + 20*log10(a1) - 20*log10(amax)
2509  * We store a table that is 4*20*log10(idx) - the extra 4 is to store or
2510  * maintain some extra precision.
2511  *
2512  * Values are stored in .5 db format capped at 127.
2513  */
2514 static void
2515 mwl_node_getmimoinfo(const struct ieee80211_node *ni,
2516 	struct ieee80211_mimo_info *mi)
2517 {
2518 #define	CVT(_dst, _src) do {						\
2519 	(_dst) = rssi + ((logdbtbl[_src] - logdbtbl[rssi_max]) >> 2);	\
2520 	(_dst) = (_dst) > 64 ? 127 : ((_dst) << 1);			\
2521 } while (0)
2522 	static const int8_t logdbtbl[32] = {
2523 	       0,   0,  24,  38,  48,  56,  62,  68,
2524 	      72,  76,  80,  83,  86,  89,  92,  94,
2525 	      96,  98, 100, 102, 104, 106, 107, 109,
2526 	     110, 112, 113, 115, 116, 117, 118, 119
2527 	};
2528 	const struct mwl_node *mn = MWL_NODE_CONST(ni);
2529 	uint8_t rssi = mn->mn_ai.rsvd1/2;		/* XXX */
2530 	uint32_t rssi_max;
2531 
2532 	rssi_max = mn->mn_ai.rssi_a;
2533 	if (mn->mn_ai.rssi_b > rssi_max)
2534 		rssi_max = mn->mn_ai.rssi_b;
2535 	if (mn->mn_ai.rssi_c > rssi_max)
2536 		rssi_max = mn->mn_ai.rssi_c;
2537 
2538 	CVT(mi->rssi[0], mn->mn_ai.rssi_a);
2539 	CVT(mi->rssi[1], mn->mn_ai.rssi_b);
2540 	CVT(mi->rssi[2], mn->mn_ai.rssi_c);
2541 
2542 	mi->noise[0] = mn->mn_ai.nf_a;
2543 	mi->noise[1] = mn->mn_ai.nf_b;
2544 	mi->noise[2] = mn->mn_ai.nf_c;
2545 #undef CVT
2546 }
2547 
2548 static __inline void *
2549 mwl_getrxdma(struct mwl_softc *sc)
2550 {
2551 	struct mwl_jumbo *buf;
2552 	void *data;
2553 
2554 	/*
2555 	 * Allocate from jumbo pool.
2556 	 */
2557 	MWL_RXFREE_LOCK(sc);
2558 	buf = SLIST_FIRST(&sc->sc_rxfree);
2559 	if (buf == NULL) {
2560 		DPRINTF(sc, MWL_DEBUG_ANY,
2561 		    "%s: out of rx dma buffers\n", __func__);
2562 		sc->sc_stats.mst_rx_nodmabuf++;
2563 		data = NULL;
2564 	} else {
2565 		SLIST_REMOVE_HEAD(&sc->sc_rxfree, next);
2566 		sc->sc_nrxfree--;
2567 		data = MWL_JUMBO_BUF2DATA(buf);
2568 	}
2569 	MWL_RXFREE_UNLOCK(sc);
2570 	return data;
2571 }
2572 
2573 static __inline void
2574 mwl_putrxdma(struct mwl_softc *sc, void *data)
2575 {
2576 	struct mwl_jumbo *buf;
2577 
2578 	/* XXX bounds check data */
2579 	MWL_RXFREE_LOCK(sc);
2580 	buf = MWL_JUMBO_DATA2BUF(data);
2581 	SLIST_INSERT_HEAD(&sc->sc_rxfree, buf, next);
2582 	sc->sc_nrxfree++;
2583 	MWL_RXFREE_UNLOCK(sc);
2584 }
2585 
2586 static int
2587 mwl_rxbuf_init(struct mwl_softc *sc, struct mwl_rxbuf *bf)
2588 {
2589 	struct mwl_rxdesc *ds;
2590 
2591 	ds = bf->bf_desc;
2592 	if (bf->bf_data == NULL) {
2593 		bf->bf_data = mwl_getrxdma(sc);
2594 		if (bf->bf_data == NULL) {
2595 			/* mark descriptor to be skipped */
2596 			ds->RxControl = EAGLE_RXD_CTRL_OS_OWN;
2597 			/* NB: don't need PREREAD */
2598 			MWL_RXDESC_SYNC(sc, ds, BUS_DMASYNC_PREWRITE);
2599 			sc->sc_stats.mst_rxbuf_failed++;
2600 			return ENOMEM;
2601 		}
2602 	}
2603 	/*
2604 	 * NB: DMA buffer contents is known to be unmodified
2605 	 *     so there's no need to flush the data cache.
2606 	 */
2607 
2608 	/*
2609 	 * Setup descriptor.
2610 	 */
2611 	ds->QosCtrl = 0;
2612 	ds->RSSI = 0;
2613 	ds->Status = EAGLE_RXD_STATUS_IDLE;
2614 	ds->Channel = 0;
2615 	ds->PktLen = htole16(MWL_AGGR_SIZE);
2616 	ds->SQ2 = 0;
2617 	ds->pPhysBuffData = htole32(MWL_JUMBO_DMA_ADDR(sc, bf->bf_data));
2618 	/* NB: don't touch pPhysNext, set once */
2619 	ds->RxControl = EAGLE_RXD_CTRL_DRIVER_OWN;
2620 	MWL_RXDESC_SYNC(sc, ds, BUS_DMASYNC_PREREAD | BUS_DMASYNC_PREWRITE);
2621 
2622 	return 0;
2623 }
2624 
2625 static int
2626 mwl_ext_free(struct mbuf *m, void *data, void *arg)
2627 {
2628 	struct mwl_softc *sc = arg;
2629 
2630 	/* XXX bounds check data */
2631 	mwl_putrxdma(sc, data);
2632 	/*
2633 	 * If we were previously blocked by a lack of rx dma buffers
2634 	 * check if we now have enough to restart rx interrupt handling.
2635 	 * NB: we know we are called at splvm which is above splnet.
2636 	 */
2637 	if (sc->sc_rxblocked && sc->sc_nrxfree > mwl_rxdmalow) {
2638 		sc->sc_rxblocked = 0;
2639 		mwl_hal_intrset(sc->sc_mh, sc->sc_imask);
2640 	}
2641 	return (EXT_FREE_OK);
2642 }
2643 
2644 struct mwl_frame_bar {
2645 	u_int8_t	i_fc[2];
2646 	u_int8_t	i_dur[2];
2647 	u_int8_t	i_ra[IEEE80211_ADDR_LEN];
2648 	u_int8_t	i_ta[IEEE80211_ADDR_LEN];
2649 	/* ctl, seq, FCS */
2650 } __packed;
2651 
2652 /*
2653  * Like ieee80211_anyhdrsize, but handles BAR frames
2654  * specially so the logic below to piece the 802.11
2655  * header together works.
2656  */
2657 static __inline int
2658 mwl_anyhdrsize(const void *data)
2659 {
2660 	const struct ieee80211_frame *wh = data;
2661 
2662 	if ((wh->i_fc[0]&IEEE80211_FC0_TYPE_MASK) == IEEE80211_FC0_TYPE_CTL) {
2663 		switch (wh->i_fc[0] & IEEE80211_FC0_SUBTYPE_MASK) {
2664 		case IEEE80211_FC0_SUBTYPE_CTS:
2665 		case IEEE80211_FC0_SUBTYPE_ACK:
2666 			return sizeof(struct ieee80211_frame_ack);
2667 		case IEEE80211_FC0_SUBTYPE_BAR:
2668 			return sizeof(struct mwl_frame_bar);
2669 		}
2670 		return sizeof(struct ieee80211_frame_min);
2671 	} else
2672 		return ieee80211_hdrsize(data);
2673 }
2674 
2675 static void
2676 mwl_handlemicerror(struct ieee80211com *ic, const uint8_t *data)
2677 {
2678 	const struct ieee80211_frame *wh;
2679 	struct ieee80211_node *ni;
2680 
2681 	wh = (const struct ieee80211_frame *)(data + sizeof(uint16_t));
2682 	ni = ieee80211_find_rxnode(ic, (const struct ieee80211_frame_min *) wh);
2683 	if (ni != NULL) {
2684 		ieee80211_notify_michael_failure(ni->ni_vap, wh, 0);
2685 		ieee80211_free_node(ni);
2686 	}
2687 }
2688 
2689 /*
2690  * Convert hardware signal strength to rssi.  The value
2691  * provided by the device has the noise floor added in;
2692  * we need to compensate for this but we don't have that
2693  * so we use a fixed value.
2694  *
2695  * The offset of 8 is good for both 2.4 and 5GHz.  The LNA
2696  * offset is already set as part of the initial gain.  This
2697  * will give at least +/- 3dB for 2.4GHz and +/- 5dB for 5GHz.
2698  */
2699 static __inline int
2700 cvtrssi(uint8_t ssi)
2701 {
2702 	int rssi = (int) ssi + 8;
2703 	/* XXX hack guess until we have a real noise floor */
2704 	rssi = 2*(87 - rssi);	/* NB: .5 dBm units */
2705 	return (rssi < 0 ? 0 : rssi > 127 ? 127 : rssi);
2706 }
2707 
2708 static void
2709 mwl_rx_proc(void *arg, int npending)
2710 {
2711 #define	IEEE80211_DIR_DSTODS(wh) \
2712 	((((const struct ieee80211_frame *)wh)->i_fc[1] & IEEE80211_FC1_DIR_MASK) == IEEE80211_FC1_DIR_DSTODS)
2713 	struct mwl_softc *sc = arg;
2714 	struct ifnet *ifp = sc->sc_ifp;
2715 	struct ieee80211com *ic = ifp->if_l2com;
2716 	struct mwl_rxbuf *bf;
2717 	struct mwl_rxdesc *ds;
2718 	struct mbuf *m;
2719 	struct ieee80211_qosframe *wh;
2720 	struct ieee80211_qosframe_addr4 *wh4;
2721 	struct ieee80211_node *ni;
2722 	struct mwl_node *mn;
2723 	int off, len, hdrlen, pktlen, rssi, ntodo;
2724 	uint8_t *data, status;
2725 	void *newdata;
2726 	int16_t nf;
2727 
2728 	DPRINTF(sc, MWL_DEBUG_RX_PROC, "%s: pending %u rdptr 0x%x wrptr 0x%x\n",
2729 	    __func__, npending, RD4(sc, sc->sc_hwspecs.rxDescRead),
2730 	    RD4(sc, sc->sc_hwspecs.rxDescWrite));
2731 	nf = -96;			/* XXX */
2732 	bf = sc->sc_rxnext;
2733 	for (ntodo = mwl_rxquota; ntodo > 0; ntodo--) {
2734 		if (bf == NULL)
2735 			bf = STAILQ_FIRST(&sc->sc_rxbuf);
2736 		ds = bf->bf_desc;
2737 		data = bf->bf_data;
2738 		if (data == NULL) {
2739 			/*
2740 			 * If data allocation failed previously there
2741 			 * will be no buffer; try again to re-populate it.
2742 			 * Note the firmware will not advance to the next
2743 			 * descriptor with a dma buffer so we must mimic
2744 			 * this or we'll get out of sync.
2745 			 */
2746 			DPRINTF(sc, MWL_DEBUG_ANY,
2747 			    "%s: rx buf w/o dma memory\n", __func__);
2748 			(void) mwl_rxbuf_init(sc, bf);
2749 			sc->sc_stats.mst_rx_dmabufmissing++;
2750 			break;
2751 		}
2752 		MWL_RXDESC_SYNC(sc, ds,
2753 		    BUS_DMASYNC_POSTREAD | BUS_DMASYNC_POSTWRITE);
2754 		if (ds->RxControl != EAGLE_RXD_CTRL_DMA_OWN)
2755 			break;
2756 #ifdef MWL_DEBUG
2757 		if (sc->sc_debug & MWL_DEBUG_RECV_DESC)
2758 			mwl_printrxbuf(bf, 0);
2759 #endif
2760 		status = ds->Status;
2761 		if (status & EAGLE_RXD_STATUS_DECRYPT_ERR_MASK) {
2762 			ifp->if_ierrors++;
2763 			sc->sc_stats.mst_rx_crypto++;
2764 			/*
2765 			 * NB: Check EAGLE_RXD_STATUS_GENERAL_DECRYPT_ERR
2766 			 *     for backwards compatibility.
2767 			 */
2768 			if (status != EAGLE_RXD_STATUS_GENERAL_DECRYPT_ERR &&
2769 			    (status & EAGLE_RXD_STATUS_TKIP_MIC_DECRYPT_ERR)) {
2770 				/*
2771 				 * MIC error, notify upper layers.
2772 				 */
2773 				bus_dmamap_sync(sc->sc_rxdmat, sc->sc_rxmap,
2774 				    BUS_DMASYNC_POSTREAD);
2775 				mwl_handlemicerror(ic, data);
2776 				sc->sc_stats.mst_rx_tkipmic++;
2777 			}
2778 			/* XXX too painful to tap packets */
2779 			goto rx_next;
2780 		}
2781 		/*
2782 		 * Sync the data buffer.
2783 		 */
2784 		len = le16toh(ds->PktLen);
2785 		bus_dmamap_sync(sc->sc_rxdmat, sc->sc_rxmap, BUS_DMASYNC_POSTREAD);
2786 		/*
2787 		 * The 802.11 header is provided all or in part at the front;
2788 		 * use it to calculate the true size of the header that we'll
2789 		 * construct below.  We use this to figure out where to copy
2790 		 * payload prior to constructing the header.
2791 		 */
2792 		hdrlen = mwl_anyhdrsize(data + sizeof(uint16_t));
2793 		off = sizeof(uint16_t) + sizeof(struct ieee80211_frame_addr4);
2794 
2795 		/* calculate rssi early so we can re-use for each aggregate */
2796 		rssi = cvtrssi(ds->RSSI);
2797 
2798 		pktlen = hdrlen + (len - off);
2799 		/*
2800 		 * NB: we know our frame is at least as large as
2801 		 * IEEE80211_MIN_LEN because there is a 4-address
2802 		 * frame at the front.  Hence there's no need to
2803 		 * vet the packet length.  If the frame in fact
2804 		 * is too small it should be discarded at the
2805 		 * net80211 layer.
2806 		 */
2807 
2808 		/*
2809 		 * Attach dma buffer to an mbuf.  We tried
2810 		 * doing this based on the packet size (i.e.
2811 		 * copying small packets) but it turns out to
2812 		 * be a net loss.  The tradeoff might be system
2813 		 * dependent (cache architecture is important).
2814 		 */
2815 		MGETHDR(m, M_NOWAIT, MT_DATA);
2816 		if (m == NULL) {
2817 			DPRINTF(sc, MWL_DEBUG_ANY,
2818 			    "%s: no rx mbuf\n", __func__);
2819 			sc->sc_stats.mst_rx_nombuf++;
2820 			goto rx_next;
2821 		}
2822 		/*
2823 		 * Acquire the replacement dma buffer before
2824 		 * processing the frame.  If we're out of dma
2825 		 * buffers we disable rx interrupts and wait
2826 		 * for the free pool to reach mlw_rxdmalow buffers
2827 		 * before starting to do work again.  If the firmware
2828 		 * runs out of descriptors then it will toss frames
2829 		 * which is better than our doing it as that can
2830 		 * starve our processing.  It is also important that
2831 		 * we always process rx'd frames in case they are
2832 		 * A-MPDU as otherwise the host's view of the BA
2833 		 * window may get out of sync with the firmware.
2834 		 */
2835 		newdata = mwl_getrxdma(sc);
2836 		if (newdata == NULL) {
2837 			/* NB: stat+msg in mwl_getrxdma */
2838 			m_free(m);
2839 			/* disable RX interrupt and mark state */
2840 			mwl_hal_intrset(sc->sc_mh,
2841 			    sc->sc_imask &~ MACREG_A2HRIC_BIT_RX_RDY);
2842 			sc->sc_rxblocked = 1;
2843 			ieee80211_drain(ic);
2844 			/* XXX check rxblocked and immediately start again? */
2845 			goto rx_stop;
2846 		}
2847 		bf->bf_data = newdata;
2848 		/*
2849 		 * Attach the dma buffer to the mbuf;
2850 		 * mwl_rxbuf_init will re-setup the rx
2851 		 * descriptor using the replacement dma
2852 		 * buffer we just installed above.
2853 		 */
2854 		MEXTADD(m, data, MWL_AGGR_SIZE, mwl_ext_free,
2855 		    data, sc, 0, EXT_NET_DRV);
2856 		m->m_data += off - hdrlen;
2857 		m->m_pkthdr.len = m->m_len = pktlen;
2858 		m->m_pkthdr.rcvif = ifp;
2859 		/* NB: dma buffer assumed read-only */
2860 
2861 		/*
2862 		 * Piece 802.11 header together.
2863 		 */
2864 		wh = mtod(m, struct ieee80211_qosframe *);
2865 		/* NB: don't need to do this sometimes but ... */
2866 		/* XXX special case so we can memcpy after m_devget? */
2867 		ovbcopy(data + sizeof(uint16_t), wh, hdrlen);
2868 		if (IEEE80211_QOS_HAS_SEQ(wh)) {
2869 			if (IEEE80211_DIR_DSTODS(wh)) {
2870 				wh4 = mtod(m,
2871 				    struct ieee80211_qosframe_addr4*);
2872 				*(uint16_t *)wh4->i_qos = ds->QosCtrl;
2873 			} else {
2874 				*(uint16_t *)wh->i_qos = ds->QosCtrl;
2875 			}
2876 		}
2877 		/*
2878 		 * The f/w strips WEP header but doesn't clear
2879 		 * the WEP bit; mark the packet with M_WEP so
2880 		 * net80211 will treat the data as decrypted.
2881 		 * While here also clear the PWR_MGT bit since
2882 		 * power save is handled by the firmware and
2883 		 * passing this up will potentially cause the
2884 		 * upper layer to put a station in power save
2885 		 * (except when configured with MWL_HOST_PS_SUPPORT).
2886 		 */
2887 		if (wh->i_fc[1] & IEEE80211_FC1_WEP)
2888 			m->m_flags |= M_WEP;
2889 #ifdef MWL_HOST_PS_SUPPORT
2890 		wh->i_fc[1] &= ~IEEE80211_FC1_WEP;
2891 #else
2892 		wh->i_fc[1] &= ~(IEEE80211_FC1_WEP | IEEE80211_FC1_PWR_MGT);
2893 #endif
2894 
2895 		if (ieee80211_radiotap_active(ic)) {
2896 			struct mwl_rx_radiotap_header *tap = &sc->sc_rx_th;
2897 
2898 			tap->wr_flags = 0;
2899 			tap->wr_rate = ds->Rate;
2900 			tap->wr_antsignal = rssi + nf;
2901 			tap->wr_antnoise = nf;
2902 		}
2903 		if (IFF_DUMPPKTS_RECV(sc, wh)) {
2904 			ieee80211_dump_pkt(ic, mtod(m, caddr_t),
2905 			    len, ds->Rate, rssi);
2906 		}
2907 		ifp->if_ipackets++;
2908 
2909 		/* dispatch */
2910 		ni = ieee80211_find_rxnode(ic,
2911 		    (const struct ieee80211_frame_min *) wh);
2912 		if (ni != NULL) {
2913 			mn = MWL_NODE(ni);
2914 #ifdef MWL_ANT_INFO_SUPPORT
2915 			mn->mn_ai.rssi_a = ds->ai.rssi_a;
2916 			mn->mn_ai.rssi_b = ds->ai.rssi_b;
2917 			mn->mn_ai.rssi_c = ds->ai.rssi_c;
2918 			mn->mn_ai.rsvd1 = rssi;
2919 #endif
2920 			/* tag AMPDU aggregates for reorder processing */
2921 			if (ni->ni_flags & IEEE80211_NODE_HT)
2922 				m->m_flags |= M_AMPDU;
2923 			(void) ieee80211_input(ni, m, rssi, nf);
2924 			ieee80211_free_node(ni);
2925 		} else
2926 			(void) ieee80211_input_all(ic, m, rssi, nf);
2927 rx_next:
2928 		/* NB: ignore ENOMEM so we process more descriptors */
2929 		(void) mwl_rxbuf_init(sc, bf);
2930 		bf = STAILQ_NEXT(bf, bf_list);
2931 	}
2932 rx_stop:
2933 	sc->sc_rxnext = bf;
2934 
2935 	if ((ifp->if_drv_flags & IFF_DRV_OACTIVE) == 0 &&
2936 	    !IFQ_IS_EMPTY(&ifp->if_snd)) {
2937 		/* NB: kick fw; the tx thread may have been preempted */
2938 		mwl_hal_txstart(sc->sc_mh, 0);
2939 		mwl_start(ifp);
2940 	}
2941 #undef IEEE80211_DIR_DSTODS
2942 }
2943 
2944 static void
2945 mwl_txq_init(struct mwl_softc *sc, struct mwl_txq *txq, int qnum)
2946 {
2947 	struct mwl_txbuf *bf, *bn;
2948 	struct mwl_txdesc *ds;
2949 
2950 	MWL_TXQ_LOCK_INIT(sc, txq);
2951 	txq->qnum = qnum;
2952 	txq->txpri = 0;	/* XXX */
2953 #if 0
2954 	/* NB: q setup by mwl_txdma_setup XXX */
2955 	STAILQ_INIT(&txq->free);
2956 #endif
2957 	STAILQ_FOREACH(bf, &txq->free, bf_list) {
2958 		bf->bf_txq = txq;
2959 
2960 		ds = bf->bf_desc;
2961 		bn = STAILQ_NEXT(bf, bf_list);
2962 		if (bn == NULL)
2963 			bn = STAILQ_FIRST(&txq->free);
2964 		ds->pPhysNext = htole32(bn->bf_daddr);
2965 	}
2966 	STAILQ_INIT(&txq->active);
2967 }
2968 
2969 /*
2970  * Setup a hardware data transmit queue for the specified
2971  * access control.  We record the mapping from ac's
2972  * to h/w queues for use by mwl_tx_start.
2973  */
2974 static int
2975 mwl_tx_setup(struct mwl_softc *sc, int ac, int mvtype)
2976 {
2977 #define	N(a)	(sizeof(a)/sizeof(a[0]))
2978 	struct mwl_txq *txq;
2979 
2980 	if (ac >= N(sc->sc_ac2q)) {
2981 		device_printf(sc->sc_dev, "AC %u out of range, max %zu!\n",
2982 			ac, N(sc->sc_ac2q));
2983 		return 0;
2984 	}
2985 	if (mvtype >= MWL_NUM_TX_QUEUES) {
2986 		device_printf(sc->sc_dev, "mvtype %u out of range, max %u!\n",
2987 			mvtype, MWL_NUM_TX_QUEUES);
2988 		return 0;
2989 	}
2990 	txq = &sc->sc_txq[mvtype];
2991 	mwl_txq_init(sc, txq, mvtype);
2992 	sc->sc_ac2q[ac] = txq;
2993 	return 1;
2994 #undef N
2995 }
2996 
2997 /*
2998  * Update WME parameters for a transmit queue.
2999  */
3000 static int
3001 mwl_txq_update(struct mwl_softc *sc, int ac)
3002 {
3003 #define	MWL_EXPONENT_TO_VALUE(v)	((1<<v)-1)
3004 	struct ifnet *ifp = sc->sc_ifp;
3005 	struct ieee80211com *ic = ifp->if_l2com;
3006 	struct mwl_txq *txq = sc->sc_ac2q[ac];
3007 	struct wmeParams *wmep = &ic->ic_wme.wme_chanParams.cap_wmeParams[ac];
3008 	struct mwl_hal *mh = sc->sc_mh;
3009 	int aifs, cwmin, cwmax, txoplim;
3010 
3011 	aifs = wmep->wmep_aifsn;
3012 	/* XXX in sta mode need to pass log values for cwmin/max */
3013 	cwmin = MWL_EXPONENT_TO_VALUE(wmep->wmep_logcwmin);
3014 	cwmax = MWL_EXPONENT_TO_VALUE(wmep->wmep_logcwmax);
3015 	txoplim = wmep->wmep_txopLimit;		/* NB: units of 32us */
3016 
3017 	if (mwl_hal_setedcaparams(mh, txq->qnum, cwmin, cwmax, aifs, txoplim)) {
3018 		device_printf(sc->sc_dev, "unable to update hardware queue "
3019 			"parameters for %s traffic!\n",
3020 			ieee80211_wme_acnames[ac]);
3021 		return 0;
3022 	}
3023 	return 1;
3024 #undef MWL_EXPONENT_TO_VALUE
3025 }
3026 
3027 /*
3028  * Callback from the 802.11 layer to update WME parameters.
3029  */
3030 static int
3031 mwl_wme_update(struct ieee80211com *ic)
3032 {
3033 	struct mwl_softc *sc = ic->ic_ifp->if_softc;
3034 
3035 	return !mwl_txq_update(sc, WME_AC_BE) ||
3036 	    !mwl_txq_update(sc, WME_AC_BK) ||
3037 	    !mwl_txq_update(sc, WME_AC_VI) ||
3038 	    !mwl_txq_update(sc, WME_AC_VO) ? EIO : 0;
3039 }
3040 
3041 /*
3042  * Reclaim resources for a setup queue.
3043  */
3044 static void
3045 mwl_tx_cleanupq(struct mwl_softc *sc, struct mwl_txq *txq)
3046 {
3047 	/* XXX hal work? */
3048 	MWL_TXQ_LOCK_DESTROY(txq);
3049 }
3050 
3051 /*
3052  * Reclaim all tx queue resources.
3053  */
3054 static void
3055 mwl_tx_cleanup(struct mwl_softc *sc)
3056 {
3057 	int i;
3058 
3059 	for (i = 0; i < MWL_NUM_TX_QUEUES; i++)
3060 		mwl_tx_cleanupq(sc, &sc->sc_txq[i]);
3061 }
3062 
3063 static int
3064 mwl_tx_dmasetup(struct mwl_softc *sc, struct mwl_txbuf *bf, struct mbuf *m0)
3065 {
3066 	struct mbuf *m;
3067 	int error;
3068 
3069 	/*
3070 	 * Load the DMA map so any coalescing is done.  This
3071 	 * also calculates the number of descriptors we need.
3072 	 */
3073 	error = bus_dmamap_load_mbuf_sg(sc->sc_dmat, bf->bf_dmamap, m0,
3074 				     bf->bf_segs, &bf->bf_nseg,
3075 				     BUS_DMA_NOWAIT);
3076 	if (error == EFBIG) {
3077 		/* XXX packet requires too many descriptors */
3078 		bf->bf_nseg = MWL_TXDESC+1;
3079 	} else if (error != 0) {
3080 		sc->sc_stats.mst_tx_busdma++;
3081 		m_freem(m0);
3082 		return error;
3083 	}
3084 	/*
3085 	 * Discard null packets and check for packets that
3086 	 * require too many TX descriptors.  We try to convert
3087 	 * the latter to a cluster.
3088 	 */
3089 	if (error == EFBIG) {		/* too many desc's, linearize */
3090 		sc->sc_stats.mst_tx_linear++;
3091 #if MWL_TXDESC > 1
3092 		m = m_collapse(m0, M_NOWAIT, MWL_TXDESC);
3093 #else
3094 		m = m_defrag(m0, M_NOWAIT);
3095 #endif
3096 		if (m == NULL) {
3097 			m_freem(m0);
3098 			sc->sc_stats.mst_tx_nombuf++;
3099 			return ENOMEM;
3100 		}
3101 		m0 = m;
3102 		error = bus_dmamap_load_mbuf_sg(sc->sc_dmat, bf->bf_dmamap, m0,
3103 					     bf->bf_segs, &bf->bf_nseg,
3104 					     BUS_DMA_NOWAIT);
3105 		if (error != 0) {
3106 			sc->sc_stats.mst_tx_busdma++;
3107 			m_freem(m0);
3108 			return error;
3109 		}
3110 		KASSERT(bf->bf_nseg <= MWL_TXDESC,
3111 		    ("too many segments after defrag; nseg %u", bf->bf_nseg));
3112 	} else if (bf->bf_nseg == 0) {		/* null packet, discard */
3113 		sc->sc_stats.mst_tx_nodata++;
3114 		m_freem(m0);
3115 		return EIO;
3116 	}
3117 	DPRINTF(sc, MWL_DEBUG_XMIT, "%s: m %p len %u\n",
3118 		__func__, m0, m0->m_pkthdr.len);
3119 	bus_dmamap_sync(sc->sc_dmat, bf->bf_dmamap, BUS_DMASYNC_PREWRITE);
3120 	bf->bf_m = m0;
3121 
3122 	return 0;
3123 }
3124 
3125 static __inline int
3126 mwl_cvtlegacyrate(int rate)
3127 {
3128 	switch (rate) {
3129 	case 2:	 return 0;
3130 	case 4:	 return 1;
3131 	case 11: return 2;
3132 	case 22: return 3;
3133 	case 44: return 4;
3134 	case 12: return 5;
3135 	case 18: return 6;
3136 	case 24: return 7;
3137 	case 36: return 8;
3138 	case 48: return 9;
3139 	case 72: return 10;
3140 	case 96: return 11;
3141 	case 108:return 12;
3142 	}
3143 	return 0;
3144 }
3145 
3146 /*
3147  * Calculate fixed tx rate information per client state;
3148  * this value is suitable for writing to the Format field
3149  * of a tx descriptor.
3150  */
3151 static uint16_t
3152 mwl_calcformat(uint8_t rate, const struct ieee80211_node *ni)
3153 {
3154 	uint16_t fmt;
3155 
3156 	fmt = SM(3, EAGLE_TXD_ANTENNA)
3157 	    | (IEEE80211_IS_CHAN_HT40D(ni->ni_chan) ?
3158 		EAGLE_TXD_EXTCHAN_LO : EAGLE_TXD_EXTCHAN_HI);
3159 	if (rate & IEEE80211_RATE_MCS) {	/* HT MCS */
3160 		fmt |= EAGLE_TXD_FORMAT_HT
3161 		    /* NB: 0x80 implicitly stripped from ucastrate */
3162 		    | SM(rate, EAGLE_TXD_RATE);
3163 		/* XXX short/long GI may be wrong; re-check */
3164 		if (IEEE80211_IS_CHAN_HT40(ni->ni_chan)) {
3165 			fmt |= EAGLE_TXD_CHW_40
3166 			    | (ni->ni_htcap & IEEE80211_HTCAP_SHORTGI40 ?
3167 			        EAGLE_TXD_GI_SHORT : EAGLE_TXD_GI_LONG);
3168 		} else {
3169 			fmt |= EAGLE_TXD_CHW_20
3170 			    | (ni->ni_htcap & IEEE80211_HTCAP_SHORTGI20 ?
3171 			        EAGLE_TXD_GI_SHORT : EAGLE_TXD_GI_LONG);
3172 		}
3173 	} else {			/* legacy rate */
3174 		fmt |= EAGLE_TXD_FORMAT_LEGACY
3175 		    | SM(mwl_cvtlegacyrate(rate), EAGLE_TXD_RATE)
3176 		    | EAGLE_TXD_CHW_20
3177 		    /* XXX iv_flags & IEEE80211_F_SHPREAMBLE? */
3178 		    | (ni->ni_capinfo & IEEE80211_CAPINFO_SHORT_PREAMBLE ?
3179 			EAGLE_TXD_PREAMBLE_SHORT : EAGLE_TXD_PREAMBLE_LONG);
3180 	}
3181 	return fmt;
3182 }
3183 
3184 static int
3185 mwl_tx_start(struct mwl_softc *sc, struct ieee80211_node *ni, struct mwl_txbuf *bf,
3186     struct mbuf *m0)
3187 {
3188 #define	IEEE80211_DIR_DSTODS(wh) \
3189 	((wh->i_fc[1] & IEEE80211_FC1_DIR_MASK) == IEEE80211_FC1_DIR_DSTODS)
3190 	struct ifnet *ifp = sc->sc_ifp;
3191 	struct ieee80211com *ic = ifp->if_l2com;
3192 	struct ieee80211vap *vap = ni->ni_vap;
3193 	int error, iswep, ismcast;
3194 	int hdrlen, copyhdrlen, pktlen;
3195 	struct mwl_txdesc *ds;
3196 	struct mwl_txq *txq;
3197 	struct ieee80211_frame *wh;
3198 	struct mwltxrec *tr;
3199 	struct mwl_node *mn;
3200 	uint16_t qos;
3201 #if MWL_TXDESC > 1
3202 	int i;
3203 #endif
3204 
3205 	wh = mtod(m0, struct ieee80211_frame *);
3206 	iswep = wh->i_fc[1] & IEEE80211_FC1_WEP;
3207 	ismcast = IEEE80211_IS_MULTICAST(wh->i_addr1);
3208 	hdrlen = ieee80211_anyhdrsize(wh);
3209 	copyhdrlen = hdrlen;
3210 	pktlen = m0->m_pkthdr.len;
3211 	if (IEEE80211_QOS_HAS_SEQ(wh)) {
3212 		if (IEEE80211_DIR_DSTODS(wh)) {
3213 			qos = *(uint16_t *)
3214 			    (((struct ieee80211_qosframe_addr4 *) wh)->i_qos);
3215 			copyhdrlen -= sizeof(qos);
3216 		} else
3217 			qos = *(uint16_t *)
3218 			    (((struct ieee80211_qosframe *) wh)->i_qos);
3219 	} else
3220 		qos = 0;
3221 
3222 	if (iswep) {
3223 		const struct ieee80211_cipher *cip;
3224 		struct ieee80211_key *k;
3225 
3226 		/*
3227 		 * Construct the 802.11 header+trailer for an encrypted
3228 		 * frame. The only reason this can fail is because of an
3229 		 * unknown or unsupported cipher/key type.
3230 		 *
3231 		 * NB: we do this even though the firmware will ignore
3232 		 *     what we've done for WEP and TKIP as we need the
3233 		 *     ExtIV filled in for CCMP and this also adjusts
3234 		 *     the headers which simplifies our work below.
3235 		 */
3236 		k = ieee80211_crypto_encap(ni, m0);
3237 		if (k == NULL) {
3238 			/*
3239 			 * This can happen when the key is yanked after the
3240 			 * frame was queued.  Just discard the frame; the
3241 			 * 802.11 layer counts failures and provides
3242 			 * debugging/diagnostics.
3243 			 */
3244 			m_freem(m0);
3245 			return EIO;
3246 		}
3247 		/*
3248 		 * Adjust the packet length for the crypto additions
3249 		 * done during encap and any other bits that the f/w
3250 		 * will add later on.
3251 		 */
3252 		cip = k->wk_cipher;
3253 		pktlen += cip->ic_header + cip->ic_miclen + cip->ic_trailer;
3254 
3255 		/* packet header may have moved, reset our local pointer */
3256 		wh = mtod(m0, struct ieee80211_frame *);
3257 	}
3258 
3259 	if (ieee80211_radiotap_active_vap(vap)) {
3260 		sc->sc_tx_th.wt_flags = 0;	/* XXX */
3261 		if (iswep)
3262 			sc->sc_tx_th.wt_flags |= IEEE80211_RADIOTAP_F_WEP;
3263 #if 0
3264 		sc->sc_tx_th.wt_rate = ds->DataRate;
3265 #endif
3266 		sc->sc_tx_th.wt_txpower = ni->ni_txpower;
3267 		sc->sc_tx_th.wt_antenna = sc->sc_txantenna;
3268 
3269 		ieee80211_radiotap_tx(vap, m0);
3270 	}
3271 	/*
3272 	 * Copy up/down the 802.11 header; the firmware requires
3273 	 * we present a 2-byte payload length followed by a
3274 	 * 4-address header (w/o QoS), followed (optionally) by
3275 	 * any WEP/ExtIV header (but only filled in for CCMP).
3276 	 * We are assured the mbuf has sufficient headroom to
3277 	 * prepend in-place by the setup of ic_headroom in
3278 	 * mwl_attach.
3279 	 */
3280 	if (hdrlen < sizeof(struct mwltxrec)) {
3281 		const int space = sizeof(struct mwltxrec) - hdrlen;
3282 		if (M_LEADINGSPACE(m0) < space) {
3283 			/* NB: should never happen */
3284 			device_printf(sc->sc_dev,
3285 			    "not enough headroom, need %d found %zd, "
3286 			    "m_flags 0x%x m_len %d\n",
3287 			    space, M_LEADINGSPACE(m0), m0->m_flags, m0->m_len);
3288 			ieee80211_dump_pkt(ic,
3289 			    mtod(m0, const uint8_t *), m0->m_len, 0, -1);
3290 			m_freem(m0);
3291 			sc->sc_stats.mst_tx_noheadroom++;
3292 			return EIO;
3293 		}
3294 		M_PREPEND(m0, space, M_NOWAIT);
3295 	}
3296 	tr = mtod(m0, struct mwltxrec *);
3297 	if (wh != (struct ieee80211_frame *) &tr->wh)
3298 		ovbcopy(wh, &tr->wh, hdrlen);
3299 	/*
3300 	 * Note: the "firmware length" is actually the length
3301 	 * of the fully formed "802.11 payload".  That is, it's
3302 	 * everything except for the 802.11 header.  In particular
3303 	 * this includes all crypto material including the MIC!
3304 	 */
3305 	tr->fwlen = htole16(pktlen - hdrlen);
3306 
3307 	/*
3308 	 * Load the DMA map so any coalescing is done.  This
3309 	 * also calculates the number of descriptors we need.
3310 	 */
3311 	error = mwl_tx_dmasetup(sc, bf, m0);
3312 	if (error != 0) {
3313 		/* NB: stat collected in mwl_tx_dmasetup */
3314 		DPRINTF(sc, MWL_DEBUG_XMIT,
3315 		    "%s: unable to setup dma\n", __func__);
3316 		return error;
3317 	}
3318 	bf->bf_node = ni;			/* NB: held reference */
3319 	m0 = bf->bf_m;				/* NB: may have changed */
3320 	tr = mtod(m0, struct mwltxrec *);
3321 	wh = (struct ieee80211_frame *)&tr->wh;
3322 
3323 	/*
3324 	 * Formulate tx descriptor.
3325 	 */
3326 	ds = bf->bf_desc;
3327 	txq = bf->bf_txq;
3328 
3329 	ds->QosCtrl = qos;			/* NB: already little-endian */
3330 #if MWL_TXDESC == 1
3331 	/*
3332 	 * NB: multiframes should be zero because the descriptors
3333 	 *     are initialized to zero.  This should handle the case
3334 	 *     where the driver is built with MWL_TXDESC=1 but we are
3335 	 *     using firmware with multi-segment support.
3336 	 */
3337 	ds->PktPtr = htole32(bf->bf_segs[0].ds_addr);
3338 	ds->PktLen = htole16(bf->bf_segs[0].ds_len);
3339 #else
3340 	ds->multiframes = htole32(bf->bf_nseg);
3341 	ds->PktLen = htole16(m0->m_pkthdr.len);
3342 	for (i = 0; i < bf->bf_nseg; i++) {
3343 		ds->PktPtrArray[i] = htole32(bf->bf_segs[i].ds_addr);
3344 		ds->PktLenArray[i] = htole16(bf->bf_segs[i].ds_len);
3345 	}
3346 #endif
3347 	/* NB: pPhysNext, DataRate, and SapPktInfo setup once, don't touch */
3348 	ds->Format = 0;
3349 	ds->pad = 0;
3350 	ds->ack_wcb_addr = 0;
3351 
3352 	mn = MWL_NODE(ni);
3353 	/*
3354 	 * Select transmit rate.
3355 	 */
3356 	switch (wh->i_fc[0] & IEEE80211_FC0_TYPE_MASK) {
3357 	case IEEE80211_FC0_TYPE_MGT:
3358 		sc->sc_stats.mst_tx_mgmt++;
3359 		/* fall thru... */
3360 	case IEEE80211_FC0_TYPE_CTL:
3361 		/* NB: assign to BE q to avoid bursting */
3362 		ds->TxPriority = MWL_WME_AC_BE;
3363 		break;
3364 	case IEEE80211_FC0_TYPE_DATA:
3365 		if (!ismcast) {
3366 			const struct ieee80211_txparam *tp = ni->ni_txparms;
3367 			/*
3368 			 * EAPOL frames get forced to a fixed rate and w/o
3369 			 * aggregation; otherwise check for any fixed rate
3370 			 * for the client (may depend on association state).
3371 			 */
3372 			if (m0->m_flags & M_EAPOL) {
3373 				const struct mwl_vap *mvp = MWL_VAP_CONST(vap);
3374 				ds->Format = mvp->mv_eapolformat;
3375 				ds->pad = htole16(
3376 				    EAGLE_TXD_FIXED_RATE | EAGLE_TXD_DONT_AGGR);
3377 			} else if (tp->ucastrate != IEEE80211_FIXED_RATE_NONE) {
3378 				/* XXX pre-calculate per node */
3379 				ds->Format = htole16(
3380 				    mwl_calcformat(tp->ucastrate, ni));
3381 				ds->pad = htole16(EAGLE_TXD_FIXED_RATE);
3382 			}
3383 			/* NB: EAPOL frames will never have qos set */
3384 			if (qos == 0)
3385 				ds->TxPriority = txq->qnum;
3386 #if MWL_MAXBA > 3
3387 			else if (mwl_bastream_match(&mn->mn_ba[3], qos))
3388 				ds->TxPriority = mn->mn_ba[3].txq;
3389 #endif
3390 #if MWL_MAXBA > 2
3391 			else if (mwl_bastream_match(&mn->mn_ba[2], qos))
3392 				ds->TxPriority = mn->mn_ba[2].txq;
3393 #endif
3394 #if MWL_MAXBA > 1
3395 			else if (mwl_bastream_match(&mn->mn_ba[1], qos))
3396 				ds->TxPriority = mn->mn_ba[1].txq;
3397 #endif
3398 #if MWL_MAXBA > 0
3399 			else if (mwl_bastream_match(&mn->mn_ba[0], qos))
3400 				ds->TxPriority = mn->mn_ba[0].txq;
3401 #endif
3402 			else
3403 				ds->TxPriority = txq->qnum;
3404 		} else
3405 			ds->TxPriority = txq->qnum;
3406 		break;
3407 	default:
3408 		if_printf(ifp, "bogus frame type 0x%x (%s)\n",
3409 			wh->i_fc[0] & IEEE80211_FC0_TYPE_MASK, __func__);
3410 		sc->sc_stats.mst_tx_badframetype++;
3411 		m_freem(m0);
3412 		return EIO;
3413 	}
3414 
3415 	if (IFF_DUMPPKTS_XMIT(sc))
3416 		ieee80211_dump_pkt(ic,
3417 		    mtod(m0, const uint8_t *)+sizeof(uint16_t),
3418 		    m0->m_len - sizeof(uint16_t), ds->DataRate, -1);
3419 
3420 	MWL_TXQ_LOCK(txq);
3421 	ds->Status = htole32(EAGLE_TXD_STATUS_FW_OWNED);
3422 	STAILQ_INSERT_TAIL(&txq->active, bf, bf_list);
3423 	MWL_TXDESC_SYNC(txq, ds, BUS_DMASYNC_PREREAD | BUS_DMASYNC_PREWRITE);
3424 
3425 	ifp->if_opackets++;
3426 	sc->sc_tx_timer = 5;
3427 	MWL_TXQ_UNLOCK(txq);
3428 
3429 	return 0;
3430 #undef	IEEE80211_DIR_DSTODS
3431 }
3432 
3433 static __inline int
3434 mwl_cvtlegacyrix(int rix)
3435 {
3436 #define	N(x)	(sizeof(x)/sizeof(x[0]))
3437 	static const int ieeerates[] =
3438 	    { 2, 4, 11, 22, 44, 12, 18, 24, 36, 48, 72, 96, 108 };
3439 	return (rix < N(ieeerates) ? ieeerates[rix] : 0);
3440 #undef N
3441 }
3442 
3443 /*
3444  * Process completed xmit descriptors from the specified queue.
3445  */
3446 static int
3447 mwl_tx_processq(struct mwl_softc *sc, struct mwl_txq *txq)
3448 {
3449 #define	EAGLE_TXD_STATUS_MCAST \
3450 	(EAGLE_TXD_STATUS_MULTICAST_TX | EAGLE_TXD_STATUS_BROADCAST_TX)
3451 	struct ifnet *ifp = sc->sc_ifp;
3452 	struct ieee80211com *ic = ifp->if_l2com;
3453 	struct mwl_txbuf *bf;
3454 	struct mwl_txdesc *ds;
3455 	struct ieee80211_node *ni;
3456 	struct mwl_node *an;
3457 	int nreaped;
3458 	uint32_t status;
3459 
3460 	DPRINTF(sc, MWL_DEBUG_TX_PROC, "%s: tx queue %u\n", __func__, txq->qnum);
3461 	for (nreaped = 0;; nreaped++) {
3462 		MWL_TXQ_LOCK(txq);
3463 		bf = STAILQ_FIRST(&txq->active);
3464 		if (bf == NULL) {
3465 			MWL_TXQ_UNLOCK(txq);
3466 			break;
3467 		}
3468 		ds = bf->bf_desc;
3469 		MWL_TXDESC_SYNC(txq, ds,
3470 		    BUS_DMASYNC_POSTREAD | BUS_DMASYNC_POSTWRITE);
3471 		if (ds->Status & htole32(EAGLE_TXD_STATUS_FW_OWNED)) {
3472 			MWL_TXQ_UNLOCK(txq);
3473 			break;
3474 		}
3475 		STAILQ_REMOVE_HEAD(&txq->active, bf_list);
3476 		MWL_TXQ_UNLOCK(txq);
3477 
3478 #ifdef MWL_DEBUG
3479 		if (sc->sc_debug & MWL_DEBUG_XMIT_DESC)
3480 			mwl_printtxbuf(bf, txq->qnum, nreaped);
3481 #endif
3482 		ni = bf->bf_node;
3483 		if (ni != NULL) {
3484 			an = MWL_NODE(ni);
3485 			status = le32toh(ds->Status);
3486 			if (status & EAGLE_TXD_STATUS_OK) {
3487 				uint16_t Format = le16toh(ds->Format);
3488 				uint8_t txant = MS(Format, EAGLE_TXD_ANTENNA);
3489 
3490 				sc->sc_stats.mst_ant_tx[txant]++;
3491 				if (status & EAGLE_TXD_STATUS_OK_RETRY)
3492 					sc->sc_stats.mst_tx_retries++;
3493 				if (status & EAGLE_TXD_STATUS_OK_MORE_RETRY)
3494 					sc->sc_stats.mst_tx_mretries++;
3495 				if (txq->qnum >= MWL_WME_AC_VO)
3496 					ic->ic_wme.wme_hipri_traffic++;
3497 				ni->ni_txrate = MS(Format, EAGLE_TXD_RATE);
3498 				if ((Format & EAGLE_TXD_FORMAT_HT) == 0) {
3499 					ni->ni_txrate = mwl_cvtlegacyrix(
3500 					    ni->ni_txrate);
3501 				} else
3502 					ni->ni_txrate |= IEEE80211_RATE_MCS;
3503 				sc->sc_stats.mst_tx_rate = ni->ni_txrate;
3504 			} else {
3505 				if (status & EAGLE_TXD_STATUS_FAILED_LINK_ERROR)
3506 					sc->sc_stats.mst_tx_linkerror++;
3507 				if (status & EAGLE_TXD_STATUS_FAILED_XRETRY)
3508 					sc->sc_stats.mst_tx_xretries++;
3509 				if (status & EAGLE_TXD_STATUS_FAILED_AGING)
3510 					sc->sc_stats.mst_tx_aging++;
3511 				if (bf->bf_m->m_flags & M_FF)
3512 					sc->sc_stats.mst_ff_txerr++;
3513 			}
3514 			/*
3515 			 * Do any tx complete callback.  Note this must
3516 			 * be done before releasing the node reference.
3517 			 * XXX no way to figure out if frame was ACK'd
3518 			 */
3519 			if (bf->bf_m->m_flags & M_TXCB) {
3520 				/* XXX strip fw len in case header inspected */
3521 				m_adj(bf->bf_m, sizeof(uint16_t));
3522 				ieee80211_process_callback(ni, bf->bf_m,
3523 					(status & EAGLE_TXD_STATUS_OK) == 0);
3524 			}
3525 			/*
3526 			 * Reclaim reference to node.
3527 			 *
3528 			 * NB: the node may be reclaimed here if, for example
3529 			 *     this is a DEAUTH message that was sent and the
3530 			 *     node was timed out due to inactivity.
3531 			 */
3532 			ieee80211_free_node(ni);
3533 		}
3534 		ds->Status = htole32(EAGLE_TXD_STATUS_IDLE);
3535 
3536 		bus_dmamap_sync(sc->sc_dmat, bf->bf_dmamap,
3537 		    BUS_DMASYNC_POSTWRITE);
3538 		bus_dmamap_unload(sc->sc_dmat, bf->bf_dmamap);
3539 		m_freem(bf->bf_m);
3540 
3541 		mwl_puttxbuf_tail(txq, bf);
3542 	}
3543 	return nreaped;
3544 #undef EAGLE_TXD_STATUS_MCAST
3545 }
3546 
3547 /*
3548  * Deferred processing of transmit interrupt; special-cased
3549  * for four hardware queues, 0-3.
3550  */
3551 static void
3552 mwl_tx_proc(void *arg, int npending)
3553 {
3554 	struct mwl_softc *sc = arg;
3555 	struct ifnet *ifp = sc->sc_ifp;
3556 	int nreaped;
3557 
3558 	/*
3559 	 * Process each active queue.
3560 	 */
3561 	nreaped = 0;
3562 	if (!STAILQ_EMPTY(&sc->sc_txq[0].active))
3563 		nreaped += mwl_tx_processq(sc, &sc->sc_txq[0]);
3564 	if (!STAILQ_EMPTY(&sc->sc_txq[1].active))
3565 		nreaped += mwl_tx_processq(sc, &sc->sc_txq[1]);
3566 	if (!STAILQ_EMPTY(&sc->sc_txq[2].active))
3567 		nreaped += mwl_tx_processq(sc, &sc->sc_txq[2]);
3568 	if (!STAILQ_EMPTY(&sc->sc_txq[3].active))
3569 		nreaped += mwl_tx_processq(sc, &sc->sc_txq[3]);
3570 
3571 	if (nreaped != 0) {
3572 		ifp->if_drv_flags &= ~IFF_DRV_OACTIVE;
3573 		sc->sc_tx_timer = 0;
3574 		if (!IFQ_IS_EMPTY(&ifp->if_snd)) {
3575 			/* NB: kick fw; the tx thread may have been preempted */
3576 			mwl_hal_txstart(sc->sc_mh, 0);
3577 			mwl_start(ifp);
3578 		}
3579 	}
3580 }
3581 
3582 static void
3583 mwl_tx_draintxq(struct mwl_softc *sc, struct mwl_txq *txq)
3584 {
3585 	struct ieee80211_node *ni;
3586 	struct mwl_txbuf *bf;
3587 	u_int ix;
3588 
3589 	/*
3590 	 * NB: this assumes output has been stopped and
3591 	 *     we do not need to block mwl_tx_tasklet
3592 	 */
3593 	for (ix = 0;; ix++) {
3594 		MWL_TXQ_LOCK(txq);
3595 		bf = STAILQ_FIRST(&txq->active);
3596 		if (bf == NULL) {
3597 			MWL_TXQ_UNLOCK(txq);
3598 			break;
3599 		}
3600 		STAILQ_REMOVE_HEAD(&txq->active, bf_list);
3601 		MWL_TXQ_UNLOCK(txq);
3602 #ifdef MWL_DEBUG
3603 		if (sc->sc_debug & MWL_DEBUG_RESET) {
3604 			struct ifnet *ifp = sc->sc_ifp;
3605 			struct ieee80211com *ic = ifp->if_l2com;
3606 			const struct mwltxrec *tr =
3607 			    mtod(bf->bf_m, const struct mwltxrec *);
3608 			mwl_printtxbuf(bf, txq->qnum, ix);
3609 			ieee80211_dump_pkt(ic, (const uint8_t *)&tr->wh,
3610 				bf->bf_m->m_len - sizeof(tr->fwlen), 0, -1);
3611 		}
3612 #endif /* MWL_DEBUG */
3613 		bus_dmamap_unload(sc->sc_dmat, bf->bf_dmamap);
3614 		ni = bf->bf_node;
3615 		if (ni != NULL) {
3616 			/*
3617 			 * Reclaim node reference.
3618 			 */
3619 			ieee80211_free_node(ni);
3620 		}
3621 		m_freem(bf->bf_m);
3622 
3623 		mwl_puttxbuf_tail(txq, bf);
3624 	}
3625 }
3626 
3627 /*
3628  * Drain the transmit queues and reclaim resources.
3629  */
3630 static void
3631 mwl_draintxq(struct mwl_softc *sc)
3632 {
3633 	struct ifnet *ifp = sc->sc_ifp;
3634 	int i;
3635 
3636 	for (i = 0; i < MWL_NUM_TX_QUEUES; i++)
3637 		mwl_tx_draintxq(sc, &sc->sc_txq[i]);
3638 	ifp->if_drv_flags &= ~IFF_DRV_OACTIVE;
3639 	sc->sc_tx_timer = 0;
3640 }
3641 
3642 #ifdef MWL_DIAGAPI
3643 /*
3644  * Reset the transmit queues to a pristine state after a fw download.
3645  */
3646 static void
3647 mwl_resettxq(struct mwl_softc *sc)
3648 {
3649 	int i;
3650 
3651 	for (i = 0; i < MWL_NUM_TX_QUEUES; i++)
3652 		mwl_txq_reset(sc, &sc->sc_txq[i]);
3653 }
3654 #endif /* MWL_DIAGAPI */
3655 
3656 /*
3657  * Clear the transmit queues of any frames submitted for the
3658  * specified vap.  This is done when the vap is deleted so we
3659  * don't potentially reference the vap after it is gone.
3660  * Note we cannot remove the frames; we only reclaim the node
3661  * reference.
3662  */
3663 static void
3664 mwl_cleartxq(struct mwl_softc *sc, struct ieee80211vap *vap)
3665 {
3666 	struct mwl_txq *txq;
3667 	struct mwl_txbuf *bf;
3668 	int i;
3669 
3670 	for (i = 0; i < MWL_NUM_TX_QUEUES; i++) {
3671 		txq = &sc->sc_txq[i];
3672 		MWL_TXQ_LOCK(txq);
3673 		STAILQ_FOREACH(bf, &txq->active, bf_list) {
3674 			struct ieee80211_node *ni = bf->bf_node;
3675 			if (ni != NULL && ni->ni_vap == vap) {
3676 				bf->bf_node = NULL;
3677 				ieee80211_free_node(ni);
3678 			}
3679 		}
3680 		MWL_TXQ_UNLOCK(txq);
3681 	}
3682 }
3683 
3684 static int
3685 mwl_recv_action(struct ieee80211_node *ni, const struct ieee80211_frame *wh,
3686 	const uint8_t *frm, const uint8_t *efrm)
3687 {
3688 	struct mwl_softc *sc = ni->ni_ic->ic_ifp->if_softc;
3689 	const struct ieee80211_action *ia;
3690 
3691 	ia = (const struct ieee80211_action *) frm;
3692 	if (ia->ia_category == IEEE80211_ACTION_CAT_HT &&
3693 	    ia->ia_action == IEEE80211_ACTION_HT_MIMOPWRSAVE) {
3694 		const struct ieee80211_action_ht_mimopowersave *mps =
3695 		    (const struct ieee80211_action_ht_mimopowersave *) ia;
3696 
3697 		mwl_hal_setmimops(sc->sc_mh, ni->ni_macaddr,
3698 		    mps->am_control & IEEE80211_A_HT_MIMOPWRSAVE_ENA,
3699 		    MS(mps->am_control, IEEE80211_A_HT_MIMOPWRSAVE_MODE));
3700 		return 0;
3701 	} else
3702 		return sc->sc_recv_action(ni, wh, frm, efrm);
3703 }
3704 
3705 static int
3706 mwl_addba_request(struct ieee80211_node *ni, struct ieee80211_tx_ampdu *tap,
3707 	int dialogtoken, int baparamset, int batimeout)
3708 {
3709 	struct mwl_softc *sc = ni->ni_ic->ic_ifp->if_softc;
3710 	struct ieee80211vap *vap = ni->ni_vap;
3711 	struct mwl_node *mn = MWL_NODE(ni);
3712 	struct mwl_bastate *bas;
3713 
3714 	bas = tap->txa_private;
3715 	if (bas == NULL) {
3716 		const MWL_HAL_BASTREAM *sp;
3717 		/*
3718 		 * Check for a free BA stream slot.
3719 		 */
3720 #if MWL_MAXBA > 3
3721 		if (mn->mn_ba[3].bastream == NULL)
3722 			bas = &mn->mn_ba[3];
3723 		else
3724 #endif
3725 #if MWL_MAXBA > 2
3726 		if (mn->mn_ba[2].bastream == NULL)
3727 			bas = &mn->mn_ba[2];
3728 		else
3729 #endif
3730 #if MWL_MAXBA > 1
3731 		if (mn->mn_ba[1].bastream == NULL)
3732 			bas = &mn->mn_ba[1];
3733 		else
3734 #endif
3735 #if MWL_MAXBA > 0
3736 		if (mn->mn_ba[0].bastream == NULL)
3737 			bas = &mn->mn_ba[0];
3738 		else
3739 #endif
3740 		{
3741 			/* sta already has max BA streams */
3742 			/* XXX assign BA stream to highest priority tid */
3743 			DPRINTF(sc, MWL_DEBUG_AMPDU,
3744 			    "%s: already has max bastreams\n", __func__);
3745 			sc->sc_stats.mst_ampdu_reject++;
3746 			return 0;
3747 		}
3748 		/* NB: no held reference to ni */
3749 		sp = mwl_hal_bastream_alloc(MWL_VAP(vap)->mv_hvap,
3750 		    (baparamset & IEEE80211_BAPS_POLICY_IMMEDIATE) != 0,
3751 		    ni->ni_macaddr, tap->txa_tid, ni->ni_htparam,
3752 		    ni, tap);
3753 		if (sp == NULL) {
3754 			/*
3755 			 * No available stream, return 0 so no
3756 			 * a-mpdu aggregation will be done.
3757 			 */
3758 			DPRINTF(sc, MWL_DEBUG_AMPDU,
3759 			    "%s: no bastream available\n", __func__);
3760 			sc->sc_stats.mst_ampdu_nostream++;
3761 			return 0;
3762 		}
3763 		DPRINTF(sc, MWL_DEBUG_AMPDU, "%s: alloc bastream %p\n",
3764 		    __func__, sp);
3765 		/* NB: qos is left zero so we won't match in mwl_tx_start */
3766 		bas->bastream = sp;
3767 		tap->txa_private = bas;
3768 	}
3769 	/* fetch current seq# from the firmware; if available */
3770 	if (mwl_hal_bastream_get_seqno(sc->sc_mh, bas->bastream,
3771 	    vap->iv_opmode == IEEE80211_M_STA ? vap->iv_myaddr : ni->ni_macaddr,
3772 	    &tap->txa_start) != 0)
3773 		tap->txa_start = 0;
3774 	return sc->sc_addba_request(ni, tap, dialogtoken, baparamset, batimeout);
3775 }
3776 
3777 static int
3778 mwl_addba_response(struct ieee80211_node *ni, struct ieee80211_tx_ampdu *tap,
3779 	int code, int baparamset, int batimeout)
3780 {
3781 	struct mwl_softc *sc = ni->ni_ic->ic_ifp->if_softc;
3782 	struct mwl_bastate *bas;
3783 
3784 	bas = tap->txa_private;
3785 	if (bas == NULL) {
3786 		/* XXX should not happen */
3787 		DPRINTF(sc, MWL_DEBUG_AMPDU,
3788 		    "%s: no BA stream allocated, TID %d\n",
3789 		    __func__, tap->txa_tid);
3790 		sc->sc_stats.mst_addba_nostream++;
3791 		return 0;
3792 	}
3793 	if (code == IEEE80211_STATUS_SUCCESS) {
3794 		struct ieee80211vap *vap = ni->ni_vap;
3795 		int bufsiz, error;
3796 
3797 		/*
3798 		 * Tell the firmware to setup the BA stream;
3799 		 * we know resources are available because we
3800 		 * pre-allocated one before forming the request.
3801 		 */
3802 		bufsiz = MS(baparamset, IEEE80211_BAPS_BUFSIZ);
3803 		if (bufsiz == 0)
3804 			bufsiz = IEEE80211_AGGR_BAWMAX;
3805 		error = mwl_hal_bastream_create(MWL_VAP(vap)->mv_hvap,
3806 		    bas->bastream, bufsiz, bufsiz, tap->txa_start);
3807 		if (error != 0) {
3808 			/*
3809 			 * Setup failed, return immediately so no a-mpdu
3810 			 * aggregation will be done.
3811 			 */
3812 			mwl_hal_bastream_destroy(sc->sc_mh, bas->bastream);
3813 			mwl_bastream_free(bas);
3814 			tap->txa_private = NULL;
3815 
3816 			DPRINTF(sc, MWL_DEBUG_AMPDU,
3817 			    "%s: create failed, error %d, bufsiz %d TID %d "
3818 			    "htparam 0x%x\n", __func__, error, bufsiz,
3819 			    tap->txa_tid, ni->ni_htparam);
3820 			sc->sc_stats.mst_bacreate_failed++;
3821 			return 0;
3822 		}
3823 		/* NB: cache txq to avoid ptr indirect */
3824 		mwl_bastream_setup(bas, tap->txa_tid, bas->bastream->txq);
3825 		DPRINTF(sc, MWL_DEBUG_AMPDU,
3826 		    "%s: bastream %p assigned to txq %d TID %d bufsiz %d "
3827 		    "htparam 0x%x\n", __func__, bas->bastream,
3828 		    bas->txq, tap->txa_tid, bufsiz, ni->ni_htparam);
3829 	} else {
3830 		/*
3831 		 * Other side NAK'd us; return the resources.
3832 		 */
3833 		DPRINTF(sc, MWL_DEBUG_AMPDU,
3834 		    "%s: request failed with code %d, destroy bastream %p\n",
3835 		    __func__, code, bas->bastream);
3836 		mwl_hal_bastream_destroy(sc->sc_mh, bas->bastream);
3837 		mwl_bastream_free(bas);
3838 		tap->txa_private = NULL;
3839 	}
3840 	/* NB: firmware sends BAR so we don't need to */
3841 	return sc->sc_addba_response(ni, tap, code, baparamset, batimeout);
3842 }
3843 
3844 static void
3845 mwl_addba_stop(struct ieee80211_node *ni, struct ieee80211_tx_ampdu *tap)
3846 {
3847 	struct mwl_softc *sc = ni->ni_ic->ic_ifp->if_softc;
3848 	struct mwl_bastate *bas;
3849 
3850 	bas = tap->txa_private;
3851 	if (bas != NULL) {
3852 		DPRINTF(sc, MWL_DEBUG_AMPDU, "%s: destroy bastream %p\n",
3853 		    __func__, bas->bastream);
3854 		mwl_hal_bastream_destroy(sc->sc_mh, bas->bastream);
3855 		mwl_bastream_free(bas);
3856 		tap->txa_private = NULL;
3857 	}
3858 	sc->sc_addba_stop(ni, tap);
3859 }
3860 
3861 /*
3862  * Setup the rx data structures.  This should only be
3863  * done once or we may get out of sync with the firmware.
3864  */
3865 static int
3866 mwl_startrecv(struct mwl_softc *sc)
3867 {
3868 	if (!sc->sc_recvsetup) {
3869 		struct mwl_rxbuf *bf, *prev;
3870 		struct mwl_rxdesc *ds;
3871 
3872 		prev = NULL;
3873 		STAILQ_FOREACH(bf, &sc->sc_rxbuf, bf_list) {
3874 			int error = mwl_rxbuf_init(sc, bf);
3875 			if (error != 0) {
3876 				DPRINTF(sc, MWL_DEBUG_RECV,
3877 					"%s: mwl_rxbuf_init failed %d\n",
3878 					__func__, error);
3879 				return error;
3880 			}
3881 			if (prev != NULL) {
3882 				ds = prev->bf_desc;
3883 				ds->pPhysNext = htole32(bf->bf_daddr);
3884 			}
3885 			prev = bf;
3886 		}
3887 		if (prev != NULL) {
3888 			ds = prev->bf_desc;
3889 			ds->pPhysNext =
3890 			    htole32(STAILQ_FIRST(&sc->sc_rxbuf)->bf_daddr);
3891 		}
3892 		sc->sc_recvsetup = 1;
3893 	}
3894 	mwl_mode_init(sc);		/* set filters, etc. */
3895 	return 0;
3896 }
3897 
3898 static MWL_HAL_APMODE
3899 mwl_getapmode(const struct ieee80211vap *vap, struct ieee80211_channel *chan)
3900 {
3901 	MWL_HAL_APMODE mode;
3902 
3903 	if (IEEE80211_IS_CHAN_HT(chan)) {
3904 		if (vap->iv_flags_ht & IEEE80211_FHT_PUREN)
3905 			mode = AP_MODE_N_ONLY;
3906 		else if (IEEE80211_IS_CHAN_5GHZ(chan))
3907 			mode = AP_MODE_AandN;
3908 		else if (vap->iv_flags & IEEE80211_F_PUREG)
3909 			mode = AP_MODE_GandN;
3910 		else
3911 			mode = AP_MODE_BandGandN;
3912 	} else if (IEEE80211_IS_CHAN_ANYG(chan)) {
3913 		if (vap->iv_flags & IEEE80211_F_PUREG)
3914 			mode = AP_MODE_G_ONLY;
3915 		else
3916 			mode = AP_MODE_MIXED;
3917 	} else if (IEEE80211_IS_CHAN_B(chan))
3918 		mode = AP_MODE_B_ONLY;
3919 	else if (IEEE80211_IS_CHAN_A(chan))
3920 		mode = AP_MODE_A_ONLY;
3921 	else
3922 		mode = AP_MODE_MIXED;		/* XXX should not happen? */
3923 	return mode;
3924 }
3925 
3926 static int
3927 mwl_setapmode(struct ieee80211vap *vap, struct ieee80211_channel *chan)
3928 {
3929 	struct mwl_hal_vap *hvap = MWL_VAP(vap)->mv_hvap;
3930 	return mwl_hal_setapmode(hvap, mwl_getapmode(vap, chan));
3931 }
3932 
3933 /*
3934  * Set/change channels.
3935  */
3936 static int
3937 mwl_chan_set(struct mwl_softc *sc, struct ieee80211_channel *chan)
3938 {
3939 	struct mwl_hal *mh = sc->sc_mh;
3940 	struct ifnet *ifp = sc->sc_ifp;
3941 	struct ieee80211com *ic = ifp->if_l2com;
3942 	MWL_HAL_CHANNEL hchan;
3943 	int maxtxpow;
3944 
3945 	DPRINTF(sc, MWL_DEBUG_RESET, "%s: chan %u MHz/flags 0x%x\n",
3946 	    __func__, chan->ic_freq, chan->ic_flags);
3947 
3948 	/*
3949 	 * Convert to a HAL channel description with
3950 	 * the flags constrained to reflect the current
3951 	 * operating mode.
3952 	 */
3953 	mwl_mapchan(&hchan, chan);
3954 	mwl_hal_intrset(mh, 0);		/* disable interrupts */
3955 #if 0
3956 	mwl_draintxq(sc);		/* clear pending tx frames */
3957 #endif
3958 	mwl_hal_setchannel(mh, &hchan);
3959 	/*
3960 	 * Tx power is cap'd by the regulatory setting and
3961 	 * possibly a user-set limit.  We pass the min of
3962 	 * these to the hal to apply them to the cal data
3963 	 * for this channel.
3964 	 * XXX min bound?
3965 	 */
3966 	maxtxpow = 2*chan->ic_maxregpower;
3967 	if (maxtxpow > ic->ic_txpowlimit)
3968 		maxtxpow = ic->ic_txpowlimit;
3969 	mwl_hal_settxpower(mh, &hchan, maxtxpow / 2);
3970 	/* NB: potentially change mcast/mgt rates */
3971 	mwl_setcurchanrates(sc);
3972 
3973 	/*
3974 	 * Update internal state.
3975 	 */
3976 	sc->sc_tx_th.wt_chan_freq = htole16(chan->ic_freq);
3977 	sc->sc_rx_th.wr_chan_freq = htole16(chan->ic_freq);
3978 	if (IEEE80211_IS_CHAN_A(chan)) {
3979 		sc->sc_tx_th.wt_chan_flags = htole16(IEEE80211_CHAN_A);
3980 		sc->sc_rx_th.wr_chan_flags = htole16(IEEE80211_CHAN_A);
3981 	} else if (IEEE80211_IS_CHAN_ANYG(chan)) {
3982 		sc->sc_tx_th.wt_chan_flags = htole16(IEEE80211_CHAN_G);
3983 		sc->sc_rx_th.wr_chan_flags = htole16(IEEE80211_CHAN_G);
3984 	} else {
3985 		sc->sc_tx_th.wt_chan_flags = htole16(IEEE80211_CHAN_B);
3986 		sc->sc_rx_th.wr_chan_flags = htole16(IEEE80211_CHAN_B);
3987 	}
3988 	sc->sc_curchan = hchan;
3989 	mwl_hal_intrset(mh, sc->sc_imask);
3990 
3991 	return 0;
3992 }
3993 
3994 static void
3995 mwl_scan_start(struct ieee80211com *ic)
3996 {
3997 	struct ifnet *ifp = ic->ic_ifp;
3998 	struct mwl_softc *sc = ifp->if_softc;
3999 
4000 	DPRINTF(sc, MWL_DEBUG_STATE, "%s\n", __func__);
4001 }
4002 
4003 static void
4004 mwl_scan_end(struct ieee80211com *ic)
4005 {
4006 	struct ifnet *ifp = ic->ic_ifp;
4007 	struct mwl_softc *sc = ifp->if_softc;
4008 
4009 	DPRINTF(sc, MWL_DEBUG_STATE, "%s\n", __func__);
4010 }
4011 
4012 static void
4013 mwl_set_channel(struct ieee80211com *ic)
4014 {
4015 	struct ifnet *ifp = ic->ic_ifp;
4016 	struct mwl_softc *sc = ifp->if_softc;
4017 
4018 	(void) mwl_chan_set(sc, ic->ic_curchan);
4019 }
4020 
4021 /*
4022  * Handle a channel switch request.  We inform the firmware
4023  * and mark the global state to suppress various actions.
4024  * NB: we issue only one request to the fw; we may be called
4025  * multiple times if there are multiple vap's.
4026  */
4027 static void
4028 mwl_startcsa(struct ieee80211vap *vap)
4029 {
4030 	struct ieee80211com *ic = vap->iv_ic;
4031 	struct mwl_softc *sc = ic->ic_ifp->if_softc;
4032 	MWL_HAL_CHANNEL hchan;
4033 
4034 	if (sc->sc_csapending)
4035 		return;
4036 
4037 	mwl_mapchan(&hchan, ic->ic_csa_newchan);
4038 	/* 1 =>'s quiet channel */
4039 	mwl_hal_setchannelswitchie(sc->sc_mh, &hchan, 1, ic->ic_csa_count);
4040 	sc->sc_csapending = 1;
4041 }
4042 
4043 /*
4044  * Plumb any static WEP key for the station.  This is
4045  * necessary as we must propagate the key from the
4046  * global key table of the vap to each sta db entry.
4047  */
4048 static void
4049 mwl_setanywepkey(struct ieee80211vap *vap, const uint8_t mac[IEEE80211_ADDR_LEN])
4050 {
4051 	if ((vap->iv_flags & (IEEE80211_F_PRIVACY|IEEE80211_F_WPA)) ==
4052 		IEEE80211_F_PRIVACY &&
4053 	    vap->iv_def_txkey != IEEE80211_KEYIX_NONE &&
4054 	    vap->iv_nw_keys[vap->iv_def_txkey].wk_keyix != IEEE80211_KEYIX_NONE)
4055 		(void) mwl_key_set(vap, &vap->iv_nw_keys[vap->iv_def_txkey], mac);
4056 }
4057 
4058 static int
4059 mwl_peerstadb(struct ieee80211_node *ni, int aid, int staid, MWL_HAL_PEERINFO *pi)
4060 {
4061 #define	WME(ie) ((const struct ieee80211_wme_info *) ie)
4062 	struct ieee80211vap *vap = ni->ni_vap;
4063 	struct mwl_hal_vap *hvap;
4064 	int error;
4065 
4066 	if (vap->iv_opmode == IEEE80211_M_WDS) {
4067 		/*
4068 		 * WDS vap's do not have a f/w vap; instead they piggyback
4069 		 * on an AP vap and we must install the sta db entry and
4070 		 * crypto state using that AP's handle (the WDS vap has none).
4071 		 */
4072 		hvap = MWL_VAP(vap)->mv_ap_hvap;
4073 	} else
4074 		hvap = MWL_VAP(vap)->mv_hvap;
4075 	error = mwl_hal_newstation(hvap, ni->ni_macaddr,
4076 	    aid, staid, pi,
4077 	    ni->ni_flags & (IEEE80211_NODE_QOS | IEEE80211_NODE_HT),
4078 	    ni->ni_ies.wme_ie != NULL ? WME(ni->ni_ies.wme_ie)->wme_info : 0);
4079 	if (error == 0) {
4080 		/*
4081 		 * Setup security for this station.  For sta mode this is
4082 		 * needed even though do the same thing on transition to
4083 		 * AUTH state because the call to mwl_hal_newstation
4084 		 * clobbers the crypto state we setup.
4085 		 */
4086 		mwl_setanywepkey(vap, ni->ni_macaddr);
4087 	}
4088 	return error;
4089 #undef WME
4090 }
4091 
4092 static void
4093 mwl_setglobalkeys(struct ieee80211vap *vap)
4094 {
4095 	struct ieee80211_key *wk;
4096 
4097 	wk = &vap->iv_nw_keys[0];
4098 	for (; wk < &vap->iv_nw_keys[IEEE80211_WEP_NKID]; wk++)
4099 		if (wk->wk_keyix != IEEE80211_KEYIX_NONE)
4100 			(void) mwl_key_set(vap, wk, vap->iv_myaddr);
4101 }
4102 
4103 /*
4104  * Convert a legacy rate set to a firmware bitmask.
4105  */
4106 static uint32_t
4107 get_rate_bitmap(const struct ieee80211_rateset *rs)
4108 {
4109 	uint32_t rates;
4110 	int i;
4111 
4112 	rates = 0;
4113 	for (i = 0; i < rs->rs_nrates; i++)
4114 		switch (rs->rs_rates[i] & IEEE80211_RATE_VAL) {
4115 		case 2:	  rates |= 0x001; break;
4116 		case 4:	  rates |= 0x002; break;
4117 		case 11:  rates |= 0x004; break;
4118 		case 22:  rates |= 0x008; break;
4119 		case 44:  rates |= 0x010; break;
4120 		case 12:  rates |= 0x020; break;
4121 		case 18:  rates |= 0x040; break;
4122 		case 24:  rates |= 0x080; break;
4123 		case 36:  rates |= 0x100; break;
4124 		case 48:  rates |= 0x200; break;
4125 		case 72:  rates |= 0x400; break;
4126 		case 96:  rates |= 0x800; break;
4127 		case 108: rates |= 0x1000; break;
4128 		}
4129 	return rates;
4130 }
4131 
4132 /*
4133  * Construct an HT firmware bitmask from an HT rate set.
4134  */
4135 static uint32_t
4136 get_htrate_bitmap(const struct ieee80211_htrateset *rs)
4137 {
4138 	uint32_t rates;
4139 	int i;
4140 
4141 	rates = 0;
4142 	for (i = 0; i < rs->rs_nrates; i++) {
4143 		if (rs->rs_rates[i] < 16)
4144 			rates |= 1<<rs->rs_rates[i];
4145 	}
4146 	return rates;
4147 }
4148 
4149 /*
4150  * Craft station database entry for station.
4151  * NB: use host byte order here, the hal handles byte swapping.
4152  */
4153 static MWL_HAL_PEERINFO *
4154 mkpeerinfo(MWL_HAL_PEERINFO *pi, const struct ieee80211_node *ni)
4155 {
4156 	const struct ieee80211vap *vap = ni->ni_vap;
4157 
4158 	memset(pi, 0, sizeof(*pi));
4159 	pi->LegacyRateBitMap = get_rate_bitmap(&ni->ni_rates);
4160 	pi->CapInfo = ni->ni_capinfo;
4161 	if (ni->ni_flags & IEEE80211_NODE_HT) {
4162 		/* HT capabilities, etc */
4163 		pi->HTCapabilitiesInfo = ni->ni_htcap;
4164 		/* XXX pi.HTCapabilitiesInfo */
4165 	        pi->MacHTParamInfo = ni->ni_htparam;
4166 		pi->HTRateBitMap = get_htrate_bitmap(&ni->ni_htrates);
4167 		pi->AddHtInfo.ControlChan = ni->ni_htctlchan;
4168 		pi->AddHtInfo.AddChan = ni->ni_ht2ndchan;
4169 		pi->AddHtInfo.OpMode = ni->ni_htopmode;
4170 		pi->AddHtInfo.stbc = ni->ni_htstbc;
4171 
4172 		/* constrain according to local configuration */
4173 		if ((vap->iv_flags_ht & IEEE80211_FHT_SHORTGI40) == 0)
4174 			pi->HTCapabilitiesInfo &= ~IEEE80211_HTCAP_SHORTGI40;
4175 		if ((vap->iv_flags_ht & IEEE80211_FHT_SHORTGI20) == 0)
4176 			pi->HTCapabilitiesInfo &= ~IEEE80211_HTCAP_SHORTGI20;
4177 		if (ni->ni_chw != 40)
4178 			pi->HTCapabilitiesInfo &= ~IEEE80211_HTCAP_CHWIDTH40;
4179 	}
4180 	return pi;
4181 }
4182 
4183 /*
4184  * Re-create the local sta db entry for a vap to ensure
4185  * up to date WME state is pushed to the firmware.  Because
4186  * this resets crypto state this must be followed by a
4187  * reload of any keys in the global key table.
4188  */
4189 static int
4190 mwl_localstadb(struct ieee80211vap *vap)
4191 {
4192 #define	WME(ie) ((const struct ieee80211_wme_info *) ie)
4193 	struct mwl_hal_vap *hvap = MWL_VAP(vap)->mv_hvap;
4194 	struct ieee80211_node *bss;
4195 	MWL_HAL_PEERINFO pi;
4196 	int error;
4197 
4198 	switch (vap->iv_opmode) {
4199 	case IEEE80211_M_STA:
4200 		bss = vap->iv_bss;
4201 		error = mwl_hal_newstation(hvap, vap->iv_myaddr, 0, 0,
4202 		    vap->iv_state == IEEE80211_S_RUN ?
4203 			mkpeerinfo(&pi, bss) : NULL,
4204 		    (bss->ni_flags & (IEEE80211_NODE_QOS | IEEE80211_NODE_HT)),
4205 		    bss->ni_ies.wme_ie != NULL ?
4206 			WME(bss->ni_ies.wme_ie)->wme_info : 0);
4207 		if (error == 0)
4208 			mwl_setglobalkeys(vap);
4209 		break;
4210 	case IEEE80211_M_HOSTAP:
4211 	case IEEE80211_M_MBSS:
4212 		error = mwl_hal_newstation(hvap, vap->iv_myaddr,
4213 		    0, 0, NULL, vap->iv_flags & IEEE80211_F_WME, 0);
4214 		if (error == 0)
4215 			mwl_setglobalkeys(vap);
4216 		break;
4217 	default:
4218 		error = 0;
4219 		break;
4220 	}
4221 	return error;
4222 #undef WME
4223 }
4224 
4225 static int
4226 mwl_newstate(struct ieee80211vap *vap, enum ieee80211_state nstate, int arg)
4227 {
4228 	struct mwl_vap *mvp = MWL_VAP(vap);
4229 	struct mwl_hal_vap *hvap = mvp->mv_hvap;
4230 	struct ieee80211com *ic = vap->iv_ic;
4231 	struct ieee80211_node *ni = NULL;
4232 	struct ifnet *ifp = ic->ic_ifp;
4233 	struct mwl_softc *sc = ifp->if_softc;
4234 	struct mwl_hal *mh = sc->sc_mh;
4235 	enum ieee80211_state ostate = vap->iv_state;
4236 	int error;
4237 
4238 	DPRINTF(sc, MWL_DEBUG_STATE, "%s: %s: %s -> %s\n",
4239 	    vap->iv_ifp->if_xname, __func__,
4240 	    ieee80211_state_name[ostate], ieee80211_state_name[nstate]);
4241 
4242 	callout_stop(&sc->sc_timer);
4243 	/*
4244 	 * Clear current radar detection state.
4245 	 */
4246 	if (ostate == IEEE80211_S_CAC) {
4247 		/* stop quiet mode radar detection */
4248 		mwl_hal_setradardetection(mh, DR_CHK_CHANNEL_AVAILABLE_STOP);
4249 	} else if (sc->sc_radarena) {
4250 		/* stop in-service radar detection */
4251 		mwl_hal_setradardetection(mh, DR_DFS_DISABLE);
4252 		sc->sc_radarena = 0;
4253 	}
4254 	/*
4255 	 * Carry out per-state actions before doing net80211 work.
4256 	 */
4257 	if (nstate == IEEE80211_S_INIT) {
4258 		/* NB: only ap+sta vap's have a fw entity */
4259 		if (hvap != NULL)
4260 			mwl_hal_stop(hvap);
4261 	} else if (nstate == IEEE80211_S_SCAN) {
4262 		mwl_hal_start(hvap);
4263 		/* NB: this disables beacon frames */
4264 		mwl_hal_setinframode(hvap);
4265 	} else if (nstate == IEEE80211_S_AUTH) {
4266 		/*
4267 		 * Must create a sta db entry in case a WEP key needs to
4268 		 * be plumbed.  This entry will be overwritten if we
4269 		 * associate; otherwise it will be reclaimed on node free.
4270 		 */
4271 		ni = vap->iv_bss;
4272 		MWL_NODE(ni)->mn_hvap = hvap;
4273 		(void) mwl_peerstadb(ni, 0, 0, NULL);
4274 	} else if (nstate == IEEE80211_S_CSA) {
4275 		/* XXX move to below? */
4276 		if (vap->iv_opmode == IEEE80211_M_HOSTAP ||
4277 		    vap->iv_opmode == IEEE80211_M_MBSS)
4278 			mwl_startcsa(vap);
4279 	} else if (nstate == IEEE80211_S_CAC) {
4280 		/* XXX move to below? */
4281 		/* stop ap xmit and enable quiet mode radar detection */
4282 		mwl_hal_setradardetection(mh, DR_CHK_CHANNEL_AVAILABLE_START);
4283 	}
4284 
4285 	/*
4286 	 * Invoke the parent method to do net80211 work.
4287 	 */
4288 	error = mvp->mv_newstate(vap, nstate, arg);
4289 
4290 	/*
4291 	 * Carry out work that must be done after net80211 runs;
4292 	 * this work requires up to date state (e.g. iv_bss).
4293 	 */
4294 	if (error == 0 && nstate == IEEE80211_S_RUN) {
4295 		/* NB: collect bss node again, it may have changed */
4296 		ni = vap->iv_bss;
4297 
4298 		DPRINTF(sc, MWL_DEBUG_STATE,
4299 		    "%s: %s(RUN): iv_flags 0x%08x bintvl %d bssid %s "
4300 		    "capinfo 0x%04x chan %d\n",
4301 		    vap->iv_ifp->if_xname, __func__, vap->iv_flags,
4302 		    ni->ni_intval, ether_sprintf(ni->ni_bssid), ni->ni_capinfo,
4303 		    ieee80211_chan2ieee(ic, ic->ic_curchan));
4304 
4305 		/*
4306 		 * Recreate local sta db entry to update WME/HT state.
4307 		 */
4308 		mwl_localstadb(vap);
4309 		switch (vap->iv_opmode) {
4310 		case IEEE80211_M_HOSTAP:
4311 		case IEEE80211_M_MBSS:
4312 			if (ostate == IEEE80211_S_CAC) {
4313 				/* enable in-service radar detection */
4314 				mwl_hal_setradardetection(mh,
4315 				    DR_IN_SERVICE_MONITOR_START);
4316 				sc->sc_radarena = 1;
4317 			}
4318 			/*
4319 			 * Allocate and setup the beacon frame
4320 			 * (and related state).
4321 			 */
4322 			error = mwl_reset_vap(vap, IEEE80211_S_RUN);
4323 			if (error != 0) {
4324 				DPRINTF(sc, MWL_DEBUG_STATE,
4325 				    "%s: beacon setup failed, error %d\n",
4326 				    __func__, error);
4327 				goto bad;
4328 			}
4329 			/* NB: must be after setting up beacon */
4330 			mwl_hal_start(hvap);
4331 			break;
4332 		case IEEE80211_M_STA:
4333 			DPRINTF(sc, MWL_DEBUG_STATE, "%s: %s: aid 0x%x\n",
4334 			    vap->iv_ifp->if_xname, __func__, ni->ni_associd);
4335 			/*
4336 			 * Set state now that we're associated.
4337 			 */
4338 			mwl_hal_setassocid(hvap, ni->ni_bssid, ni->ni_associd);
4339 			mwl_setrates(vap);
4340 			mwl_hal_setrtsthreshold(hvap, vap->iv_rtsthreshold);
4341 			if ((vap->iv_flags & IEEE80211_F_DWDS) &&
4342 			    sc->sc_ndwdsvaps++ == 0)
4343 				mwl_hal_setdwds(mh, 1);
4344 			break;
4345 		case IEEE80211_M_WDS:
4346 			DPRINTF(sc, MWL_DEBUG_STATE, "%s: %s: bssid %s\n",
4347 			    vap->iv_ifp->if_xname, __func__,
4348 			    ether_sprintf(ni->ni_bssid));
4349 			mwl_seteapolformat(vap);
4350 			break;
4351 		default:
4352 			break;
4353 		}
4354 		/*
4355 		 * Set CS mode according to operating channel;
4356 		 * this mostly an optimization for 5GHz.
4357 		 *
4358 		 * NB: must follow mwl_hal_start which resets csmode
4359 		 */
4360 		if (IEEE80211_IS_CHAN_5GHZ(ic->ic_bsschan))
4361 			mwl_hal_setcsmode(mh, CSMODE_AGGRESSIVE);
4362 		else
4363 			mwl_hal_setcsmode(mh, CSMODE_AUTO_ENA);
4364 		/*
4365 		 * Start timer to prod firmware.
4366 		 */
4367 		if (sc->sc_ageinterval != 0)
4368 			callout_reset(&sc->sc_timer, sc->sc_ageinterval*hz,
4369 			    mwl_agestations, sc);
4370 	} else if (nstate == IEEE80211_S_SLEEP) {
4371 		/* XXX set chip in power save */
4372 	} else if ((vap->iv_flags & IEEE80211_F_DWDS) &&
4373 	    --sc->sc_ndwdsvaps == 0)
4374 		mwl_hal_setdwds(mh, 0);
4375 bad:
4376 	return error;
4377 }
4378 
4379 /*
4380  * Manage station id's; these are separate from AID's
4381  * as AID's may have values out of the range of possible
4382  * station id's acceptable to the firmware.
4383  */
4384 static int
4385 allocstaid(struct mwl_softc *sc, int aid)
4386 {
4387 	int staid;
4388 
4389 	if (!(0 < aid && aid < MWL_MAXSTAID) || isset(sc->sc_staid, aid)) {
4390 		/* NB: don't use 0 */
4391 		for (staid = 1; staid < MWL_MAXSTAID; staid++)
4392 			if (isclr(sc->sc_staid, staid))
4393 				break;
4394 	} else
4395 		staid = aid;
4396 	setbit(sc->sc_staid, staid);
4397 	return staid;
4398 }
4399 
4400 static void
4401 delstaid(struct mwl_softc *sc, int staid)
4402 {
4403 	clrbit(sc->sc_staid, staid);
4404 }
4405 
4406 /*
4407  * Setup driver-specific state for a newly associated node.
4408  * Note that we're called also on a re-associate, the isnew
4409  * param tells us if this is the first time or not.
4410  */
4411 static void
4412 mwl_newassoc(struct ieee80211_node *ni, int isnew)
4413 {
4414 	struct ieee80211vap *vap = ni->ni_vap;
4415         struct mwl_softc *sc = vap->iv_ic->ic_ifp->if_softc;
4416 	struct mwl_node *mn = MWL_NODE(ni);
4417 	MWL_HAL_PEERINFO pi;
4418 	uint16_t aid;
4419 	int error;
4420 
4421 	aid = IEEE80211_AID(ni->ni_associd);
4422 	if (isnew) {
4423 		mn->mn_staid = allocstaid(sc, aid);
4424 		mn->mn_hvap = MWL_VAP(vap)->mv_hvap;
4425 	} else {
4426 		mn = MWL_NODE(ni);
4427 		/* XXX reset BA stream? */
4428 	}
4429 	DPRINTF(sc, MWL_DEBUG_NODE, "%s: mac %s isnew %d aid %d staid %d\n",
4430 	    __func__, ether_sprintf(ni->ni_macaddr), isnew, aid, mn->mn_staid);
4431 	error = mwl_peerstadb(ni, aid, mn->mn_staid, mkpeerinfo(&pi, ni));
4432 	if (error != 0) {
4433 		DPRINTF(sc, MWL_DEBUG_NODE,
4434 		    "%s: error %d creating sta db entry\n",
4435 		    __func__, error);
4436 		/* XXX how to deal with error? */
4437 	}
4438 }
4439 
4440 /*
4441  * Periodically poke the firmware to age out station state
4442  * (power save queues, pending tx aggregates).
4443  */
4444 static void
4445 mwl_agestations(void *arg)
4446 {
4447 	struct mwl_softc *sc = arg;
4448 
4449 	mwl_hal_setkeepalive(sc->sc_mh);
4450 	if (sc->sc_ageinterval != 0)		/* NB: catch dynamic changes */
4451 		callout_schedule(&sc->sc_timer, sc->sc_ageinterval*hz);
4452 }
4453 
4454 static const struct mwl_hal_channel *
4455 findhalchannel(const MWL_HAL_CHANNELINFO *ci, int ieee)
4456 {
4457 	int i;
4458 
4459 	for (i = 0; i < ci->nchannels; i++) {
4460 		const struct mwl_hal_channel *hc = &ci->channels[i];
4461 		if (hc->ieee == ieee)
4462 			return hc;
4463 	}
4464 	return NULL;
4465 }
4466 
4467 static int
4468 mwl_setregdomain(struct ieee80211com *ic, struct ieee80211_regdomain *rd,
4469 	int nchan, struct ieee80211_channel chans[])
4470 {
4471 	struct mwl_softc *sc = ic->ic_ifp->if_softc;
4472 	struct mwl_hal *mh = sc->sc_mh;
4473 	const MWL_HAL_CHANNELINFO *ci;
4474 	int i;
4475 
4476 	for (i = 0; i < nchan; i++) {
4477 		struct ieee80211_channel *c = &chans[i];
4478 		const struct mwl_hal_channel *hc;
4479 
4480 		if (IEEE80211_IS_CHAN_2GHZ(c)) {
4481 			mwl_hal_getchannelinfo(mh, MWL_FREQ_BAND_2DOT4GHZ,
4482 			    IEEE80211_IS_CHAN_HT40(c) ?
4483 				MWL_CH_40_MHz_WIDTH : MWL_CH_20_MHz_WIDTH, &ci);
4484 		} else if (IEEE80211_IS_CHAN_5GHZ(c)) {
4485 			mwl_hal_getchannelinfo(mh, MWL_FREQ_BAND_5GHZ,
4486 			    IEEE80211_IS_CHAN_HT40(c) ?
4487 				MWL_CH_40_MHz_WIDTH : MWL_CH_20_MHz_WIDTH, &ci);
4488 		} else {
4489 			if_printf(ic->ic_ifp,
4490 			    "%s: channel %u freq %u/0x%x not 2.4/5GHz\n",
4491 			    __func__, c->ic_ieee, c->ic_freq, c->ic_flags);
4492 			return EINVAL;
4493 		}
4494 		/*
4495 		 * Verify channel has cal data and cap tx power.
4496 		 */
4497 		hc = findhalchannel(ci, c->ic_ieee);
4498 		if (hc != NULL) {
4499 			if (c->ic_maxpower > 2*hc->maxTxPow)
4500 				c->ic_maxpower = 2*hc->maxTxPow;
4501 			goto next;
4502 		}
4503 		if (IEEE80211_IS_CHAN_HT40(c)) {
4504 			/*
4505 			 * Look for the extension channel since the
4506 			 * hal table only has the primary channel.
4507 			 */
4508 			hc = findhalchannel(ci, c->ic_extieee);
4509 			if (hc != NULL) {
4510 				if (c->ic_maxpower > 2*hc->maxTxPow)
4511 					c->ic_maxpower = 2*hc->maxTxPow;
4512 				goto next;
4513 			}
4514 		}
4515 		if_printf(ic->ic_ifp,
4516 		    "%s: no cal data for channel %u ext %u freq %u/0x%x\n",
4517 		    __func__, c->ic_ieee, c->ic_extieee,
4518 		    c->ic_freq, c->ic_flags);
4519 		return EINVAL;
4520 	next:
4521 		;
4522 	}
4523 	return 0;
4524 }
4525 
4526 #define	IEEE80211_CHAN_HTG	(IEEE80211_CHAN_HT|IEEE80211_CHAN_G)
4527 #define	IEEE80211_CHAN_HTA	(IEEE80211_CHAN_HT|IEEE80211_CHAN_A)
4528 
4529 static void
4530 addchan(struct ieee80211_channel *c, int freq, int flags, int ieee, int txpow)
4531 {
4532 	c->ic_freq = freq;
4533 	c->ic_flags = flags;
4534 	c->ic_ieee = ieee;
4535 	c->ic_minpower = 0;
4536 	c->ic_maxpower = 2*txpow;
4537 	c->ic_maxregpower = txpow;
4538 }
4539 
4540 static const struct ieee80211_channel *
4541 findchannel(const struct ieee80211_channel chans[], int nchans,
4542 	int freq, int flags)
4543 {
4544 	const struct ieee80211_channel *c;
4545 	int i;
4546 
4547 	for (i = 0; i < nchans; i++) {
4548 		c = &chans[i];
4549 		if (c->ic_freq == freq && c->ic_flags == flags)
4550 			return c;
4551 	}
4552 	return NULL;
4553 }
4554 
4555 static void
4556 addht40channels(struct ieee80211_channel chans[], int maxchans, int *nchans,
4557 	const MWL_HAL_CHANNELINFO *ci, int flags)
4558 {
4559 	struct ieee80211_channel *c;
4560 	const struct ieee80211_channel *extc;
4561 	const struct mwl_hal_channel *hc;
4562 	int i;
4563 
4564 	c = &chans[*nchans];
4565 
4566 	flags &= ~IEEE80211_CHAN_HT;
4567 	for (i = 0; i < ci->nchannels; i++) {
4568 		/*
4569 		 * Each entry defines an HT40 channel pair; find the
4570 		 * extension channel above and the insert the pair.
4571 		 */
4572 		hc = &ci->channels[i];
4573 		extc = findchannel(chans, *nchans, hc->freq+20,
4574 		    flags | IEEE80211_CHAN_HT20);
4575 		if (extc != NULL) {
4576 			if (*nchans >= maxchans)
4577 				break;
4578 			addchan(c, hc->freq, flags | IEEE80211_CHAN_HT40U,
4579 			    hc->ieee, hc->maxTxPow);
4580 			c->ic_extieee = extc->ic_ieee;
4581 			c++, (*nchans)++;
4582 			if (*nchans >= maxchans)
4583 				break;
4584 			addchan(c, extc->ic_freq, flags | IEEE80211_CHAN_HT40D,
4585 			    extc->ic_ieee, hc->maxTxPow);
4586 			c->ic_extieee = hc->ieee;
4587 			c++, (*nchans)++;
4588 		}
4589 	}
4590 }
4591 
4592 static void
4593 addchannels(struct ieee80211_channel chans[], int maxchans, int *nchans,
4594 	const MWL_HAL_CHANNELINFO *ci, int flags)
4595 {
4596 	struct ieee80211_channel *c;
4597 	int i;
4598 
4599 	c = &chans[*nchans];
4600 
4601 	for (i = 0; i < ci->nchannels; i++) {
4602 		const struct mwl_hal_channel *hc;
4603 
4604 		hc = &ci->channels[i];
4605 		if (*nchans >= maxchans)
4606 			break;
4607 		addchan(c, hc->freq, flags, hc->ieee, hc->maxTxPow);
4608 		c++, (*nchans)++;
4609 		if (flags == IEEE80211_CHAN_G || flags == IEEE80211_CHAN_HTG) {
4610 			/* g channel have a separate b-only entry */
4611 			if (*nchans >= maxchans)
4612 				break;
4613 			c[0] = c[-1];
4614 			c[-1].ic_flags = IEEE80211_CHAN_B;
4615 			c++, (*nchans)++;
4616 		}
4617 		if (flags == IEEE80211_CHAN_HTG) {
4618 			/* HT g channel have a separate g-only entry */
4619 			if (*nchans >= maxchans)
4620 				break;
4621 			c[-1].ic_flags = IEEE80211_CHAN_G;
4622 			c[0] = c[-1];
4623 			c[0].ic_flags &= ~IEEE80211_CHAN_HT;
4624 			c[0].ic_flags |= IEEE80211_CHAN_HT20;	/* HT20 */
4625 			c++, (*nchans)++;
4626 		}
4627 		if (flags == IEEE80211_CHAN_HTA) {
4628 			/* HT a channel have a separate a-only entry */
4629 			if (*nchans >= maxchans)
4630 				break;
4631 			c[-1].ic_flags = IEEE80211_CHAN_A;
4632 			c[0] = c[-1];
4633 			c[0].ic_flags &= ~IEEE80211_CHAN_HT;
4634 			c[0].ic_flags |= IEEE80211_CHAN_HT20;	/* HT20 */
4635 			c++, (*nchans)++;
4636 		}
4637 	}
4638 }
4639 
4640 static void
4641 getchannels(struct mwl_softc *sc, int maxchans, int *nchans,
4642 	struct ieee80211_channel chans[])
4643 {
4644 	const MWL_HAL_CHANNELINFO *ci;
4645 
4646 	/*
4647 	 * Use the channel info from the hal to craft the
4648 	 * channel list.  Note that we pass back an unsorted
4649 	 * list; the caller is required to sort it for us
4650 	 * (if desired).
4651 	 */
4652 	*nchans = 0;
4653 	if (mwl_hal_getchannelinfo(sc->sc_mh,
4654 	    MWL_FREQ_BAND_2DOT4GHZ, MWL_CH_20_MHz_WIDTH, &ci) == 0)
4655 		addchannels(chans, maxchans, nchans, ci, IEEE80211_CHAN_HTG);
4656 	if (mwl_hal_getchannelinfo(sc->sc_mh,
4657 	    MWL_FREQ_BAND_5GHZ, MWL_CH_20_MHz_WIDTH, &ci) == 0)
4658 		addchannels(chans, maxchans, nchans, ci, IEEE80211_CHAN_HTA);
4659 	if (mwl_hal_getchannelinfo(sc->sc_mh,
4660 	    MWL_FREQ_BAND_2DOT4GHZ, MWL_CH_40_MHz_WIDTH, &ci) == 0)
4661 		addht40channels(chans, maxchans, nchans, ci, IEEE80211_CHAN_HTG);
4662 	if (mwl_hal_getchannelinfo(sc->sc_mh,
4663 	    MWL_FREQ_BAND_5GHZ, MWL_CH_40_MHz_WIDTH, &ci) == 0)
4664 		addht40channels(chans, maxchans, nchans, ci, IEEE80211_CHAN_HTA);
4665 }
4666 
4667 static void
4668 mwl_getradiocaps(struct ieee80211com *ic,
4669 	int maxchans, int *nchans, struct ieee80211_channel chans[])
4670 {
4671 	struct mwl_softc *sc = ic->ic_ifp->if_softc;
4672 
4673 	getchannels(sc, maxchans, nchans, chans);
4674 }
4675 
4676 static int
4677 mwl_getchannels(struct mwl_softc *sc)
4678 {
4679 	struct ifnet *ifp = sc->sc_ifp;
4680 	struct ieee80211com *ic = ifp->if_l2com;
4681 
4682 	/*
4683 	 * Use the channel info from the hal to craft the
4684 	 * channel list for net80211.  Note that we pass up
4685 	 * an unsorted list; net80211 will sort it for us.
4686 	 */
4687 	memset(ic->ic_channels, 0, sizeof(ic->ic_channels));
4688 	ic->ic_nchans = 0;
4689 	getchannels(sc, IEEE80211_CHAN_MAX, &ic->ic_nchans, ic->ic_channels);
4690 
4691 	ic->ic_regdomain.regdomain = SKU_DEBUG;
4692 	ic->ic_regdomain.country = CTRY_DEFAULT;
4693 	ic->ic_regdomain.location = 'I';
4694 	ic->ic_regdomain.isocc[0] = ' ';	/* XXX? */
4695 	ic->ic_regdomain.isocc[1] = ' ';
4696 	return (ic->ic_nchans == 0 ? EIO : 0);
4697 }
4698 #undef IEEE80211_CHAN_HTA
4699 #undef IEEE80211_CHAN_HTG
4700 
4701 #ifdef MWL_DEBUG
4702 static void
4703 mwl_printrxbuf(const struct mwl_rxbuf *bf, u_int ix)
4704 {
4705 	const struct mwl_rxdesc *ds = bf->bf_desc;
4706 	uint32_t status = le32toh(ds->Status);
4707 
4708 	printf("R[%2u] (DS.V:%p DS.P:%p) NEXT:%08x DATA:%08x RC:%02x%s\n"
4709 	       "      STAT:%02x LEN:%04x RSSI:%02x CHAN:%02x RATE:%02x QOS:%04x HT:%04x\n",
4710 	    ix, ds, (const struct mwl_desc *)bf->bf_daddr,
4711 	    le32toh(ds->pPhysNext), le32toh(ds->pPhysBuffData),
4712 	    ds->RxControl,
4713 	    ds->RxControl != EAGLE_RXD_CTRL_DRIVER_OWN ?
4714 	        "" : (status & EAGLE_RXD_STATUS_OK) ? " *" : " !",
4715 	    ds->Status, le16toh(ds->PktLen), ds->RSSI, ds->Channel,
4716 	    ds->Rate, le16toh(ds->QosCtrl), le16toh(ds->HtSig2));
4717 }
4718 
4719 static void
4720 mwl_printtxbuf(const struct mwl_txbuf *bf, u_int qnum, u_int ix)
4721 {
4722 	const struct mwl_txdesc *ds = bf->bf_desc;
4723 	uint32_t status = le32toh(ds->Status);
4724 
4725 	printf("Q%u[%3u]", qnum, ix);
4726 	printf(" (DS.V:%p DS.P:%p)\n",
4727 	    ds, (const struct mwl_txdesc *)bf->bf_daddr);
4728 	printf("    NEXT:%08x DATA:%08x LEN:%04x STAT:%08x%s\n",
4729 	    le32toh(ds->pPhysNext),
4730 	    le32toh(ds->PktPtr), le16toh(ds->PktLen), status,
4731 	    status & EAGLE_TXD_STATUS_USED ?
4732 		"" : (status & 3) != 0 ? " *" : " !");
4733 	printf("    RATE:%02x PRI:%x QOS:%04x SAP:%08x FORMAT:%04x\n",
4734 	    ds->DataRate, ds->TxPriority, le16toh(ds->QosCtrl),
4735 	    le32toh(ds->SapPktInfo), le16toh(ds->Format));
4736 #if MWL_TXDESC > 1
4737 	printf("    MULTIFRAMES:%u LEN:%04x %04x %04x %04x %04x %04x\n"
4738 	    , le32toh(ds->multiframes)
4739 	    , le16toh(ds->PktLenArray[0]), le16toh(ds->PktLenArray[1])
4740 	    , le16toh(ds->PktLenArray[2]), le16toh(ds->PktLenArray[3])
4741 	    , le16toh(ds->PktLenArray[4]), le16toh(ds->PktLenArray[5])
4742 	);
4743 	printf("    DATA:%08x %08x %08x %08x %08x %08x\n"
4744 	    , le32toh(ds->PktPtrArray[0]), le32toh(ds->PktPtrArray[1])
4745 	    , le32toh(ds->PktPtrArray[2]), le32toh(ds->PktPtrArray[3])
4746 	    , le32toh(ds->PktPtrArray[4]), le32toh(ds->PktPtrArray[5])
4747 	);
4748 #endif
4749 #if 0
4750 { const uint8_t *cp = (const uint8_t *) ds;
4751   int i;
4752   for (i = 0; i < sizeof(struct mwl_txdesc); i++) {
4753 	printf("%02x ", cp[i]);
4754 	if (((i+1) % 16) == 0)
4755 		printf("\n");
4756   }
4757   printf("\n");
4758 }
4759 #endif
4760 }
4761 #endif /* MWL_DEBUG */
4762 
4763 #if 0
4764 static void
4765 mwl_txq_dump(struct mwl_txq *txq)
4766 {
4767 	struct mwl_txbuf *bf;
4768 	int i = 0;
4769 
4770 	MWL_TXQ_LOCK(txq);
4771 	STAILQ_FOREACH(bf, &txq->active, bf_list) {
4772 		struct mwl_txdesc *ds = bf->bf_desc;
4773 		MWL_TXDESC_SYNC(txq, ds,
4774 		    BUS_DMASYNC_POSTREAD | BUS_DMASYNC_POSTWRITE);
4775 #ifdef MWL_DEBUG
4776 		mwl_printtxbuf(bf, txq->qnum, i);
4777 #endif
4778 		i++;
4779 	}
4780 	MWL_TXQ_UNLOCK(txq);
4781 }
4782 #endif
4783 
4784 static void
4785 mwl_watchdog(void *arg)
4786 {
4787 	struct mwl_softc *sc;
4788 	struct ifnet *ifp;
4789 
4790 	sc = arg;
4791 	callout_reset(&sc->sc_watchdog, hz, mwl_watchdog, sc);
4792 	if (sc->sc_tx_timer == 0 || --sc->sc_tx_timer > 0)
4793 		return;
4794 
4795 	ifp = sc->sc_ifp;
4796 	if ((ifp->if_drv_flags & IFF_DRV_RUNNING) && !sc->sc_invalid) {
4797 		if (mwl_hal_setkeepalive(sc->sc_mh))
4798 			if_printf(ifp, "transmit timeout (firmware hung?)\n");
4799 		else
4800 			if_printf(ifp, "transmit timeout\n");
4801 #if 0
4802 		mwl_reset(ifp);
4803 mwl_txq_dump(&sc->sc_txq[0]);/*XXX*/
4804 #endif
4805 		ifp->if_oerrors++;
4806 		sc->sc_stats.mst_watchdog++;
4807 	}
4808 }
4809 
4810 #ifdef MWL_DIAGAPI
4811 /*
4812  * Diagnostic interface to the HAL.  This is used by various
4813  * tools to do things like retrieve register contents for
4814  * debugging.  The mechanism is intentionally opaque so that
4815  * it can change frequently w/o concern for compatiblity.
4816  */
4817 static int
4818 mwl_ioctl_diag(struct mwl_softc *sc, struct mwl_diag *md)
4819 {
4820 	struct mwl_hal *mh = sc->sc_mh;
4821 	u_int id = md->md_id & MWL_DIAG_ID;
4822 	void *indata = NULL;
4823 	void *outdata = NULL;
4824 	u_int32_t insize = md->md_in_size;
4825 	u_int32_t outsize = md->md_out_size;
4826 	int error = 0;
4827 
4828 	if (md->md_id & MWL_DIAG_IN) {
4829 		/*
4830 		 * Copy in data.
4831 		 */
4832 		indata = malloc(insize, M_TEMP, M_NOWAIT);
4833 		if (indata == NULL) {
4834 			error = ENOMEM;
4835 			goto bad;
4836 		}
4837 		error = copyin(md->md_in_data, indata, insize);
4838 		if (error)
4839 			goto bad;
4840 	}
4841 	if (md->md_id & MWL_DIAG_DYN) {
4842 		/*
4843 		 * Allocate a buffer for the results (otherwise the HAL
4844 		 * returns a pointer to a buffer where we can read the
4845 		 * results).  Note that we depend on the HAL leaving this
4846 		 * pointer for us to use below in reclaiming the buffer;
4847 		 * may want to be more defensive.
4848 		 */
4849 		outdata = malloc(outsize, M_TEMP, M_NOWAIT);
4850 		if (outdata == NULL) {
4851 			error = ENOMEM;
4852 			goto bad;
4853 		}
4854 	}
4855 	if (mwl_hal_getdiagstate(mh, id, indata, insize, &outdata, &outsize)) {
4856 		if (outsize < md->md_out_size)
4857 			md->md_out_size = outsize;
4858 		if (outdata != NULL)
4859 			error = copyout(outdata, md->md_out_data,
4860 					md->md_out_size);
4861 	} else {
4862 		error = EINVAL;
4863 	}
4864 bad:
4865 	if ((md->md_id & MWL_DIAG_IN) && indata != NULL)
4866 		free(indata, M_TEMP);
4867 	if ((md->md_id & MWL_DIAG_DYN) && outdata != NULL)
4868 		free(outdata, M_TEMP);
4869 	return error;
4870 }
4871 
4872 static int
4873 mwl_ioctl_reset(struct mwl_softc *sc, struct mwl_diag *md)
4874 {
4875 	struct mwl_hal *mh = sc->sc_mh;
4876 	int error;
4877 
4878 	MWL_LOCK_ASSERT(sc);
4879 
4880 	if (md->md_id == 0 && mwl_hal_fwload(mh, NULL) != 0) {
4881 		device_printf(sc->sc_dev, "unable to load firmware\n");
4882 		return EIO;
4883 	}
4884 	if (mwl_hal_gethwspecs(mh, &sc->sc_hwspecs) != 0) {
4885 		device_printf(sc->sc_dev, "unable to fetch h/w specs\n");
4886 		return EIO;
4887 	}
4888 	error = mwl_setupdma(sc);
4889 	if (error != 0) {
4890 		/* NB: mwl_setupdma prints a msg */
4891 		return error;
4892 	}
4893 	/*
4894 	 * Reset tx/rx data structures; after reload we must
4895 	 * re-start the driver's notion of the next xmit/recv.
4896 	 */
4897 	mwl_draintxq(sc);		/* clear pending frames */
4898 	mwl_resettxq(sc);		/* rebuild tx q lists */
4899 	sc->sc_rxnext = NULL;		/* force rx to start at the list head */
4900 	return 0;
4901 }
4902 #endif /* MWL_DIAGAPI */
4903 
4904 static int
4905 mwl_ioctl(struct ifnet *ifp, u_long cmd, caddr_t data)
4906 {
4907 #define	IS_RUNNING(ifp) \
4908 	((ifp->if_flags & IFF_UP) && (ifp->if_drv_flags & IFF_DRV_RUNNING))
4909 	struct mwl_softc *sc = ifp->if_softc;
4910 	struct ieee80211com *ic = ifp->if_l2com;
4911 	struct ifreq *ifr = (struct ifreq *)data;
4912 	int error = 0, startall;
4913 
4914 	switch (cmd) {
4915 	case SIOCSIFFLAGS:
4916 		MWL_LOCK(sc);
4917 		startall = 0;
4918 		if (IS_RUNNING(ifp)) {
4919 			/*
4920 			 * To avoid rescanning another access point,
4921 			 * do not call mwl_init() here.  Instead,
4922 			 * only reflect promisc mode settings.
4923 			 */
4924 			mwl_mode_init(sc);
4925 		} else if (ifp->if_flags & IFF_UP) {
4926 			/*
4927 			 * Beware of being called during attach/detach
4928 			 * to reset promiscuous mode.  In that case we
4929 			 * will still be marked UP but not RUNNING.
4930 			 * However trying to re-init the interface
4931 			 * is the wrong thing to do as we've already
4932 			 * torn down much of our state.  There's
4933 			 * probably a better way to deal with this.
4934 			 */
4935 			if (!sc->sc_invalid) {
4936 				mwl_init_locked(sc);	/* XXX lose error */
4937 				startall = 1;
4938 			}
4939 		} else
4940 			mwl_stop_locked(ifp, 1);
4941 		MWL_UNLOCK(sc);
4942 		if (startall)
4943 			ieee80211_start_all(ic);
4944 		break;
4945 	case SIOCGMVSTATS:
4946 		mwl_hal_gethwstats(sc->sc_mh, &sc->sc_stats.hw_stats);
4947 		/* NB: embed these numbers to get a consistent view */
4948 		sc->sc_stats.mst_tx_packets = ifp->if_opackets;
4949 		sc->sc_stats.mst_rx_packets = ifp->if_ipackets;
4950 		/*
4951 		 * NB: Drop the softc lock in case of a page fault;
4952 		 * we'll accept any potential inconsisentcy in the
4953 		 * statistics.  The alternative is to copy the data
4954 		 * to a local structure.
4955 		 */
4956 		return copyout(&sc->sc_stats,
4957 				ifr->ifr_data, sizeof (sc->sc_stats));
4958 #ifdef MWL_DIAGAPI
4959 	case SIOCGMVDIAG:
4960 		/* XXX check privs */
4961 		return mwl_ioctl_diag(sc, (struct mwl_diag *) ifr);
4962 	case SIOCGMVRESET:
4963 		/* XXX check privs */
4964 		MWL_LOCK(sc);
4965 		error = mwl_ioctl_reset(sc,(struct mwl_diag *) ifr);
4966 		MWL_UNLOCK(sc);
4967 		break;
4968 #endif /* MWL_DIAGAPI */
4969 	case SIOCGIFMEDIA:
4970 		error = ifmedia_ioctl(ifp, ifr, &ic->ic_media, cmd);
4971 		break;
4972 	case SIOCGIFADDR:
4973 		error = ether_ioctl(ifp, cmd, data);
4974 		break;
4975 	default:
4976 		error = EINVAL;
4977 		break;
4978 	}
4979 	return error;
4980 #undef IS_RUNNING
4981 }
4982 
4983 #ifdef	MWL_DEBUG
4984 static int
4985 mwl_sysctl_debug(SYSCTL_HANDLER_ARGS)
4986 {
4987 	struct mwl_softc *sc = arg1;
4988 	int debug, error;
4989 
4990 	debug = sc->sc_debug | (mwl_hal_getdebug(sc->sc_mh) << 24);
4991 	error = sysctl_handle_int(oidp, &debug, 0, req);
4992 	if (error || !req->newptr)
4993 		return error;
4994 	mwl_hal_setdebug(sc->sc_mh, debug >> 24);
4995 	sc->sc_debug = debug & 0x00ffffff;
4996 	return 0;
4997 }
4998 #endif /* MWL_DEBUG */
4999 
5000 static void
5001 mwl_sysctlattach(struct mwl_softc *sc)
5002 {
5003 #ifdef	MWL_DEBUG
5004 	struct sysctl_ctx_list *ctx = device_get_sysctl_ctx(sc->sc_dev);
5005 	struct sysctl_oid *tree = device_get_sysctl_tree(sc->sc_dev);
5006 
5007 	sc->sc_debug = mwl_debug;
5008 	SYSCTL_ADD_PROC(ctx, SYSCTL_CHILDREN(tree), OID_AUTO,
5009 		"debug", CTLTYPE_INT | CTLFLAG_RW, sc, 0,
5010 		mwl_sysctl_debug, "I", "control debugging printfs");
5011 #endif
5012 }
5013 
5014 /*
5015  * Announce various information on device/driver attach.
5016  */
5017 static void
5018 mwl_announce(struct mwl_softc *sc)
5019 {
5020 	struct ifnet *ifp = sc->sc_ifp;
5021 
5022 	if_printf(ifp, "Rev A%d hardware, v%d.%d.%d.%d firmware (regioncode %d)\n",
5023 		sc->sc_hwspecs.hwVersion,
5024 		(sc->sc_hwspecs.fwReleaseNumber>>24) & 0xff,
5025 		(sc->sc_hwspecs.fwReleaseNumber>>16) & 0xff,
5026 		(sc->sc_hwspecs.fwReleaseNumber>>8) & 0xff,
5027 		(sc->sc_hwspecs.fwReleaseNumber>>0) & 0xff,
5028 		sc->sc_hwspecs.regionCode);
5029 	sc->sc_fwrelease = sc->sc_hwspecs.fwReleaseNumber;
5030 
5031 	if (bootverbose) {
5032 		int i;
5033 		for (i = 0; i <= WME_AC_VO; i++) {
5034 			struct mwl_txq *txq = sc->sc_ac2q[i];
5035 			if_printf(ifp, "Use hw queue %u for %s traffic\n",
5036 				txq->qnum, ieee80211_wme_acnames[i]);
5037 		}
5038 	}
5039 	if (bootverbose || mwl_rxdesc != MWL_RXDESC)
5040 		if_printf(ifp, "using %u rx descriptors\n", mwl_rxdesc);
5041 	if (bootverbose || mwl_rxbuf != MWL_RXBUF)
5042 		if_printf(ifp, "using %u rx buffers\n", mwl_rxbuf);
5043 	if (bootverbose || mwl_txbuf != MWL_TXBUF)
5044 		if_printf(ifp, "using %u tx buffers\n", mwl_txbuf);
5045 	if (bootverbose && mwl_hal_ismbsscapable(sc->sc_mh))
5046 		if_printf(ifp, "multi-bss support\n");
5047 #ifdef MWL_TX_NODROP
5048 	if (bootverbose)
5049 		if_printf(ifp, "no tx drop\n");
5050 #endif
5051 }
5052