]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/dev/malo/if_malo.c
Update elftoolchain to upstream rev 3130
[FreeBSD/FreeBSD.git] / sys / dev / malo / if_malo.c
1 /*-
2  * Copyright (c) 2008 Weongyo Jeong <weongyo@freebsd.org>
3  * Copyright (c) 2007 Marvell Semiconductor, Inc.
4  * Copyright (c) 2007 Sam Leffler, Errno Consulting
5  * All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer,
12  *    without modification.
13  * 2. Redistributions in binary form must reproduce at minimum a disclaimer
14  *    similar to the "NO WARRANTY" disclaimer below ("Disclaimer") and any
15  *    redistribution must be conditioned upon including a substantially
16  *    similar Disclaimer requirement for further binary redistribution.
17  *
18  * NO WARRANTY
19  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
20  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
21  * LIMITED TO, THE IMPLIED WARRANTIES OF NONINFRINGEMENT, MERCHANTIBILITY
22  * AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
23  * THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR SPECIAL, EXEMPLARY,
24  * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
25  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
26  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER
27  * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
28  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
29  * THE POSSIBILITY OF SUCH DAMAGES.
30  */
31
32 #include <sys/cdefs.h>
33 #ifdef __FreeBSD__
34 __FBSDID("$FreeBSD$");
35 #endif
36
37 #include "opt_malo.h"
38
39 #include <sys/param.h>
40 #include <sys/endian.h>
41 #include <sys/kernel.h>
42 #include <sys/socket.h>
43 #include <sys/sockio.h>
44 #include <sys/sysctl.h>
45 #include <sys/taskqueue.h>
46
47 #include <machine/bus.h>
48 #include <sys/bus.h>
49
50 #include <net/if.h>
51 #include <net/if_var.h>
52 #include <net/if_dl.h>
53 #include <net/if_media.h>
54 #include <net/if_types.h>
55 #include <net/ethernet.h>
56
57 #include <net80211/ieee80211_var.h>
58 #include <net80211/ieee80211_regdomain.h>
59
60 #include <net/bpf.h>
61
62 #include <dev/malo/if_malo.h>
63
64 SYSCTL_NODE(_hw, OID_AUTO, malo, CTLFLAG_RD, 0,
65     "Marvell 88w8335 driver parameters");
66
67 static  int malo_txcoalesce = 8;        /* # tx pkts to q before poking f/w*/
68 SYSCTL_INT(_hw_malo, OID_AUTO, txcoalesce, CTLFLAG_RWTUN, &malo_txcoalesce,
69             0, "tx buffers to send at once");
70 static  int malo_rxbuf = MALO_RXBUF;            /* # rx buffers to allocate */
71 SYSCTL_INT(_hw_malo, OID_AUTO, rxbuf, CTLFLAG_RWTUN, &malo_rxbuf,
72             0, "rx buffers allocated");
73 static  int malo_rxquota = MALO_RXBUF;          /* # max buffers to process */
74 SYSCTL_INT(_hw_malo, OID_AUTO, rxquota, CTLFLAG_RWTUN, &malo_rxquota,
75             0, "max rx buffers to process per interrupt");
76 static  int malo_txbuf = MALO_TXBUF;            /* # tx buffers to allocate */
77 SYSCTL_INT(_hw_malo, OID_AUTO, txbuf, CTLFLAG_RWTUN, &malo_txbuf,
78             0, "tx buffers allocated");
79
80 #ifdef MALO_DEBUG
81 static  int malo_debug = 0;
82 SYSCTL_INT(_hw_malo, OID_AUTO, debug, CTLFLAG_RWTUN, &malo_debug,
83             0, "control debugging printfs");
84 enum {
85         MALO_DEBUG_XMIT         = 0x00000001,   /* basic xmit operation */
86         MALO_DEBUG_XMIT_DESC    = 0x00000002,   /* xmit descriptors */
87         MALO_DEBUG_RECV         = 0x00000004,   /* basic recv operation */
88         MALO_DEBUG_RECV_DESC    = 0x00000008,   /* recv descriptors */
89         MALO_DEBUG_RESET        = 0x00000010,   /* reset processing */
90         MALO_DEBUG_INTR         = 0x00000040,   /* ISR */
91         MALO_DEBUG_TX_PROC      = 0x00000080,   /* tx ISR proc */
92         MALO_DEBUG_RX_PROC      = 0x00000100,   /* rx ISR proc */
93         MALO_DEBUG_STATE        = 0x00000400,   /* 802.11 state transitions */
94         MALO_DEBUG_NODE         = 0x00000800,   /* node management */
95         MALO_DEBUG_RECV_ALL     = 0x00001000,   /* trace all frames (beacons) */
96         MALO_DEBUG_FW           = 0x00008000,   /* firmware */
97         MALO_DEBUG_ANY          = 0xffffffff
98 };
99 #define IS_BEACON(wh)                                                   \
100         ((wh->i_fc[0] & (IEEE80211_FC0_TYPE_MASK |                      \
101                 IEEE80211_FC0_SUBTYPE_MASK)) ==                         \
102          (IEEE80211_FC0_TYPE_MGT|IEEE80211_FC0_SUBTYPE_BEACON))
103 #define IFF_DUMPPKTS_RECV(sc, wh)                                       \
104         (((sc->malo_debug & MALO_DEBUG_RECV) &&                         \
105           ((sc->malo_debug & MALO_DEBUG_RECV_ALL) || !IS_BEACON(wh))) || \
106          (sc->malo_ifp->if_flags & (IFF_DEBUG|IFF_LINK2)) ==            \
107           (IFF_DEBUG|IFF_LINK2))
108 #define IFF_DUMPPKTS_XMIT(sc)                                           \
109         ((sc->malo_debug & MALO_DEBUG_XMIT) ||                          \
110          (sc->malo_ifp->if_flags & (IFF_DEBUG | IFF_LINK2)) ==          \
111              (IFF_DEBUG | IFF_LINK2))
112 #define DPRINTF(sc, m, fmt, ...) do {                           \
113         if (sc->malo_debug & (m))                               \
114                 printf(fmt, __VA_ARGS__);                       \
115 } while (0)
116 #else
117 #define DPRINTF(sc, m, fmt, ...) do {                           \
118         (void) sc;                                              \
119 } while (0)
120 #endif
121
122 static MALLOC_DEFINE(M_MALODEV, "malodev", "malo driver dma buffers");
123
124 static struct ieee80211vap *malo_vap_create(struct ieee80211com *,
125                     const char [IFNAMSIZ], int, enum ieee80211_opmode, int,
126                     const uint8_t [IEEE80211_ADDR_LEN],
127                     const uint8_t [IEEE80211_ADDR_LEN]);
128 static  void    malo_vap_delete(struct ieee80211vap *);
129 static  int     malo_dma_setup(struct malo_softc *);
130 static  int     malo_setup_hwdma(struct malo_softc *);
131 static  void    malo_txq_init(struct malo_softc *, struct malo_txq *, int);
132 static  void    malo_tx_cleanupq(struct malo_softc *, struct malo_txq *);
133 static  void    malo_start(struct ifnet *);
134 static  void    malo_watchdog(void *);
135 static  int     malo_ioctl(struct ifnet *, u_long, caddr_t);
136 static  void    malo_updateslot(struct ifnet *);
137 static  int     malo_newstate(struct ieee80211vap *, enum ieee80211_state, int);
138 static  void    malo_scan_start(struct ieee80211com *);
139 static  void    malo_scan_end(struct ieee80211com *);
140 static  void    malo_set_channel(struct ieee80211com *);
141 static  int     malo_raw_xmit(struct ieee80211_node *, struct mbuf *,
142                     const struct ieee80211_bpf_params *);
143 static  void    malo_sysctlattach(struct malo_softc *);
144 static  void    malo_announce(struct malo_softc *);
145 static  void    malo_dma_cleanup(struct malo_softc *);
146 static  void    malo_stop_locked(struct ifnet *, int);
147 static  int     malo_chan_set(struct malo_softc *, struct ieee80211_channel *);
148 static  int     malo_mode_init(struct malo_softc *);
149 static  void    malo_tx_proc(void *, int);
150 static  void    malo_rx_proc(void *, int);
151 static  void    malo_init(void *);
152
153 /*
154  * Read/Write shorthands for accesses to BAR 0.  Note that all BAR 1
155  * operations are done in the "hal" except getting H/W MAC address at
156  * malo_attach and there should be no reference to them here.
157  */
158 static uint32_t
159 malo_bar0_read4(struct malo_softc *sc, bus_size_t off)
160 {
161         return bus_space_read_4(sc->malo_io0t, sc->malo_io0h, off);
162 }
163
164 static void
165 malo_bar0_write4(struct malo_softc *sc, bus_size_t off, uint32_t val)
166 {
167         DPRINTF(sc, MALO_DEBUG_FW, "%s: off 0x%jx val 0x%x\n",
168             __func__, (intmax_t)off, val);
169
170         bus_space_write_4(sc->malo_io0t, sc->malo_io0h, off, val);
171 }
172
173 int
174 malo_attach(uint16_t devid, struct malo_softc *sc)
175 {
176         int error;
177         struct ieee80211com *ic;
178         struct ifnet *ifp;
179         struct malo_hal *mh;
180         uint8_t bands;
181
182         ifp = sc->malo_ifp = if_alloc(IFT_IEEE80211);
183         if (ifp == NULL) {
184                 device_printf(sc->malo_dev, "can not if_alloc()\n");
185                 return ENOSPC;
186         }
187         ic = ifp->if_l2com;
188
189         MALO_LOCK_INIT(sc);
190         callout_init_mtx(&sc->malo_watchdog_timer, &sc->malo_mtx, 0);
191
192         /* set these up early for if_printf use */
193         if_initname(ifp, device_get_name(sc->malo_dev),
194             device_get_unit(sc->malo_dev));
195
196         mh = malo_hal_attach(sc->malo_dev, devid,
197             sc->malo_io1h, sc->malo_io1t, sc->malo_dmat);
198         if (mh == NULL) {
199                 if_printf(ifp, "unable to attach HAL\n");
200                 error = EIO;
201                 goto bad;
202         }
203         sc->malo_mh = mh;
204
205         /*
206          * Load firmware so we can get setup.  We arbitrarily pick station
207          * firmware; we'll re-load firmware as needed so setting up
208          * the wrong mode isn't a big deal.
209          */
210         error = malo_hal_fwload(mh, "malo8335-h", "malo8335-m");
211         if (error != 0) {
212                 if_printf(ifp, "unable to setup firmware\n");
213                 goto bad1;
214         }
215         /* XXX gethwspecs() extracts correct informations?  not maybe!  */
216         error = malo_hal_gethwspecs(mh, &sc->malo_hwspecs);
217         if (error != 0) {
218                 if_printf(ifp, "unable to fetch h/w specs\n");
219                 goto bad1;
220         }
221
222         DPRINTF(sc, MALO_DEBUG_FW,
223             "malo_hal_gethwspecs: hwversion 0x%x hostif 0x%x"
224             "maxnum_wcb 0x%x maxnum_mcaddr 0x%x maxnum_tx_wcb 0x%x"
225             "regioncode 0x%x num_antenna 0x%x fw_releasenum 0x%x"
226             "wcbbase0 0x%x rxdesc_read 0x%x rxdesc_write 0x%x"
227             "ul_fw_awakecookie 0x%x w[4] = %x %x %x %x",
228             sc->malo_hwspecs.hwversion,
229             sc->malo_hwspecs.hostinterface, sc->malo_hwspecs.maxnum_wcb,
230             sc->malo_hwspecs.maxnum_mcaddr, sc->malo_hwspecs.maxnum_tx_wcb,
231             sc->malo_hwspecs.regioncode, sc->malo_hwspecs.num_antenna,
232             sc->malo_hwspecs.fw_releasenum, sc->malo_hwspecs.wcbbase0,
233             sc->malo_hwspecs.rxdesc_read, sc->malo_hwspecs.rxdesc_write,
234             sc->malo_hwspecs.ul_fw_awakecookie,
235             sc->malo_hwspecs.wcbbase[0], sc->malo_hwspecs.wcbbase[1],
236             sc->malo_hwspecs.wcbbase[2], sc->malo_hwspecs.wcbbase[3]);
237
238         /* NB: firmware looks that it does not export regdomain info API.  */
239         bands = 0;
240         setbit(&bands, IEEE80211_MODE_11B);
241         setbit(&bands, IEEE80211_MODE_11G);
242         ieee80211_init_channels(ic, NULL, &bands);
243
244         sc->malo_txantenna = 0x2;       /* h/w default */
245         sc->malo_rxantenna = 0xffff;    /* h/w default */
246
247         /*
248          * Allocate tx + rx descriptors and populate the lists.
249          * We immediately push the information to the firmware
250          * as otherwise it gets upset.
251          */
252         error = malo_dma_setup(sc);
253         if (error != 0) {
254                 if_printf(ifp, "failed to setup descriptors: %d\n", error);
255                 goto bad1;
256         }
257         error = malo_setup_hwdma(sc);   /* push to firmware */
258         if (error != 0)                 /* NB: malo_setupdma prints msg */
259                 goto bad2;
260
261         sc->malo_tq = taskqueue_create_fast("malo_taskq", M_NOWAIT,
262                 taskqueue_thread_enqueue, &sc->malo_tq);
263         taskqueue_start_threads(&sc->malo_tq, 1, PI_NET,
264                 "%s taskq", ifp->if_xname);
265
266         TASK_INIT(&sc->malo_rxtask, 0, malo_rx_proc, sc);
267         TASK_INIT(&sc->malo_txtask, 0, malo_tx_proc, sc);
268
269         ifp->if_softc = sc;
270         ifp->if_flags = IFF_SIMPLEX | IFF_BROADCAST | IFF_MULTICAST;
271         ifp->if_start = malo_start;
272         ifp->if_ioctl = malo_ioctl;
273         ifp->if_init = malo_init;
274         IFQ_SET_MAXLEN(&ifp->if_snd, ifqmaxlen);
275         ifp->if_snd.ifq_drv_maxlen = ifqmaxlen;
276         IFQ_SET_READY(&ifp->if_snd);
277
278         ic->ic_ifp = ifp;
279         /* XXX not right but it's not used anywhere important */
280         ic->ic_phytype = IEEE80211_T_OFDM;
281         ic->ic_opmode = IEEE80211_M_STA;
282         ic->ic_caps =
283               IEEE80211_C_STA                   /* station mode supported */
284             | IEEE80211_C_BGSCAN                /* capable of bg scanning */
285             | IEEE80211_C_MONITOR               /* monitor mode */
286             | IEEE80211_C_SHPREAMBLE            /* short preamble supported */
287             | IEEE80211_C_SHSLOT                /* short slot time supported */
288             | IEEE80211_C_TXPMGT                /* capable of txpow mgt */
289             | IEEE80211_C_WPA                   /* capable of WPA1+WPA2 */
290             ;
291
292         /*
293          * Transmit requires space in the packet for a special format transmit
294          * record and optional padding between this record and the payload.
295          * Ask the net80211 layer to arrange this when encapsulating
296          * packets so we can add it efficiently. 
297          */
298         ic->ic_headroom = sizeof(struct malo_txrec) -
299                 sizeof(struct ieee80211_frame);
300
301         /* call MI attach routine. */
302         ieee80211_ifattach(ic, sc->malo_hwspecs.macaddr);
303         /* override default methods */
304         ic->ic_vap_create = malo_vap_create;
305         ic->ic_vap_delete = malo_vap_delete;
306         ic->ic_raw_xmit = malo_raw_xmit;
307         ic->ic_updateslot = malo_updateslot;
308
309         ic->ic_scan_start = malo_scan_start;
310         ic->ic_scan_end = malo_scan_end;
311         ic->ic_set_channel = malo_set_channel;
312
313         sc->malo_invalid = 0;           /* ready to go, enable int handling */
314
315         ieee80211_radiotap_attach(ic,
316             &sc->malo_tx_th.wt_ihdr, sizeof(sc->malo_tx_th),
317                 MALO_TX_RADIOTAP_PRESENT,
318             &sc->malo_rx_th.wr_ihdr, sizeof(sc->malo_rx_th),
319                 MALO_RX_RADIOTAP_PRESENT);
320
321         /*
322          * Setup dynamic sysctl's.
323          */
324         malo_sysctlattach(sc);
325
326         if (bootverbose)
327                 ieee80211_announce(ic);
328         malo_announce(sc);
329
330         return 0;
331 bad2:
332         malo_dma_cleanup(sc);
333 bad1:
334         malo_hal_detach(mh);
335 bad:
336         if_free(ifp);
337         sc->malo_invalid = 1;
338
339         return error;
340 }
341
342 static struct ieee80211vap *
343 malo_vap_create(struct ieee80211com *ic, const char name[IFNAMSIZ], int unit,
344     enum ieee80211_opmode opmode, int flags,
345     const uint8_t bssid[IEEE80211_ADDR_LEN],
346     const uint8_t mac[IEEE80211_ADDR_LEN])
347 {
348         struct ifnet *ifp = ic->ic_ifp;
349         struct malo_vap *mvp;
350         struct ieee80211vap *vap;
351
352         if (!TAILQ_EMPTY(&ic->ic_vaps)) {
353                 if_printf(ifp, "multiple vaps not supported\n");
354                 return NULL;
355         }
356         switch (opmode) {
357         case IEEE80211_M_STA:
358                 if (opmode == IEEE80211_M_STA)
359                         flags |= IEEE80211_CLONE_NOBEACONS;
360                 /* fall thru... */
361         case IEEE80211_M_MONITOR:
362                 break;
363         default:
364                 if_printf(ifp, "%s mode not supported\n",
365                     ieee80211_opmode_name[opmode]);
366                 return NULL;            /* unsupported */
367         }
368         mvp = (struct malo_vap *) malloc(sizeof(struct malo_vap),
369             M_80211_VAP, M_NOWAIT | M_ZERO);
370         if (mvp == NULL) {
371                 if_printf(ifp, "cannot allocate vap state block\n");
372                 return NULL;
373         }
374         vap = &mvp->malo_vap;
375         ieee80211_vap_setup(ic, vap, name, unit, opmode, flags, bssid, mac);
376
377         /* override state transition machine */
378         mvp->malo_newstate = vap->iv_newstate;
379         vap->iv_newstate = malo_newstate;
380
381         /* complete setup */
382         ieee80211_vap_attach(vap,
383             ieee80211_media_change, ieee80211_media_status);
384         ic->ic_opmode = opmode;
385         return vap;
386 }
387
388 static void
389 malo_vap_delete(struct ieee80211vap *vap)
390 {
391         struct malo_vap *mvp = MALO_VAP(vap);
392
393         ieee80211_vap_detach(vap);
394         free(mvp, M_80211_VAP);
395 }
396
397 int
398 malo_intr(void *arg)
399 {
400         struct malo_softc *sc = arg;
401         struct malo_hal *mh = sc->malo_mh;
402         uint32_t status;
403
404         if (sc->malo_invalid) {
405                 /*
406                  * The hardware is not ready/present, don't touch anything.
407                  * Note this can happen early on if the IRQ is shared.
408                  */
409                 DPRINTF(sc, MALO_DEBUG_ANY, "%s: invalid; ignored\n", __func__);
410                 return (FILTER_STRAY);
411         }
412
413         /*
414          * Figure out the reason(s) for the interrupt.
415          */
416         malo_hal_getisr(mh, &status);           /* NB: clears ISR too */
417         if (status == 0)                        /* must be a shared irq */
418                 return (FILTER_STRAY);
419
420         DPRINTF(sc, MALO_DEBUG_INTR, "%s: status 0x%x imask 0x%x\n",
421             __func__, status, sc->malo_imask);
422
423         if (status & MALO_A2HRIC_BIT_RX_RDY)
424                 taskqueue_enqueue_fast(sc->malo_tq, &sc->malo_rxtask);
425         if (status & MALO_A2HRIC_BIT_TX_DONE)
426                 taskqueue_enqueue_fast(sc->malo_tq, &sc->malo_txtask);
427         if (status & MALO_A2HRIC_BIT_OPC_DONE)
428                 malo_hal_cmddone(mh);
429         if (status & MALO_A2HRIC_BIT_MAC_EVENT)
430                 ;
431         if (status & MALO_A2HRIC_BIT_RX_PROBLEM)
432                 ;
433         if (status & MALO_A2HRIC_BIT_ICV_ERROR) {
434                 /* TKIP ICV error */
435                 sc->malo_stats.mst_rx_badtkipicv++;
436         }
437 #ifdef MALO_DEBUG
438         if (((status | sc->malo_imask) ^ sc->malo_imask) != 0)
439                 DPRINTF(sc, MALO_DEBUG_INTR,
440                     "%s: can't handle interrupt status 0x%x\n",
441                     __func__, status);
442 #endif
443         return (FILTER_HANDLED);
444 }
445
446 static void
447 malo_load_cb(void *arg, bus_dma_segment_t *segs, int nsegs, int error)
448 {
449         bus_addr_t *paddr = (bus_addr_t*) arg;
450
451         KASSERT(error == 0, ("error %u on bus_dma callback", error));
452
453         *paddr = segs->ds_addr;
454 }
455
456 static int
457 malo_desc_setup(struct malo_softc *sc, const char *name,
458     struct malo_descdma *dd,
459     int nbuf, size_t bufsize, int ndesc, size_t descsize)
460 {
461         int error;
462         struct ifnet *ifp = sc->malo_ifp;
463         uint8_t *ds;
464
465         DPRINTF(sc, MALO_DEBUG_RESET,
466             "%s: %s DMA: %u bufs (%ju) %u desc/buf (%ju)\n",
467             __func__, name, nbuf, (uintmax_t) bufsize,
468             ndesc, (uintmax_t) descsize);
469         
470         dd->dd_name = name;
471         dd->dd_desc_len = nbuf * ndesc * descsize;
472
473         /*
474          * Setup DMA descriptor area.
475          */
476         error = bus_dma_tag_create(bus_get_dma_tag(sc->malo_dev),/* parent */
477                        PAGE_SIZE, 0,            /* alignment, bounds */
478                        BUS_SPACE_MAXADDR_32BIT, /* lowaddr */
479                        BUS_SPACE_MAXADDR,       /* highaddr */
480                        NULL, NULL,              /* filter, filterarg */
481                        dd->dd_desc_len,         /* maxsize */
482                        1,                       /* nsegments */
483                        dd->dd_desc_len,         /* maxsegsize */
484                        BUS_DMA_ALLOCNOW,        /* flags */
485                        NULL,                    /* lockfunc */
486                        NULL,                    /* lockarg */
487                        &dd->dd_dmat);
488         if (error != 0) {
489                 if_printf(ifp, "cannot allocate %s DMA tag\n", dd->dd_name);
490                 return error;
491         }
492         
493         /* allocate descriptors */
494         error = bus_dmamem_alloc(dd->dd_dmat, (void**) &dd->dd_desc,
495             BUS_DMA_NOWAIT | BUS_DMA_COHERENT, &dd->dd_dmamap);
496         if (error != 0) {
497                 if_printf(ifp, "unable to alloc memory for %u %s descriptors, "
498                     "error %u\n", nbuf * ndesc, dd->dd_name, error);
499                 goto fail1;
500         }
501
502         error = bus_dmamap_load(dd->dd_dmat, dd->dd_dmamap,
503             dd->dd_desc, dd->dd_desc_len,
504             malo_load_cb, &dd->dd_desc_paddr, BUS_DMA_NOWAIT);
505         if (error != 0) {
506                 if_printf(ifp, "unable to map %s descriptors, error %u\n",
507                     dd->dd_name, error);
508                 goto fail2;
509         }
510         
511         ds = dd->dd_desc;
512         memset(ds, 0, dd->dd_desc_len);
513         DPRINTF(sc, MALO_DEBUG_RESET, "%s: %s DMA map: %p (%lu) -> %p (%lu)\n",
514             __func__, dd->dd_name, ds, (u_long) dd->dd_desc_len,
515             (caddr_t) dd->dd_desc_paddr, /*XXX*/ (u_long) dd->dd_desc_len);
516
517         return 0;
518 fail2:
519         bus_dmamem_free(dd->dd_dmat, dd->dd_desc, dd->dd_dmamap);
520 fail1:
521         bus_dma_tag_destroy(dd->dd_dmat);
522         memset(dd, 0, sizeof(*dd));
523         return error;
524 }
525
526 #define DS2PHYS(_dd, _ds) \
527         ((_dd)->dd_desc_paddr + ((caddr_t)(_ds) - (caddr_t)(_dd)->dd_desc))
528
529 static int
530 malo_rxdma_setup(struct malo_softc *sc)
531 {
532         struct ifnet *ifp = sc->malo_ifp;
533         int error, bsize, i;
534         struct malo_rxbuf *bf;
535         struct malo_rxdesc *ds;
536
537         error = malo_desc_setup(sc, "rx", &sc->malo_rxdma,
538             malo_rxbuf, sizeof(struct malo_rxbuf),
539             1, sizeof(struct malo_rxdesc));
540         if (error != 0)
541                 return error;
542
543         /*
544          * Allocate rx buffers and set them up.
545          */
546         bsize = malo_rxbuf * sizeof(struct malo_rxbuf);
547         bf = malloc(bsize, M_MALODEV, M_NOWAIT | M_ZERO);
548         if (bf == NULL) {
549                 if_printf(ifp, "malloc of %u rx buffers failed\n", bsize);
550                 return error;
551         }
552         sc->malo_rxdma.dd_bufptr = bf;
553         
554         STAILQ_INIT(&sc->malo_rxbuf);
555         ds = sc->malo_rxdma.dd_desc;
556         for (i = 0; i < malo_rxbuf; i++, bf++, ds++) {
557                 bf->bf_desc = ds;
558                 bf->bf_daddr = DS2PHYS(&sc->malo_rxdma, ds);
559                 error = bus_dmamap_create(sc->malo_dmat, BUS_DMA_NOWAIT,
560                     &bf->bf_dmamap);
561                 if (error != 0) {
562                         if_printf(ifp, "%s: unable to dmamap for rx buffer, "
563                             "error %d\n", __func__, error);
564                         return error;
565                 }
566                 /* NB: tail is intentional to preserve descriptor order */
567                 STAILQ_INSERT_TAIL(&sc->malo_rxbuf, bf, bf_list);
568         }
569         return 0;
570 }
571
572 static int
573 malo_txdma_setup(struct malo_softc *sc, struct malo_txq *txq)
574 {
575         struct ifnet *ifp = sc->malo_ifp;
576         int error, bsize, i;
577         struct malo_txbuf *bf;
578         struct malo_txdesc *ds;
579
580         error = malo_desc_setup(sc, "tx", &txq->dma,
581             malo_txbuf, sizeof(struct malo_txbuf),
582             MALO_TXDESC, sizeof(struct malo_txdesc));
583         if (error != 0)
584                 return error;
585         
586         /* allocate and setup tx buffers */
587         bsize = malo_txbuf * sizeof(struct malo_txbuf);
588         bf = malloc(bsize, M_MALODEV, M_NOWAIT | M_ZERO);
589         if (bf == NULL) {
590                 if_printf(ifp, "malloc of %u tx buffers failed\n",
591                     malo_txbuf);
592                 return ENOMEM;
593         }
594         txq->dma.dd_bufptr = bf;
595         
596         STAILQ_INIT(&txq->free);
597         txq->nfree = 0;
598         ds = txq->dma.dd_desc;
599         for (i = 0; i < malo_txbuf; i++, bf++, ds += MALO_TXDESC) {
600                 bf->bf_desc = ds;
601                 bf->bf_daddr = DS2PHYS(&txq->dma, ds);
602                 error = bus_dmamap_create(sc->malo_dmat, BUS_DMA_NOWAIT,
603                     &bf->bf_dmamap);
604                 if (error != 0) {
605                         if_printf(ifp, "unable to create dmamap for tx "
606                             "buffer %u, error %u\n", i, error);
607                         return error;
608                 }
609                 STAILQ_INSERT_TAIL(&txq->free, bf, bf_list);
610                 txq->nfree++;
611         }
612
613         return 0;
614 }
615
616 static void
617 malo_desc_cleanup(struct malo_softc *sc, struct malo_descdma *dd)
618 {
619         bus_dmamap_unload(dd->dd_dmat, dd->dd_dmamap);
620         bus_dmamem_free(dd->dd_dmat, dd->dd_desc, dd->dd_dmamap);
621         bus_dma_tag_destroy(dd->dd_dmat);
622
623         memset(dd, 0, sizeof(*dd));
624 }
625
626 static void
627 malo_rxdma_cleanup(struct malo_softc *sc)
628 {
629         struct malo_rxbuf *bf;
630
631         STAILQ_FOREACH(bf, &sc->malo_rxbuf, bf_list) {
632                 if (bf->bf_m != NULL) {
633                         m_freem(bf->bf_m);
634                         bf->bf_m = NULL;
635                 }
636                 if (bf->bf_dmamap != NULL) {
637                         bus_dmamap_destroy(sc->malo_dmat, bf->bf_dmamap);
638                         bf->bf_dmamap = NULL;
639                 }
640         }
641         STAILQ_INIT(&sc->malo_rxbuf);
642         if (sc->malo_rxdma.dd_bufptr != NULL) {
643                 free(sc->malo_rxdma.dd_bufptr, M_MALODEV);
644                 sc->malo_rxdma.dd_bufptr = NULL;
645         }
646         if (sc->malo_rxdma.dd_desc_len != 0)
647                 malo_desc_cleanup(sc, &sc->malo_rxdma);
648 }
649
650 static void
651 malo_txdma_cleanup(struct malo_softc *sc, struct malo_txq *txq)
652 {
653         struct malo_txbuf *bf;
654         struct ieee80211_node *ni;
655
656         STAILQ_FOREACH(bf, &txq->free, bf_list) {
657                 if (bf->bf_m != NULL) {
658                         m_freem(bf->bf_m);
659                         bf->bf_m = NULL;
660                 }
661                 ni = bf->bf_node;
662                 bf->bf_node = NULL;
663                 if (ni != NULL) {
664                         /*
665                          * Reclaim node reference.
666                          */
667                         ieee80211_free_node(ni);
668                 }
669                 if (bf->bf_dmamap != NULL) {
670                         bus_dmamap_destroy(sc->malo_dmat, bf->bf_dmamap);
671                         bf->bf_dmamap = NULL;
672                 }
673         }
674         STAILQ_INIT(&txq->free);
675         txq->nfree = 0;
676         if (txq->dma.dd_bufptr != NULL) {
677                 free(txq->dma.dd_bufptr, M_MALODEV);
678                 txq->dma.dd_bufptr = NULL;
679         }
680         if (txq->dma.dd_desc_len != 0)
681                 malo_desc_cleanup(sc, &txq->dma);
682 }
683
684 static void
685 malo_dma_cleanup(struct malo_softc *sc)
686 {
687         int i;
688
689         for (i = 0; i < MALO_NUM_TX_QUEUES; i++)
690                 malo_txdma_cleanup(sc, &sc->malo_txq[i]);
691
692         malo_rxdma_cleanup(sc);
693 }
694
695 static int
696 malo_dma_setup(struct malo_softc *sc)
697 {
698         int error, i;
699
700         /* rxdma initializing.  */
701         error = malo_rxdma_setup(sc);
702         if (error != 0)
703                 return error;
704
705         /* NB: we just have 1 tx queue now.  */
706         for (i = 0; i < MALO_NUM_TX_QUEUES; i++) {
707                 error = malo_txdma_setup(sc, &sc->malo_txq[i]);
708                 if (error != 0) {
709                         malo_dma_cleanup(sc);
710
711                         return error;
712                 }
713
714                 malo_txq_init(sc, &sc->malo_txq[i], i);
715         }
716
717         return 0;
718 }
719
720 static void
721 malo_hal_set_rxtxdma(struct malo_softc *sc)
722 {
723         int i;
724
725         malo_bar0_write4(sc, sc->malo_hwspecs.rxdesc_read,
726             sc->malo_hwdma.rxdesc_read);
727         malo_bar0_write4(sc, sc->malo_hwspecs.rxdesc_write,
728             sc->malo_hwdma.rxdesc_read);
729
730         for (i = 0; i < MALO_NUM_TX_QUEUES; i++) {
731                 malo_bar0_write4(sc,
732                     sc->malo_hwspecs.wcbbase[i], sc->malo_hwdma.wcbbase[i]);
733         }
734 }
735
736 /*
737  * Inform firmware of our tx/rx dma setup.  The BAR 0 writes below are
738  * for compatibility with older firmware.  For current firmware we send
739  * this information with a cmd block via malo_hal_sethwdma.
740  */
741 static int
742 malo_setup_hwdma(struct malo_softc *sc)
743 {
744         int i;
745         struct malo_txq *txq;
746
747         sc->malo_hwdma.rxdesc_read = sc->malo_rxdma.dd_desc_paddr;
748
749         for (i = 0; i < MALO_NUM_TX_QUEUES; i++) {
750                 txq = &sc->malo_txq[i];
751                 sc->malo_hwdma.wcbbase[i] = txq->dma.dd_desc_paddr;
752         }
753         sc->malo_hwdma.maxnum_txwcb = malo_txbuf;
754         sc->malo_hwdma.maxnum_wcb = MALO_NUM_TX_QUEUES;
755
756         malo_hal_set_rxtxdma(sc);
757
758         return 0;
759 }
760
761 static void
762 malo_txq_init(struct malo_softc *sc, struct malo_txq *txq, int qnum)
763 {
764         struct malo_txbuf *bf, *bn;
765         struct malo_txdesc *ds;
766
767         MALO_TXQ_LOCK_INIT(sc, txq);
768         txq->qnum = qnum;
769         txq->txpri = 0; /* XXX */
770
771         STAILQ_FOREACH(bf, &txq->free, bf_list) {
772                 bf->bf_txq = txq;
773
774                 ds = bf->bf_desc;
775                 bn = STAILQ_NEXT(bf, bf_list);
776                 if (bn == NULL)
777                         bn = STAILQ_FIRST(&txq->free);
778                 ds->physnext = htole32(bn->bf_daddr);
779         }
780         STAILQ_INIT(&txq->active);
781 }
782
783 /*
784  * Reclaim resources for a setup queue.
785  */
786 static void
787 malo_tx_cleanupq(struct malo_softc *sc, struct malo_txq *txq)
788 {
789         /* XXX hal work? */
790         MALO_TXQ_LOCK_DESTROY(txq);
791 }
792
793 /*
794  * Allocate a tx buffer for sending a frame.
795  */
796 static struct malo_txbuf *
797 malo_getbuf(struct malo_softc *sc, struct malo_txq *txq)
798 {
799         struct malo_txbuf *bf;
800
801         MALO_TXQ_LOCK(txq);
802         bf = STAILQ_FIRST(&txq->free);
803         if (bf != NULL) {
804                 STAILQ_REMOVE_HEAD(&txq->free, bf_list);
805                 txq->nfree--;
806         }
807         MALO_TXQ_UNLOCK(txq);
808         if (bf == NULL) {
809                 DPRINTF(sc, MALO_DEBUG_XMIT,
810                     "%s: out of xmit buffers on q %d\n", __func__, txq->qnum);
811                 sc->malo_stats.mst_tx_qstop++;
812         }
813         return bf;
814 }
815
816 static int
817 malo_tx_dmasetup(struct malo_softc *sc, struct malo_txbuf *bf, struct mbuf *m0)
818 {
819         struct mbuf *m;
820         int error;
821
822         /*
823          * Load the DMA map so any coalescing is done.  This also calculates
824          * the number of descriptors we need.
825          */
826         error = bus_dmamap_load_mbuf_sg(sc->malo_dmat, bf->bf_dmamap, m0,
827                                      bf->bf_segs, &bf->bf_nseg,
828                                      BUS_DMA_NOWAIT);
829         if (error == EFBIG) {
830                 /* XXX packet requires too many descriptors */
831                 bf->bf_nseg = MALO_TXDESC + 1;
832         } else if (error != 0) {
833                 sc->malo_stats.mst_tx_busdma++;
834                 m_freem(m0);
835                 return error;
836         }
837         /*
838          * Discard null packets and check for packets that require too many
839          * TX descriptors.  We try to convert the latter to a cluster.
840          */
841         if (error == EFBIG) {           /* too many desc's, linearize */
842                 sc->malo_stats.mst_tx_linear++;
843                 m = m_defrag(m0, M_NOWAIT);
844                 if (m == NULL) {
845                         m_freem(m0);
846                         sc->malo_stats.mst_tx_nombuf++;
847                         return ENOMEM;
848                 }
849                 m0 = m;
850                 error = bus_dmamap_load_mbuf_sg(sc->malo_dmat, bf->bf_dmamap, m0,
851                                              bf->bf_segs, &bf->bf_nseg,
852                                              BUS_DMA_NOWAIT);
853                 if (error != 0) {
854                         sc->malo_stats.mst_tx_busdma++;
855                         m_freem(m0);
856                         return error;
857                 }
858                 KASSERT(bf->bf_nseg <= MALO_TXDESC,
859                     ("too many segments after defrag; nseg %u", bf->bf_nseg));
860         } else if (bf->bf_nseg == 0) {          /* null packet, discard */
861                 sc->malo_stats.mst_tx_nodata++;
862                 m_freem(m0);
863                 return EIO;
864         }
865         DPRINTF(sc, MALO_DEBUG_XMIT, "%s: m %p len %u\n",
866                 __func__, m0, m0->m_pkthdr.len);
867         bus_dmamap_sync(sc->malo_dmat, bf->bf_dmamap, BUS_DMASYNC_PREWRITE);
868         bf->bf_m = m0;
869
870         return 0;
871 }
872
873 #ifdef MALO_DEBUG
874 static void
875 malo_printrxbuf(const struct malo_rxbuf *bf, u_int ix)
876 {
877         const struct malo_rxdesc *ds = bf->bf_desc;
878         uint32_t status = le32toh(ds->status);
879         
880         printf("R[%2u] (DS.V:%p DS.P:%p) NEXT:%08x DATA:%08x RC:%02x%s\n"
881             "      STAT:%02x LEN:%04x SNR:%02x NF:%02x CHAN:%02x"
882             " RATE:%02x QOS:%04x\n",
883             ix, ds, (const struct malo_desc *)bf->bf_daddr,
884             le32toh(ds->physnext), le32toh(ds->physbuffdata),
885             ds->rxcontrol, 
886             ds->rxcontrol != MALO_RXD_CTRL_DRIVER_OWN ?
887                 "" : (status & MALO_RXD_STATUS_OK) ? " *" : " !",
888             ds->status, le16toh(ds->pktlen), ds->snr, ds->nf, ds->channel,
889             ds->rate, le16toh(ds->qosctrl));
890 }
891
892 static void
893 malo_printtxbuf(const struct malo_txbuf *bf, u_int qnum, u_int ix)
894 {
895         const struct malo_txdesc *ds = bf->bf_desc;
896         uint32_t status = le32toh(ds->status);
897         
898         printf("Q%u[%3u]", qnum, ix);
899         printf(" (DS.V:%p DS.P:%p)\n",
900             ds, (const struct malo_txdesc *)bf->bf_daddr);
901         printf("    NEXT:%08x DATA:%08x LEN:%04x STAT:%08x%s\n",
902             le32toh(ds->physnext),
903             le32toh(ds->pktptr), le16toh(ds->pktlen), status,
904             status & MALO_TXD_STATUS_USED ?
905             "" : (status & 3) != 0 ? " *" : " !");
906         printf("    RATE:%02x PRI:%x QOS:%04x SAP:%08x FORMAT:%04x\n",
907             ds->datarate, ds->txpriority, le16toh(ds->qosctrl),
908             le32toh(ds->sap_pktinfo), le16toh(ds->format));
909 #if 0
910         {
911                 const uint8_t *cp = (const uint8_t *) ds;
912                 int i;
913                 for (i = 0; i < sizeof(struct malo_txdesc); i++) {
914                         printf("%02x ", cp[i]);
915                         if (((i+1) % 16) == 0)
916                                 printf("\n");
917                 }
918                 printf("\n");
919         }
920 #endif
921 }
922 #endif /* MALO_DEBUG */
923
924 static __inline void
925 malo_updatetxrate(struct ieee80211_node *ni, int rix)
926 {
927 #define N(x)    (sizeof(x)/sizeof(x[0]))
928         static const int ieeerates[] =
929             { 2, 4, 11, 22, 44, 12, 18, 24, 36, 48, 96, 108 };
930         if (rix < N(ieeerates))
931                 ni->ni_txrate = ieeerates[rix];
932 #undef N
933 }
934
935 static int
936 malo_fix2rate(int fix_rate)
937 {
938 #define N(x)    (sizeof(x)/sizeof(x[0]))
939         static const int rates[] =
940             { 2, 4, 11, 22, 12, 18, 24, 36, 48, 96, 108 };
941         return (fix_rate < N(rates) ? rates[fix_rate] : 0);
942 #undef N
943 }
944
945 /* idiomatic shorthands: MS = mask+shift, SM = shift+mask */
946 #define MS(v,x)                 (((v) & x) >> x##_S)
947 #define SM(v,x)                 (((v) << x##_S) & x)
948
949 /*
950  * Process completed xmit descriptors from the specified queue.
951  */
952 static int
953 malo_tx_processq(struct malo_softc *sc, struct malo_txq *txq)
954 {
955         struct malo_txbuf *bf;
956         struct malo_txdesc *ds;
957         struct ieee80211_node *ni;
958         int nreaped;
959         uint32_t status;
960
961         DPRINTF(sc, MALO_DEBUG_TX_PROC, "%s: tx queue %u\n",
962             __func__, txq->qnum);
963         for (nreaped = 0;; nreaped++) {
964                 MALO_TXQ_LOCK(txq);
965                 bf = STAILQ_FIRST(&txq->active);
966                 if (bf == NULL) {
967                         MALO_TXQ_UNLOCK(txq);
968                         break;
969                 }
970                 ds = bf->bf_desc;
971                 MALO_TXDESC_SYNC(txq, ds,
972                     BUS_DMASYNC_POSTREAD | BUS_DMASYNC_POSTWRITE);
973                 if (ds->status & htole32(MALO_TXD_STATUS_FW_OWNED)) {
974                         MALO_TXQ_UNLOCK(txq);
975                         break;
976                 }
977                 STAILQ_REMOVE_HEAD(&txq->active, bf_list);
978                 MALO_TXQ_UNLOCK(txq);
979
980 #ifdef MALO_DEBUG
981                 if (sc->malo_debug & MALO_DEBUG_XMIT_DESC)
982                         malo_printtxbuf(bf, txq->qnum, nreaped);
983 #endif
984                 ni = bf->bf_node;
985                 if (ni != NULL) {
986                         status = le32toh(ds->status);
987                         if (status & MALO_TXD_STATUS_OK) {
988                                 uint16_t format = le16toh(ds->format);
989                                 uint8_t txant = MS(format, MALO_TXD_ANTENNA);
990
991                                 sc->malo_stats.mst_ant_tx[txant]++;
992                                 if (status & MALO_TXD_STATUS_OK_RETRY)
993                                         sc->malo_stats.mst_tx_retries++;
994                                 if (status & MALO_TXD_STATUS_OK_MORE_RETRY)
995                                         sc->malo_stats.mst_tx_mretries++;
996                                 malo_updatetxrate(ni, ds->datarate);
997                                 sc->malo_stats.mst_tx_rate = ds->datarate;
998                         } else {
999                                 if (status & MALO_TXD_STATUS_FAILED_LINK_ERROR)
1000                                         sc->malo_stats.mst_tx_linkerror++;
1001                                 if (status & MALO_TXD_STATUS_FAILED_XRETRY)
1002                                         sc->malo_stats.mst_tx_xretries++;
1003                                 if (status & MALO_TXD_STATUS_FAILED_AGING)
1004                                         sc->malo_stats.mst_tx_aging++;
1005                         }
1006                         /*
1007                          * Do any tx complete callback.  Note this must
1008                          * be done before releasing the node reference.
1009                          * XXX no way to figure out if frame was ACK'd
1010                          */
1011                         if (bf->bf_m->m_flags & M_TXCB) {
1012                                 /* XXX strip fw len in case header inspected */
1013                                 m_adj(bf->bf_m, sizeof(uint16_t));
1014                                 ieee80211_process_callback(ni, bf->bf_m,
1015                                         (status & MALO_TXD_STATUS_OK) == 0);
1016                         }
1017                         /*
1018                          * Reclaim reference to node.
1019                          *
1020                          * NB: the node may be reclaimed here if, for example
1021                          *     this is a DEAUTH message that was sent and the
1022                          *     node was timed out due to inactivity.
1023                          */
1024                         ieee80211_free_node(ni);
1025                 }
1026                 ds->status = htole32(MALO_TXD_STATUS_IDLE);
1027                 ds->pktlen = htole32(0);
1028
1029                 bus_dmamap_sync(sc->malo_dmat, bf->bf_dmamap,
1030                     BUS_DMASYNC_POSTWRITE);
1031                 bus_dmamap_unload(sc->malo_dmat, bf->bf_dmamap);
1032                 m_freem(bf->bf_m);
1033                 bf->bf_m = NULL;
1034                 bf->bf_node = NULL;
1035
1036                 MALO_TXQ_LOCK(txq);
1037                 STAILQ_INSERT_TAIL(&txq->free, bf, bf_list);
1038                 txq->nfree++;
1039                 MALO_TXQ_UNLOCK(txq);
1040         }
1041         return nreaped;
1042 }
1043
1044 /*
1045  * Deferred processing of transmit interrupt.
1046  */
1047 static void
1048 malo_tx_proc(void *arg, int npending)
1049 {
1050         struct malo_softc *sc = arg;
1051         struct ifnet *ifp = sc->malo_ifp;
1052         int i, nreaped;
1053
1054         /*
1055          * Process each active queue.
1056          */
1057         nreaped = 0;
1058         for (i = 0; i < MALO_NUM_TX_QUEUES; i++) {
1059                 if (!STAILQ_EMPTY(&sc->malo_txq[i].active))
1060                         nreaped += malo_tx_processq(sc, &sc->malo_txq[i]);
1061         }
1062
1063         if (nreaped != 0) {
1064                 ifp->if_drv_flags &= ~IFF_DRV_OACTIVE;
1065                 sc->malo_timer = 0;
1066                 malo_start(ifp);
1067         }
1068 }
1069
1070 static int
1071 malo_tx_start(struct malo_softc *sc, struct ieee80211_node *ni,
1072     struct malo_txbuf *bf, struct mbuf *m0)
1073 {
1074 #define IEEE80211_DIR_DSTODS(wh) \
1075         ((wh->i_fc[1] & IEEE80211_FC1_DIR_MASK) == IEEE80211_FC1_DIR_DSTODS)
1076 #define IS_DATA_FRAME(wh)                                               \
1077         ((wh->i_fc[0] & (IEEE80211_FC0_TYPE_MASK)) == IEEE80211_FC0_TYPE_DATA)
1078         int error, ismcast, iswep;
1079         int copyhdrlen, hdrlen, pktlen;
1080         struct ieee80211_frame *wh;
1081         struct ifnet *ifp = sc->malo_ifp;
1082         struct ieee80211com *ic = ifp->if_l2com;
1083         struct ieee80211vap *vap = ni->ni_vap;
1084         struct malo_txdesc *ds;
1085         struct malo_txrec *tr;
1086         struct malo_txq *txq;
1087         uint16_t qos;
1088
1089         wh = mtod(m0, struct ieee80211_frame *);
1090         iswep = wh->i_fc[1] & IEEE80211_FC1_PROTECTED;
1091         ismcast = IEEE80211_IS_MULTICAST(wh->i_addr1);
1092         copyhdrlen = hdrlen = ieee80211_anyhdrsize(wh);
1093         pktlen = m0->m_pkthdr.len;
1094         if (IEEE80211_QOS_HAS_SEQ(wh)) {
1095                 if (IEEE80211_DIR_DSTODS(wh)) {
1096                         qos = *(uint16_t *)
1097                             (((struct ieee80211_qosframe_addr4 *) wh)->i_qos);
1098                         copyhdrlen -= sizeof(qos);
1099                 } else
1100                         qos = *(uint16_t *)
1101                             (((struct ieee80211_qosframe *) wh)->i_qos);
1102         } else
1103                 qos = 0;
1104
1105         if (iswep) {
1106                 struct ieee80211_key *k;
1107
1108                 /*
1109                  * Construct the 802.11 header+trailer for an encrypted
1110                  * frame. The only reason this can fail is because of an
1111                  * unknown or unsupported cipher/key type.
1112                  *
1113                  * NB: we do this even though the firmware will ignore
1114                  *     what we've done for WEP and TKIP as we need the
1115                  *     ExtIV filled in for CCMP and this also adjusts
1116                  *     the headers which simplifies our work below.
1117                  */
1118                 k = ieee80211_crypto_encap(ni, m0);
1119                 if (k == NULL) {
1120                         /*
1121                          * This can happen when the key is yanked after the
1122                          * frame was queued.  Just discard the frame; the
1123                          * 802.11 layer counts failures and provides
1124                          * debugging/diagnostics.
1125                          */
1126                         m_freem(m0);
1127                         return EIO;
1128                 }
1129
1130                 /*
1131                  * Adjust the packet length for the crypto additions
1132                  * done during encap and any other bits that the f/w
1133                  * will add later on.
1134                  */
1135                 pktlen = m0->m_pkthdr.len;
1136
1137                 /* packet header may have moved, reset our local pointer */
1138                 wh = mtod(m0, struct ieee80211_frame *);
1139         }
1140
1141         if (ieee80211_radiotap_active_vap(vap)) {
1142                 sc->malo_tx_th.wt_flags = 0;    /* XXX */
1143                 if (iswep)
1144                         sc->malo_tx_th.wt_flags |= IEEE80211_RADIOTAP_F_WEP;
1145                 sc->malo_tx_th.wt_txpower = ni->ni_txpower;
1146                 sc->malo_tx_th.wt_antenna = sc->malo_txantenna;
1147
1148                 ieee80211_radiotap_tx(vap, m0);
1149         }
1150
1151         /*
1152          * Copy up/down the 802.11 header; the firmware requires
1153          * we present a 2-byte payload length followed by a
1154          * 4-address header (w/o QoS), followed (optionally) by
1155          * any WEP/ExtIV header (but only filled in for CCMP).
1156          * We are assured the mbuf has sufficient headroom to
1157          * prepend in-place by the setup of ic_headroom in
1158          * malo_attach.
1159          */
1160         if (hdrlen < sizeof(struct malo_txrec)) {
1161                 const int space = sizeof(struct malo_txrec) - hdrlen;
1162                 if (M_LEADINGSPACE(m0) < space) {
1163                         /* NB: should never happen */
1164                         device_printf(sc->malo_dev,
1165                             "not enough headroom, need %d found %zd, "
1166                             "m_flags 0x%x m_len %d\n",
1167                             space, M_LEADINGSPACE(m0), m0->m_flags, m0->m_len);
1168                         ieee80211_dump_pkt(ic,
1169                             mtod(m0, const uint8_t *), m0->m_len, 0, -1);
1170                         m_freem(m0);
1171                         /* XXX stat */
1172                         return EIO;
1173                 }
1174                 M_PREPEND(m0, space, M_NOWAIT);
1175         }
1176         tr = mtod(m0, struct malo_txrec *);
1177         if (wh != (struct ieee80211_frame *) &tr->wh)
1178                 ovbcopy(wh, &tr->wh, hdrlen);
1179         /*
1180          * Note: the "firmware length" is actually the length of the fully
1181          * formed "802.11 payload".  That is, it's everything except for
1182          * the 802.11 header.  In particular this includes all crypto
1183          * material including the MIC!
1184          */
1185         tr->fwlen = htole16(pktlen - hdrlen);
1186
1187         /*
1188          * Load the DMA map so any coalescing is done.  This
1189          * also calculates the number of descriptors we need.
1190          */
1191         error = malo_tx_dmasetup(sc, bf, m0);
1192         if (error != 0)
1193                 return error;
1194         bf->bf_node = ni;                       /* NB: held reference */
1195         m0 = bf->bf_m;                          /* NB: may have changed */
1196         tr = mtod(m0, struct malo_txrec *);
1197         wh = (struct ieee80211_frame *)&tr->wh;
1198
1199         /*
1200          * Formulate tx descriptor.
1201          */
1202         ds = bf->bf_desc;
1203         txq = bf->bf_txq;
1204
1205         ds->qosctrl = qos;                      /* NB: already little-endian */
1206         ds->pktptr = htole32(bf->bf_segs[0].ds_addr);
1207         ds->pktlen = htole16(bf->bf_segs[0].ds_len);
1208         /* NB: pPhysNext setup once, don't touch */
1209         ds->datarate = IS_DATA_FRAME(wh) ? 1 : 0;
1210         ds->sap_pktinfo = 0;
1211         ds->format = 0;
1212
1213         /*
1214          * Select transmit rate.
1215          */
1216         switch (wh->i_fc[0] & IEEE80211_FC0_TYPE_MASK) {
1217         case IEEE80211_FC0_TYPE_MGT:
1218                 sc->malo_stats.mst_tx_mgmt++;
1219                 /* fall thru... */
1220         case IEEE80211_FC0_TYPE_CTL:
1221                 ds->txpriority = 1;
1222                 break;
1223         case IEEE80211_FC0_TYPE_DATA:
1224                 ds->txpriority = txq->qnum;
1225                 break;
1226         default:
1227                 if_printf(ifp, "bogus frame type 0x%x (%s)\n",
1228                         wh->i_fc[0] & IEEE80211_FC0_TYPE_MASK, __func__);
1229                 /* XXX statistic */
1230                 m_freem(m0);
1231                 return EIO;
1232         }
1233
1234 #ifdef MALO_DEBUG
1235         if (IFF_DUMPPKTS_XMIT(sc))
1236                 ieee80211_dump_pkt(ic,
1237                     mtod(m0, const uint8_t *)+sizeof(uint16_t),
1238                     m0->m_len - sizeof(uint16_t), ds->datarate, -1);
1239 #endif
1240
1241         MALO_TXQ_LOCK(txq);
1242         if (!IS_DATA_FRAME(wh))
1243                 ds->status |= htole32(1);
1244         ds->status |= htole32(MALO_TXD_STATUS_FW_OWNED);
1245         STAILQ_INSERT_TAIL(&txq->active, bf, bf_list);
1246         MALO_TXDESC_SYNC(txq, ds, BUS_DMASYNC_PREREAD | BUS_DMASYNC_PREWRITE);
1247
1248         if_inc_counter(ifp, IFCOUNTER_OPACKETS, 1);
1249         sc->malo_timer = 5;
1250         MALO_TXQ_UNLOCK(txq);
1251         return 0;
1252 #undef IEEE80211_DIR_DSTODS
1253 }
1254
1255 static void
1256 malo_start(struct ifnet *ifp)
1257 {
1258         struct malo_softc *sc = ifp->if_softc;
1259         struct ieee80211_node *ni;
1260         struct malo_txq *txq = &sc->malo_txq[0];
1261         struct malo_txbuf *bf = NULL;
1262         struct mbuf *m;
1263         int nqueued = 0;
1264
1265         if ((ifp->if_drv_flags & IFF_DRV_RUNNING) == 0 || sc->malo_invalid)
1266                 return;
1267
1268         for (;;) {
1269                 IFQ_DRV_DEQUEUE(&ifp->if_snd, m);
1270                 if (m == NULL)
1271                         break;
1272                 ni = (struct ieee80211_node *) m->m_pkthdr.rcvif;
1273                 bf = malo_getbuf(sc, txq);
1274                 if (bf == NULL) {
1275                         IFQ_DRV_PREPEND(&ifp->if_snd, m);
1276
1277                         /* XXX blocks other traffic */
1278                         ifp->if_drv_flags |= IFF_DRV_OACTIVE;
1279                         sc->malo_stats.mst_tx_qstop++;
1280                         break;
1281                 }
1282                 /*
1283                  * Pass the frame to the h/w for transmission.
1284                  */
1285                 if (malo_tx_start(sc, ni, bf, m)) {
1286                         if_inc_counter(ifp, IFCOUNTER_OERRORS, 1);
1287                         if (bf != NULL) {
1288                                 bf->bf_m = NULL;
1289                                 bf->bf_node = NULL;
1290                                 MALO_TXQ_LOCK(txq);
1291                                 STAILQ_INSERT_HEAD(&txq->free, bf, bf_list);
1292                                 MALO_TXQ_UNLOCK(txq);
1293                         }
1294                         ieee80211_free_node(ni);
1295                         continue;
1296                 }
1297                 nqueued++;
1298
1299                 if (nqueued >= malo_txcoalesce) {
1300                         /*
1301                          * Poke the firmware to process queued frames;
1302                          * see below about (lack of) locking.
1303                          */
1304                         nqueued = 0;
1305                         malo_hal_txstart(sc->malo_mh, 0/*XXX*/);
1306                 }
1307         }
1308
1309         if (nqueued) {
1310                 /*
1311                  * NB: We don't need to lock against tx done because
1312                  * this just prods the firmware to check the transmit
1313                  * descriptors.  The firmware will also start fetching
1314                  * descriptors by itself if it notices new ones are
1315                  * present when it goes to deliver a tx done interrupt
1316                  * to the host. So if we race with tx done processing
1317                  * it's ok.  Delivering the kick here rather than in
1318                  * malo_tx_start is an optimization to avoid poking the
1319                  * firmware for each packet.
1320                  *
1321                  * NB: the queue id isn't used so 0 is ok.
1322                  */
1323                 malo_hal_txstart(sc->malo_mh, 0/*XXX*/);
1324         }
1325 }
1326
1327 static void
1328 malo_watchdog(void *arg)
1329 {
1330         struct malo_softc *sc;
1331         struct ifnet *ifp;
1332
1333         sc = arg;
1334         callout_reset(&sc->malo_watchdog_timer, hz, malo_watchdog, sc);
1335         if (sc->malo_timer == 0 || --sc->malo_timer > 0)
1336                 return;
1337
1338         ifp = sc->malo_ifp;
1339         if ((ifp->if_drv_flags & IFF_DRV_RUNNING) && !sc->malo_invalid) {
1340                 if_printf(ifp, "watchdog timeout\n");
1341
1342                 /* XXX no way to reset h/w. now  */
1343
1344                 if_inc_counter(ifp, IFCOUNTER_OERRORS, 1);
1345                 sc->malo_stats.mst_watchdog++;
1346         }
1347 }
1348
1349 static int
1350 malo_hal_reset(struct malo_softc *sc)
1351 {
1352         static int first = 0;
1353         struct ifnet *ifp = sc->malo_ifp;
1354         struct ieee80211com *ic = ifp->if_l2com;
1355         struct malo_hal *mh = sc->malo_mh;
1356
1357         if (first == 0) {
1358                 /*
1359                  * NB: when the device firstly is initialized, sometimes
1360                  * firmware could override rx/tx dma registers so we re-set
1361                  * these values once.
1362                  */
1363                 malo_hal_set_rxtxdma(sc);
1364                 first = 1;
1365         }
1366
1367         malo_hal_setantenna(mh, MHA_ANTENNATYPE_RX, sc->malo_rxantenna);
1368         malo_hal_setantenna(mh, MHA_ANTENNATYPE_TX, sc->malo_txantenna);
1369         malo_hal_setradio(mh, 1, MHP_AUTO_PREAMBLE);
1370         malo_chan_set(sc, ic->ic_curchan);
1371
1372         /* XXX needs other stuffs?  */
1373
1374         return 1;
1375 }
1376
1377 static __inline struct mbuf *
1378 malo_getrxmbuf(struct malo_softc *sc, struct malo_rxbuf *bf)
1379 {
1380         struct mbuf *m;
1381         bus_addr_t paddr;
1382         int error;
1383
1384         /* XXX don't need mbuf, just dma buffer */
1385         m = m_getjcl(M_NOWAIT, MT_DATA, M_PKTHDR, MJUMPAGESIZE);
1386         if (m == NULL) {
1387                 sc->malo_stats.mst_rx_nombuf++; /* XXX */
1388                 return NULL;
1389         }
1390         error = bus_dmamap_load(sc->malo_dmat, bf->bf_dmamap,
1391             mtod(m, caddr_t), MJUMPAGESIZE,
1392             malo_load_cb, &paddr, BUS_DMA_NOWAIT);
1393         if (error != 0) {
1394                 if_printf(sc->malo_ifp,
1395                     "%s: bus_dmamap_load failed, error %d\n", __func__, error);
1396                 m_freem(m);
1397                 return NULL;
1398         }
1399         bf->bf_data = paddr;
1400         bus_dmamap_sync(sc->malo_dmat, bf->bf_dmamap, BUS_DMASYNC_PREWRITE);
1401
1402         return m;
1403 }
1404
1405 static int
1406 malo_rxbuf_init(struct malo_softc *sc, struct malo_rxbuf *bf)
1407 {
1408         struct malo_rxdesc *ds;
1409
1410         ds = bf->bf_desc;
1411         if (bf->bf_m == NULL) {
1412                 bf->bf_m = malo_getrxmbuf(sc, bf);
1413                 if (bf->bf_m == NULL) {
1414                         /* mark descriptor to be skipped */
1415                         ds->rxcontrol = MALO_RXD_CTRL_OS_OWN;
1416                         /* NB: don't need PREREAD */
1417                         MALO_RXDESC_SYNC(sc, ds, BUS_DMASYNC_PREWRITE);
1418                         return ENOMEM;
1419                 }
1420         }
1421
1422         /*
1423          * Setup descriptor.
1424          */
1425         ds->qosctrl = 0;
1426         ds->snr = 0;
1427         ds->status = MALO_RXD_STATUS_IDLE;
1428         ds->channel = 0;
1429         ds->pktlen = htole16(MALO_RXSIZE);
1430         ds->nf = 0;
1431         ds->physbuffdata = htole32(bf->bf_data);
1432         /* NB: don't touch pPhysNext, set once */
1433         ds->rxcontrol = MALO_RXD_CTRL_DRIVER_OWN;
1434         MALO_RXDESC_SYNC(sc, ds, BUS_DMASYNC_PREREAD | BUS_DMASYNC_PREWRITE);
1435
1436         return 0;
1437 }
1438
1439 /*
1440  * Setup the rx data structures.  This should only be done once or we may get
1441  * out of sync with the firmware.
1442  */
1443 static int
1444 malo_startrecv(struct malo_softc *sc)
1445 {
1446         struct malo_rxbuf *bf, *prev;
1447         struct malo_rxdesc *ds;
1448         
1449         if (sc->malo_recvsetup == 1) {
1450                 malo_mode_init(sc);             /* set filters, etc. */
1451                 return 0;
1452         }
1453         
1454         prev = NULL;
1455         STAILQ_FOREACH(bf, &sc->malo_rxbuf, bf_list) {
1456                 int error = malo_rxbuf_init(sc, bf);
1457                 if (error != 0) {
1458                         DPRINTF(sc, MALO_DEBUG_RECV,
1459                             "%s: malo_rxbuf_init failed %d\n",
1460                             __func__, error);
1461                         return error;
1462                 }
1463                 if (prev != NULL) {
1464                         ds = prev->bf_desc;
1465                         ds->physnext = htole32(bf->bf_daddr);
1466                 }
1467                 prev = bf;
1468         }
1469         if (prev != NULL) {
1470                 ds = prev->bf_desc;
1471                 ds->physnext =
1472                     htole32(STAILQ_FIRST(&sc->malo_rxbuf)->bf_daddr);
1473         }
1474
1475         sc->malo_recvsetup = 1;
1476
1477         malo_mode_init(sc);             /* set filters, etc. */
1478         
1479         return 0;
1480 }
1481
1482 static void
1483 malo_init_locked(struct malo_softc *sc)
1484 {
1485         struct ifnet *ifp = sc->malo_ifp;
1486         struct malo_hal *mh = sc->malo_mh;
1487         int error;
1488         
1489         DPRINTF(sc, MALO_DEBUG_ANY, "%s: if_flags 0x%x\n",
1490             __func__, ifp->if_flags);
1491
1492         MALO_LOCK_ASSERT(sc);
1493         
1494         /*
1495          * Stop anything previously setup.  This is safe whether this is
1496          * the first time through or not.
1497          */
1498         malo_stop_locked(ifp, 0);
1499
1500         /*
1501          * Push state to the firmware.
1502          */
1503         if (!malo_hal_reset(sc)) {
1504                 if_printf(ifp, "%s: unable to reset hardware\n", __func__);
1505                 return;
1506         }
1507
1508         /*
1509          * Setup recv (once); transmit is already good to go.
1510          */
1511         error = malo_startrecv(sc);
1512         if (error != 0) {
1513                 if_printf(ifp, "%s: unable to start recv logic, error %d\n",
1514                     __func__, error);
1515                 return;
1516         }
1517
1518         /*
1519          * Enable interrupts.
1520          */
1521         sc->malo_imask = MALO_A2HRIC_BIT_RX_RDY
1522             | MALO_A2HRIC_BIT_TX_DONE
1523             | MALO_A2HRIC_BIT_OPC_DONE
1524             | MALO_A2HRIC_BIT_MAC_EVENT
1525             | MALO_A2HRIC_BIT_RX_PROBLEM
1526             | MALO_A2HRIC_BIT_ICV_ERROR
1527             | MALO_A2HRIC_BIT_RADAR_DETECT
1528             | MALO_A2HRIC_BIT_CHAN_SWITCH;
1529
1530         ifp->if_drv_flags |= IFF_DRV_RUNNING;
1531         malo_hal_intrset(mh, sc->malo_imask);
1532         callout_reset(&sc->malo_watchdog_timer, hz, malo_watchdog, sc);
1533 }
1534
1535 static void
1536 malo_init(void *arg)
1537 {
1538         struct malo_softc *sc = (struct malo_softc *) arg;
1539         struct ifnet *ifp = sc->malo_ifp;
1540         struct ieee80211com *ic = ifp->if_l2com;
1541         
1542         DPRINTF(sc, MALO_DEBUG_ANY, "%s: if_flags 0x%x\n",
1543             __func__, ifp->if_flags);
1544
1545         MALO_LOCK(sc);
1546         malo_init_locked(sc);
1547
1548         MALO_UNLOCK(sc);
1549
1550         if (ifp->if_drv_flags & IFF_DRV_RUNNING)
1551                 ieee80211_start_all(ic);        /* start all vap's */
1552 }
1553
1554 /*
1555  * Set the multicast filter contents into the hardware.
1556  */
1557 static void
1558 malo_setmcastfilter(struct malo_softc *sc)
1559 {
1560         struct ifnet *ifp = sc->malo_ifp;
1561         struct ieee80211com *ic = ifp->if_l2com;
1562         struct ifmultiaddr *ifma;
1563         uint8_t macs[IEEE80211_ADDR_LEN * MALO_HAL_MCAST_MAX];
1564         uint8_t *mp;
1565         int nmc;
1566
1567         mp = macs;
1568         nmc = 0;
1569
1570         if (ic->ic_opmode == IEEE80211_M_MONITOR ||
1571             (ifp->if_flags & (IFF_ALLMULTI | IFF_PROMISC)))
1572                 goto all;
1573         
1574         if_maddr_rlock(ifp);
1575         TAILQ_FOREACH(ifma, &ifp->if_multiaddrs, ifma_link) {
1576                 if (ifma->ifma_addr->sa_family != AF_LINK)
1577                         continue;
1578
1579                 if (nmc == MALO_HAL_MCAST_MAX) {
1580                         ifp->if_flags |= IFF_ALLMULTI;
1581                         if_maddr_runlock(ifp);
1582                         goto all;
1583                 }
1584                 IEEE80211_ADDR_COPY(mp,
1585                     LLADDR((struct sockaddr_dl *)ifma->ifma_addr));
1586
1587                 mp += IEEE80211_ADDR_LEN, nmc++;
1588         }
1589         if_maddr_runlock(ifp);
1590
1591         malo_hal_setmcast(sc->malo_mh, nmc, macs);
1592
1593 all:
1594         /*
1595          * XXX we don't know how to set the f/w for supporting
1596          * IFF_ALLMULTI | IFF_PROMISC cases
1597          */
1598         return;
1599 }
1600
1601 static int
1602 malo_mode_init(struct malo_softc *sc)
1603 {
1604         struct ifnet *ifp = sc->malo_ifp;
1605         struct ieee80211com *ic = ifp->if_l2com;
1606         struct malo_hal *mh = sc->malo_mh;
1607
1608         /*
1609          * NB: Ignore promisc in hostap mode; it's set by the
1610          * bridge.  This is wrong but we have no way to
1611          * identify internal requests (from the bridge)
1612          * versus external requests such as for tcpdump.
1613          */
1614         malo_hal_setpromisc(mh, (ifp->if_flags & IFF_PROMISC) &&
1615             ic->ic_opmode != IEEE80211_M_HOSTAP);
1616         malo_setmcastfilter(sc);
1617
1618         return ENXIO;
1619 }
1620
1621 static void
1622 malo_tx_draintxq(struct malo_softc *sc, struct malo_txq *txq)
1623 {
1624         struct ieee80211_node *ni;
1625         struct malo_txbuf *bf;
1626         u_int ix;
1627         
1628         /*
1629          * NB: this assumes output has been stopped and
1630          *     we do not need to block malo_tx_tasklet
1631          */
1632         for (ix = 0;; ix++) {
1633                 MALO_TXQ_LOCK(txq);
1634                 bf = STAILQ_FIRST(&txq->active);
1635                 if (bf == NULL) {
1636                         MALO_TXQ_UNLOCK(txq);
1637                         break;
1638                 }
1639                 STAILQ_REMOVE_HEAD(&txq->active, bf_list);
1640                 MALO_TXQ_UNLOCK(txq);
1641 #ifdef MALO_DEBUG
1642                 if (sc->malo_debug & MALO_DEBUG_RESET) {
1643                         struct ifnet *ifp = sc->malo_ifp;
1644                         struct ieee80211com *ic = ifp->if_l2com;
1645                         const struct malo_txrec *tr =
1646                             mtod(bf->bf_m, const struct malo_txrec *);
1647                         malo_printtxbuf(bf, txq->qnum, ix);
1648                         ieee80211_dump_pkt(ic, (const uint8_t *)&tr->wh,
1649                             bf->bf_m->m_len - sizeof(tr->fwlen), 0, -1);
1650                 }
1651 #endif /* MALO_DEBUG */
1652                 bus_dmamap_unload(sc->malo_dmat, bf->bf_dmamap);
1653                 ni = bf->bf_node;
1654                 bf->bf_node = NULL;
1655                 if (ni != NULL) {
1656                         /*
1657                          * Reclaim node reference.
1658                          */
1659                         ieee80211_free_node(ni);
1660                 }
1661                 m_freem(bf->bf_m);
1662                 bf->bf_m = NULL;
1663                 
1664                 MALO_TXQ_LOCK(txq);
1665                 STAILQ_INSERT_TAIL(&txq->free, bf, bf_list);
1666                 txq->nfree++;
1667                 MALO_TXQ_UNLOCK(txq);
1668         }
1669 }
1670
1671 static void
1672 malo_stop_locked(struct ifnet *ifp, int disable)
1673 {
1674         struct malo_softc *sc = ifp->if_softc;
1675         struct malo_hal *mh = sc->malo_mh;
1676         int i;
1677
1678         DPRINTF(sc, MALO_DEBUG_ANY, "%s: invalid %u if_flags 0x%x\n",
1679             __func__, sc->malo_invalid, ifp->if_flags);
1680
1681         MALO_LOCK_ASSERT(sc);
1682
1683         if (!(ifp->if_drv_flags & IFF_DRV_RUNNING))
1684                 return;
1685
1686         /*
1687          * Shutdown the hardware and driver:
1688          *    disable interrupts
1689          *    turn off the radio
1690          *    drain and release tx queues
1691          *
1692          * Note that some of this work is not possible if the hardware
1693          * is gone (invalid).
1694          */
1695         ifp->if_drv_flags &= ~IFF_DRV_RUNNING;
1696         callout_stop(&sc->malo_watchdog_timer);
1697         sc->malo_timer = 0;
1698         /* diable interrupt.  */
1699         malo_hal_intrset(mh, 0);
1700         /* turn off the radio.  */
1701         malo_hal_setradio(mh, 0, MHP_AUTO_PREAMBLE);
1702
1703         /* drain and release tx queues.  */
1704         for (i = 0; i < MALO_NUM_TX_QUEUES; i++)
1705                 malo_tx_draintxq(sc, &sc->malo_txq[i]);
1706 }
1707
1708 static int
1709 malo_ioctl(struct ifnet *ifp, u_long cmd, caddr_t data)
1710 {
1711 #define MALO_IS_RUNNING(ifp) \
1712         ((ifp->if_flags & IFF_UP) && (ifp->if_drv_flags & IFF_DRV_RUNNING))
1713         struct malo_softc *sc = ifp->if_softc;
1714         struct ieee80211com *ic = ifp->if_l2com;
1715         struct ifreq *ifr = (struct ifreq *) data;
1716         int error = 0, startall = 0;
1717
1718         MALO_LOCK(sc);
1719         switch (cmd) {
1720         case SIOCSIFFLAGS:
1721                 if (MALO_IS_RUNNING(ifp)) {
1722                         /*
1723                          * To avoid rescanning another access point,
1724                          * do not call malo_init() here.  Instead,
1725                          * only reflect promisc mode settings.
1726                          */
1727                         malo_mode_init(sc);
1728                 } else if (ifp->if_flags & IFF_UP) {
1729                         /*
1730                          * Beware of being called during attach/detach
1731                          * to reset promiscuous mode.  In that case we
1732                          * will still be marked UP but not RUNNING.
1733                          * However trying to re-init the interface
1734                          * is the wrong thing to do as we've already
1735                          * torn down much of our state.  There's
1736                          * probably a better way to deal with this.
1737                          */
1738                         if (!sc->malo_invalid) {
1739                                 malo_init_locked(sc);
1740                                 startall = 1;
1741                         }
1742                 } else
1743                         malo_stop_locked(ifp, 1);
1744                 break;
1745         case SIOCGIFMEDIA:
1746         case SIOCSIFMEDIA:
1747                 error = ifmedia_ioctl(ifp, ifr, &ic->ic_media, cmd);
1748                 break;
1749         default:
1750                 error = ether_ioctl(ifp, cmd, data);
1751                 break;
1752         }
1753         MALO_UNLOCK(sc);
1754
1755         if (startall)
1756                 ieee80211_start_all(ic);
1757         return error;
1758 #undef MALO_IS_RUNNING
1759 }
1760
1761 /*
1762  * Callback from the 802.11 layer to update the slot time
1763  * based on the current setting.  We use it to notify the
1764  * firmware of ERP changes and the f/w takes care of things
1765  * like slot time and preamble.
1766  */
1767 static void
1768 malo_updateslot(struct ifnet *ifp)
1769 {
1770         struct malo_softc *sc = ifp->if_softc;
1771         struct ieee80211com *ic = ifp->if_l2com;
1772         struct malo_hal *mh = sc->malo_mh;
1773         int error;
1774         
1775         /* NB: can be called early; suppress needless cmds */
1776         if ((ifp->if_drv_flags & IFF_DRV_RUNNING) == 0)
1777                 return;
1778
1779         DPRINTF(sc, MALO_DEBUG_RESET,
1780             "%s: chan %u MHz/flags 0x%x %s slot, (ic_flags 0x%x)\n",
1781             __func__, ic->ic_curchan->ic_freq, ic->ic_curchan->ic_flags,
1782             ic->ic_flags & IEEE80211_F_SHSLOT ? "short" : "long", ic->ic_flags);
1783
1784         if (ic->ic_flags & IEEE80211_F_SHSLOT)
1785                 error = malo_hal_set_slot(mh, 1);
1786         else
1787                 error = malo_hal_set_slot(mh, 0);
1788
1789         if (error != 0)
1790                 device_printf(sc->malo_dev, "setting %s slot failed\n",
1791                         ic->ic_flags & IEEE80211_F_SHSLOT ? "short" : "long");
1792 }
1793
1794 static int
1795 malo_newstate(struct ieee80211vap *vap, enum ieee80211_state nstate, int arg)
1796 {
1797         struct ieee80211com *ic = vap->iv_ic;
1798         struct malo_softc *sc = ic->ic_ifp->if_softc;
1799         struct malo_hal *mh = sc->malo_mh;
1800         int error;
1801
1802         DPRINTF(sc, MALO_DEBUG_STATE, "%s: %s -> %s\n", __func__,
1803             ieee80211_state_name[vap->iv_state],
1804             ieee80211_state_name[nstate]);
1805
1806         /*
1807          * Invoke the net80211 layer first so iv_bss is setup.
1808          */
1809         error = MALO_VAP(vap)->malo_newstate(vap, nstate, arg);
1810         if (error != 0)
1811                 return error;
1812
1813         if (nstate == IEEE80211_S_RUN && vap->iv_state != IEEE80211_S_RUN) {
1814                 struct ieee80211_node *ni = vap->iv_bss;
1815                 enum ieee80211_phymode mode = ieee80211_chan2mode(ni->ni_chan);
1816                 const struct ieee80211_txparam *tp = &vap->iv_txparms[mode];
1817
1818                 DPRINTF(sc, MALO_DEBUG_STATE,
1819                     "%s: %s(RUN): iv_flags 0x%08x bintvl %d bssid %s "
1820                     "capinfo 0x%04x chan %d associd 0x%x mode %d rate %d\n",
1821                     vap->iv_ifp->if_xname, __func__, vap->iv_flags,
1822                     ni->ni_intval, ether_sprintf(ni->ni_bssid), ni->ni_capinfo,
1823                     ieee80211_chan2ieee(ic, ic->ic_curchan),
1824                     ni->ni_associd, mode, tp->ucastrate);
1825
1826                 malo_hal_setradio(mh, 1,
1827                     (ic->ic_flags & IEEE80211_F_SHPREAMBLE) ?
1828                         MHP_SHORT_PREAMBLE : MHP_LONG_PREAMBLE);
1829                 malo_hal_setassocid(sc->malo_mh, ni->ni_bssid, ni->ni_associd);
1830                 malo_hal_set_rate(mh, mode, 
1831                    tp->ucastrate == IEEE80211_FIXED_RATE_NONE ?
1832                        0 : malo_fix2rate(tp->ucastrate));
1833         }
1834         return 0;
1835 }
1836
1837 static int
1838 malo_raw_xmit(struct ieee80211_node *ni, struct mbuf *m,
1839         const struct ieee80211_bpf_params *params)
1840 {
1841         struct ieee80211com *ic = ni->ni_ic;
1842         struct ifnet *ifp = ic->ic_ifp;
1843         struct malo_softc *sc = ifp->if_softc;
1844         struct malo_txbuf *bf;
1845         struct malo_txq *txq;
1846
1847         if ((ifp->if_drv_flags & IFF_DRV_RUNNING) == 0 || sc->malo_invalid) {
1848                 ieee80211_free_node(ni);
1849                 m_freem(m);
1850                 return ENETDOWN;
1851         }
1852
1853         /*
1854          * Grab a TX buffer and associated resources.  Note that we depend
1855          * on the classification by the 802.11 layer to get to the right h/w
1856          * queue.  Management frames must ALWAYS go on queue 1 but we
1857          * cannot just force that here because we may receive non-mgt frames.
1858          */
1859         txq = &sc->malo_txq[0];
1860         bf = malo_getbuf(sc, txq);
1861         if (bf == NULL) {
1862                 /* XXX blocks other traffic */
1863                 ifp->if_drv_flags |= IFF_DRV_OACTIVE;
1864                 ieee80211_free_node(ni);
1865                 m_freem(m);
1866                 return ENOBUFS;
1867         }
1868
1869         /*
1870          * Pass the frame to the h/w for transmission.
1871          */
1872         if (malo_tx_start(sc, ni, bf, m) != 0) {
1873                 if_inc_counter(ifp, IFCOUNTER_OERRORS, 1);
1874                 bf->bf_m = NULL;
1875                 bf->bf_node = NULL;
1876                 MALO_TXQ_LOCK(txq);
1877                 STAILQ_INSERT_HEAD(&txq->free, bf, bf_list);
1878                 txq->nfree++;
1879                 MALO_TXQ_UNLOCK(txq);
1880
1881                 ieee80211_free_node(ni);
1882                 return EIO;             /* XXX */
1883         }
1884
1885         /*
1886          * NB: We don't need to lock against tx done because this just
1887          * prods the firmware to check the transmit descriptors.  The firmware
1888          * will also start fetching descriptors by itself if it notices
1889          * new ones are present when it goes to deliver a tx done interrupt
1890          * to the host. So if we race with tx done processing it's ok.
1891          * Delivering the kick here rather than in malo_tx_start is
1892          * an optimization to avoid poking the firmware for each packet.
1893          *
1894          * NB: the queue id isn't used so 0 is ok.
1895          */
1896         malo_hal_txstart(sc->malo_mh, 0/*XXX*/);
1897
1898         return 0;
1899 }
1900
1901 static void
1902 malo_sysctlattach(struct malo_softc *sc)
1903 {
1904 #ifdef  MALO_DEBUG
1905         struct sysctl_ctx_list *ctx = device_get_sysctl_ctx(sc->malo_dev);
1906         struct sysctl_oid *tree = device_get_sysctl_tree(sc->malo_dev);
1907
1908         sc->malo_debug = malo_debug;
1909         SYSCTL_ADD_INT(ctx, SYSCTL_CHILDREN(tree), OID_AUTO,
1910                 "debug", CTLFLAG_RW, &sc->malo_debug, 0,
1911                 "control debugging printfs");
1912 #endif
1913 }
1914
1915 static void
1916 malo_announce(struct malo_softc *sc)
1917 {
1918         struct ifnet *ifp = sc->malo_ifp;
1919
1920         if_printf(ifp, "versions [hw %d fw %d.%d.%d.%d] (regioncode %d)\n",
1921                 sc->malo_hwspecs.hwversion,
1922                 (sc->malo_hwspecs.fw_releasenum >> 24) & 0xff,
1923                 (sc->malo_hwspecs.fw_releasenum >> 16) & 0xff,
1924                 (sc->malo_hwspecs.fw_releasenum >> 8) & 0xff,
1925                 (sc->malo_hwspecs.fw_releasenum >> 0) & 0xff,
1926                 sc->malo_hwspecs.regioncode);
1927
1928         if (bootverbose || malo_rxbuf != MALO_RXBUF)
1929                 if_printf(ifp, "using %u rx buffers\n", malo_rxbuf);
1930         if (bootverbose || malo_txbuf != MALO_TXBUF)
1931                 if_printf(ifp, "using %u tx buffers\n", malo_txbuf);
1932 }
1933
1934 /*
1935  * Convert net80211 channel to a HAL channel.
1936  */
1937 static void
1938 malo_mapchan(struct malo_hal_channel *hc, const struct ieee80211_channel *chan)
1939 {
1940         hc->channel = chan->ic_ieee;
1941
1942         *(uint32_t *)&hc->flags = 0;
1943         if (IEEE80211_IS_CHAN_2GHZ(chan))
1944                 hc->flags.freqband = MALO_FREQ_BAND_2DOT4GHZ;
1945 }
1946
1947 /*
1948  * Set/change channels.  If the channel is really being changed,
1949  * it's done by reseting the chip.  To accomplish this we must
1950  * first cleanup any pending DMA, then restart stuff after a la
1951  * malo_init.
1952  */
1953 static int
1954 malo_chan_set(struct malo_softc *sc, struct ieee80211_channel *chan)
1955 {
1956         struct malo_hal *mh = sc->malo_mh;
1957         struct malo_hal_channel hchan;
1958
1959         DPRINTF(sc, MALO_DEBUG_RESET, "%s: chan %u MHz/flags 0x%x\n",
1960             __func__, chan->ic_freq, chan->ic_flags);
1961
1962         /*
1963          * Convert to a HAL channel description with the flags constrained
1964          * to reflect the current operating mode.
1965          */
1966         malo_mapchan(&hchan, chan);
1967         malo_hal_intrset(mh, 0);                /* disable interrupts */
1968         malo_hal_setchannel(mh, &hchan);
1969         malo_hal_settxpower(mh, &hchan);
1970
1971         /*
1972          * Update internal state.
1973          */
1974         sc->malo_tx_th.wt_chan_freq = htole16(chan->ic_freq);
1975         sc->malo_rx_th.wr_chan_freq = htole16(chan->ic_freq);
1976         if (IEEE80211_IS_CHAN_ANYG(chan)) {
1977                 sc->malo_tx_th.wt_chan_flags = htole16(IEEE80211_CHAN_G);
1978                 sc->malo_rx_th.wr_chan_flags = htole16(IEEE80211_CHAN_G);
1979         } else {
1980                 sc->malo_tx_th.wt_chan_flags = htole16(IEEE80211_CHAN_B);
1981                 sc->malo_rx_th.wr_chan_flags = htole16(IEEE80211_CHAN_B);
1982         }
1983         sc->malo_curchan = hchan;
1984         malo_hal_intrset(mh, sc->malo_imask);
1985
1986         return 0;
1987 }
1988
1989 static void
1990 malo_scan_start(struct ieee80211com *ic)
1991 {
1992         struct ifnet *ifp = ic->ic_ifp;
1993         struct malo_softc *sc = ifp->if_softc;
1994
1995         DPRINTF(sc, MALO_DEBUG_STATE, "%s\n", __func__);
1996 }
1997
1998 static void
1999 malo_scan_end(struct ieee80211com *ic)
2000 {
2001         struct ifnet *ifp = ic->ic_ifp;
2002         struct malo_softc *sc = ifp->if_softc;
2003
2004         DPRINTF(sc, MALO_DEBUG_STATE, "%s\n", __func__);
2005 }
2006
2007 static void
2008 malo_set_channel(struct ieee80211com *ic)
2009 {
2010         struct ifnet *ifp = ic->ic_ifp;
2011         struct malo_softc *sc = ifp->if_softc;
2012
2013         (void) malo_chan_set(sc, ic->ic_curchan);
2014 }
2015
2016 static void
2017 malo_rx_proc(void *arg, int npending)
2018 {
2019 #define IEEE80211_DIR_DSTODS(wh)                                        \
2020         ((((const struct ieee80211_frame *)wh)->i_fc[1] &               \
2021             IEEE80211_FC1_DIR_MASK) == IEEE80211_FC1_DIR_DSTODS)
2022         struct malo_softc *sc = arg;
2023         struct ifnet *ifp = sc->malo_ifp;
2024         struct ieee80211com *ic = ifp->if_l2com;
2025         struct malo_rxbuf *bf;
2026         struct malo_rxdesc *ds;
2027         struct mbuf *m, *mnew;
2028         struct ieee80211_qosframe *wh;
2029         struct ieee80211_qosframe_addr4 *wh4;
2030         struct ieee80211_node *ni;
2031         int off, len, hdrlen, pktlen, rssi, ntodo;
2032         uint8_t *data, status;
2033         uint32_t readptr, writeptr;
2034
2035         DPRINTF(sc, MALO_DEBUG_RX_PROC,
2036             "%s: pending %u rdptr(0x%x) 0x%x wrptr(0x%x) 0x%x\n",
2037             __func__, npending,
2038             sc->malo_hwspecs.rxdesc_read,
2039             malo_bar0_read4(sc, sc->malo_hwspecs.rxdesc_read),
2040             sc->malo_hwspecs.rxdesc_write,
2041             malo_bar0_read4(sc, sc->malo_hwspecs.rxdesc_write));
2042
2043         readptr = malo_bar0_read4(sc, sc->malo_hwspecs.rxdesc_read);
2044         writeptr = malo_bar0_read4(sc, sc->malo_hwspecs.rxdesc_write);
2045         if (readptr == writeptr)
2046                 return;
2047
2048         bf = sc->malo_rxnext;
2049         for (ntodo = malo_rxquota; ntodo > 0 && readptr != writeptr; ntodo--) {
2050                 if (bf == NULL) {
2051                         bf = STAILQ_FIRST(&sc->malo_rxbuf);
2052                         break;
2053                 }
2054                 ds = bf->bf_desc;
2055                 if (bf->bf_m == NULL) {
2056                         /*
2057                          * If data allocation failed previously there
2058                          * will be no buffer; try again to re-populate it.
2059                          * Note the firmware will not advance to the next
2060                          * descriptor with a dma buffer so we must mimic
2061                          * this or we'll get out of sync.
2062                          */ 
2063                         DPRINTF(sc, MALO_DEBUG_ANY,
2064                             "%s: rx buf w/o dma memory\n", __func__);
2065                         (void)malo_rxbuf_init(sc, bf);
2066                         break;
2067                 }
2068                 MALO_RXDESC_SYNC(sc, ds,
2069                     BUS_DMASYNC_POSTREAD | BUS_DMASYNC_POSTWRITE);
2070                 if (ds->rxcontrol != MALO_RXD_CTRL_DMA_OWN)
2071                         break;
2072
2073                 readptr = le32toh(ds->physnext);
2074
2075 #ifdef MALO_DEBUG
2076                 if (sc->malo_debug & MALO_DEBUG_RECV_DESC)
2077                         malo_printrxbuf(bf, 0);
2078 #endif
2079                 status = ds->status;
2080                 if (status & MALO_RXD_STATUS_DECRYPT_ERR_MASK) {
2081                         if_inc_counter(ifp, IFCOUNTER_IERRORS, 1);
2082                         goto rx_next;
2083                 }
2084                 /*
2085                  * Sync the data buffer.
2086                  */
2087                 len = le16toh(ds->pktlen);
2088                 bus_dmamap_sync(sc->malo_dmat, bf->bf_dmamap,
2089                     BUS_DMASYNC_POSTREAD);
2090                 /*
2091                  * The 802.11 header is provided all or in part at the front;
2092                  * use it to calculate the true size of the header that we'll
2093                  * construct below.  We use this to figure out where to copy
2094                  * payload prior to constructing the header.
2095                  */
2096                 m = bf->bf_m;
2097                 data = mtod(m, uint8_t *);
2098                 hdrlen = ieee80211_anyhdrsize(data + sizeof(uint16_t));
2099                 off = sizeof(uint16_t) + sizeof(struct ieee80211_frame_addr4);
2100
2101                 /*
2102                  * Calculate RSSI. XXX wrong
2103                  */
2104                 rssi = 2 * ((int) ds->snr - ds->nf);    /* NB: .5 dBm  */
2105                 if (rssi > 100)
2106                         rssi = 100;
2107
2108                 pktlen = hdrlen + (len - off);
2109                 /*
2110                  * NB: we know our frame is at least as large as
2111                  * IEEE80211_MIN_LEN because there is a 4-address frame at
2112                  * the front.  Hence there's no need to vet the packet length.
2113                  * If the frame in fact is too small it should be discarded
2114                  * at the net80211 layer.
2115                  */
2116
2117                 /* XXX don't need mbuf, just dma buffer */
2118                 mnew = malo_getrxmbuf(sc, bf);
2119                 if (mnew == NULL) {
2120                         if_inc_counter(ifp, IFCOUNTER_IERRORS, 1);
2121                         goto rx_next;
2122                 }
2123                 /*
2124                  * Attach the dma buffer to the mbuf; malo_rxbuf_init will
2125                  * re-setup the rx descriptor using the replacement dma
2126                  * buffer we just installed above.
2127                  */
2128                 bf->bf_m = mnew;
2129                 m->m_data += off - hdrlen;
2130                 m->m_pkthdr.len = m->m_len = pktlen;
2131                 m->m_pkthdr.rcvif = ifp;
2132
2133                 /*
2134                  * Piece 802.11 header together.
2135                  */
2136                 wh = mtod(m, struct ieee80211_qosframe *);
2137                 /* NB: don't need to do this sometimes but ... */
2138                 /* XXX special case so we can memcpy after m_devget? */
2139                 ovbcopy(data + sizeof(uint16_t), wh, hdrlen);
2140                 if (IEEE80211_QOS_HAS_SEQ(wh)) {
2141                         if (IEEE80211_DIR_DSTODS(wh)) {
2142                                 wh4 = mtod(m,
2143                                     struct ieee80211_qosframe_addr4*);
2144                                 *(uint16_t *)wh4->i_qos = ds->qosctrl;
2145                         } else {
2146                                 *(uint16_t *)wh->i_qos = ds->qosctrl;
2147                         }
2148                 }
2149                 if (ieee80211_radiotap_active(ic)) {
2150                         sc->malo_rx_th.wr_flags = 0;
2151                         sc->malo_rx_th.wr_rate = ds->rate;
2152                         sc->malo_rx_th.wr_antsignal = rssi;
2153                         sc->malo_rx_th.wr_antnoise = ds->nf;
2154                 }
2155 #ifdef MALO_DEBUG
2156                 if (IFF_DUMPPKTS_RECV(sc, wh)) {
2157                         ieee80211_dump_pkt(ic, mtod(m, caddr_t),
2158                             len, ds->rate, rssi);
2159                 }
2160 #endif
2161                 if_inc_counter(ifp, IFCOUNTER_IPACKETS, 1);
2162                 
2163                 /* dispatch */
2164                 ni = ieee80211_find_rxnode(ic,
2165                     (struct ieee80211_frame_min *)wh);
2166                 if (ni != NULL) {
2167                         (void) ieee80211_input(ni, m, rssi, ds->nf);
2168                         ieee80211_free_node(ni);
2169                 } else
2170                         (void) ieee80211_input_all(ic, m, rssi, ds->nf);
2171 rx_next:
2172                 /* NB: ignore ENOMEM so we process more descriptors */
2173                 (void) malo_rxbuf_init(sc, bf);
2174                 bf = STAILQ_NEXT(bf, bf_list);
2175         }
2176         
2177         malo_bar0_write4(sc, sc->malo_hwspecs.rxdesc_read, readptr);
2178         sc->malo_rxnext = bf;
2179
2180         if ((ifp->if_drv_flags & IFF_DRV_OACTIVE) == 0 &&
2181             !IFQ_IS_EMPTY(&ifp->if_snd))
2182                 malo_start(ifp);
2183 #undef IEEE80211_DIR_DSTODS
2184 }
2185
2186 static void
2187 malo_stop(struct ifnet *ifp, int disable)
2188 {
2189         struct malo_softc *sc = ifp->if_softc;
2190
2191         MALO_LOCK(sc);
2192         malo_stop_locked(ifp, disable);
2193         MALO_UNLOCK(sc);
2194 }
2195
2196 /*
2197  * Reclaim all tx queue resources.
2198  */
2199 static void
2200 malo_tx_cleanup(struct malo_softc *sc)
2201 {
2202         int i;
2203
2204         for (i = 0; i < MALO_NUM_TX_QUEUES; i++)
2205                 malo_tx_cleanupq(sc, &sc->malo_txq[i]);
2206 }
2207
2208 int
2209 malo_detach(struct malo_softc *sc)
2210 {
2211         struct ifnet *ifp = sc->malo_ifp;
2212         struct ieee80211com *ic = ifp->if_l2com;
2213
2214         DPRINTF(sc, MALO_DEBUG_ANY, "%s: if_flags %x\n",
2215                 __func__, ifp->if_flags);
2216
2217         malo_stop(ifp, 1);
2218
2219         if (sc->malo_tq != NULL) {
2220                 taskqueue_drain(sc->malo_tq, &sc->malo_rxtask);
2221                 taskqueue_drain(sc->malo_tq, &sc->malo_txtask);
2222                 taskqueue_free(sc->malo_tq);
2223                 sc->malo_tq = NULL;
2224         }
2225
2226         /*
2227          * NB: the order of these is important:
2228          * o call the 802.11 layer before detaching the hal to
2229          *   insure callbacks into the driver to delete global
2230          *   key cache entries can be handled
2231          * o reclaim the tx queue data structures after calling
2232          *   the 802.11 layer as we'll get called back to reclaim
2233          *   node state and potentially want to use them
2234          * o to cleanup the tx queues the hal is called, so detach
2235          *   it last
2236          * Other than that, it's straightforward...
2237          */
2238         ieee80211_ifdetach(ic);
2239         callout_drain(&sc->malo_watchdog_timer);
2240         malo_dma_cleanup(sc);
2241         malo_tx_cleanup(sc);
2242         malo_hal_detach(sc->malo_mh);
2243         if_free(ifp);
2244
2245         MALO_LOCK_DESTROY(sc);
2246
2247         return 0;
2248 }
2249
2250 void
2251 malo_shutdown(struct malo_softc *sc)
2252 {
2253         malo_stop(sc->malo_ifp, 1);
2254 }
2255
2256 void
2257 malo_suspend(struct malo_softc *sc)
2258 {
2259         struct ifnet *ifp = sc->malo_ifp;
2260
2261         DPRINTF(sc, MALO_DEBUG_ANY, "%s: if_flags %x\n",
2262                 __func__, ifp->if_flags);
2263
2264         malo_stop(ifp, 1);
2265 }
2266
2267 void
2268 malo_resume(struct malo_softc *sc)
2269 {
2270         struct ifnet *ifp = sc->malo_ifp;
2271
2272         DPRINTF(sc, MALO_DEBUG_ANY, "%s: if_flags %x\n",
2273                 __func__, ifp->if_flags);
2274
2275         if (ifp->if_flags & IFF_UP)
2276                 malo_init(sc);
2277 }