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