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