if_malo.c revision 283527
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 283527 2015-05-25 13:51:13Z glebius $");
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	 (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
122static MALLOC_DEFINE(M_MALODEV, "malodev", "malo driver dma buffers");
123
124static 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]);
128static  void	malo_vap_delete(struct ieee80211vap *);
129static	int	malo_dma_setup(struct malo_softc *);
130static	int	malo_setup_hwdma(struct malo_softc *);
131static	void	malo_txq_init(struct malo_softc *, struct malo_txq *, int);
132static	void	malo_tx_cleanupq(struct malo_softc *, struct malo_txq *);
133static	void	malo_start(struct ifnet *);
134static	void	malo_watchdog(void *);
135static	int	malo_ioctl(struct ifnet *, u_long, caddr_t);
136static	void	malo_updateslot(struct ifnet *);
137static	int	malo_newstate(struct ieee80211vap *, enum ieee80211_state, int);
138static	void	malo_scan_start(struct ieee80211com *);
139static	void	malo_scan_end(struct ieee80211com *);
140static	void	malo_set_channel(struct ieee80211com *);
141static	int	malo_raw_xmit(struct ieee80211_node *, struct mbuf *,
142		    const struct ieee80211_bpf_params *);
143static	void	malo_sysctlattach(struct malo_softc *);
144static	void	malo_announce(struct malo_softc *);
145static	void	malo_dma_cleanup(struct malo_softc *);
146static	void	malo_stop_locked(struct ifnet *, int);
147static	int	malo_chan_set(struct malo_softc *, struct ieee80211_channel *);
148static	int	malo_mode_init(struct malo_softc *);
149static	void	malo_tx_proc(void *, int);
150static	void	malo_rx_proc(void *, int);
151static	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 */
158static uint32_t
159malo_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
164static void
165malo_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__, (uintmax_t)off, val);
169
170	bus_space_write_4(sc->malo_io0t, sc->malo_io0h, off, val);
171}
172
173int
174malo_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	ic->ic_name = device_get_nameunit(sc->malo_dev);
280	/* XXX not right but it's not used anywhere important */
281	ic->ic_phytype = IEEE80211_T_OFDM;
282	ic->ic_opmode = IEEE80211_M_STA;
283	ic->ic_caps =
284	      IEEE80211_C_STA			/* station mode supported */
285	    | IEEE80211_C_BGSCAN		/* capable of bg scanning */
286	    | IEEE80211_C_MONITOR		/* monitor mode */
287	    | IEEE80211_C_SHPREAMBLE		/* short preamble supported */
288	    | IEEE80211_C_SHSLOT		/* short slot time supported */
289	    | IEEE80211_C_TXPMGT		/* capable of txpow mgt */
290	    | IEEE80211_C_WPA			/* capable of WPA1+WPA2 */
291	    ;
292
293	/*
294	 * Transmit requires space in the packet for a special format transmit
295	 * record and optional padding between this record and the payload.
296	 * Ask the net80211 layer to arrange this when encapsulating
297	 * packets so we can add it efficiently.
298	 */
299	ic->ic_headroom = sizeof(struct malo_txrec) -
300		sizeof(struct ieee80211_frame);
301
302	/* call MI attach routine. */
303	ieee80211_ifattach(ic, sc->malo_hwspecs.macaddr);
304	/* override default methods */
305	ic->ic_vap_create = malo_vap_create;
306	ic->ic_vap_delete = malo_vap_delete;
307	ic->ic_raw_xmit = malo_raw_xmit;
308	ic->ic_updateslot = malo_updateslot;
309
310	ic->ic_scan_start = malo_scan_start;
311	ic->ic_scan_end = malo_scan_end;
312	ic->ic_set_channel = malo_set_channel;
313
314	sc->malo_invalid = 0;		/* ready to go, enable int handling */
315
316	ieee80211_radiotap_attach(ic,
317	    &sc->malo_tx_th.wt_ihdr, sizeof(sc->malo_tx_th),
318		MALO_TX_RADIOTAP_PRESENT,
319	    &sc->malo_rx_th.wr_ihdr, sizeof(sc->malo_rx_th),
320		MALO_RX_RADIOTAP_PRESENT);
321
322	/*
323	 * Setup dynamic sysctl's.
324	 */
325	malo_sysctlattach(sc);
326
327	if (bootverbose)
328		ieee80211_announce(ic);
329	malo_announce(sc);
330
331	return 0;
332bad2:
333	malo_dma_cleanup(sc);
334bad1:
335	malo_hal_detach(mh);
336bad:
337	if_free(ifp);
338	sc->malo_invalid = 1;
339
340	return error;
341}
342
343static struct ieee80211vap *
344malo_vap_create(struct ieee80211com *ic, const char name[IFNAMSIZ], int unit,
345    enum ieee80211_opmode opmode, int flags,
346    const uint8_t bssid[IEEE80211_ADDR_LEN],
347    const uint8_t mac[IEEE80211_ADDR_LEN])
348{
349	struct ifnet *ifp = ic->ic_ifp;
350	struct malo_vap *mvp;
351	struct ieee80211vap *vap;
352
353	if (!TAILQ_EMPTY(&ic->ic_vaps)) {
354		if_printf(ifp, "multiple vaps not supported\n");
355		return NULL;
356	}
357	switch (opmode) {
358	case IEEE80211_M_STA:
359		if (opmode == IEEE80211_M_STA)
360			flags |= IEEE80211_CLONE_NOBEACONS;
361		/* fall thru... */
362	case IEEE80211_M_MONITOR:
363		break;
364	default:
365		if_printf(ifp, "%s mode not supported\n",
366		    ieee80211_opmode_name[opmode]);
367		return NULL;		/* unsupported */
368	}
369	mvp = (struct malo_vap *) malloc(sizeof(struct malo_vap),
370	    M_80211_VAP, M_NOWAIT | M_ZERO);
371	if (mvp == NULL) {
372		if_printf(ifp, "cannot allocate vap state block\n");
373		return NULL;
374	}
375	vap = &mvp->malo_vap;
376	ieee80211_vap_setup(ic, vap, name, unit, opmode, flags, bssid, mac);
377
378	/* override state transition machine */
379	mvp->malo_newstate = vap->iv_newstate;
380	vap->iv_newstate = malo_newstate;
381
382	/* complete setup */
383	ieee80211_vap_attach(vap,
384	    ieee80211_media_change, ieee80211_media_status);
385	ic->ic_opmode = opmode;
386	return vap;
387}
388
389static void
390malo_vap_delete(struct ieee80211vap *vap)
391{
392	struct malo_vap *mvp = MALO_VAP(vap);
393
394	ieee80211_vap_detach(vap);
395	free(mvp, M_80211_VAP);
396}
397
398int
399malo_intr(void *arg)
400{
401	struct malo_softc *sc = arg;
402	struct malo_hal *mh = sc->malo_mh;
403	uint32_t status;
404
405	if (sc->malo_invalid) {
406		/*
407		 * The hardware is not ready/present, don't touch anything.
408		 * Note this can happen early on if the IRQ is shared.
409		 */
410		DPRINTF(sc, MALO_DEBUG_ANY, "%s: invalid; ignored\n", __func__);
411		return (FILTER_STRAY);
412	}
413
414	/*
415	 * Figure out the reason(s) for the interrupt.
416	 */
417	malo_hal_getisr(mh, &status);		/* NB: clears ISR too */
418	if (status == 0)			/* must be a shared irq */
419		return (FILTER_STRAY);
420
421	DPRINTF(sc, MALO_DEBUG_INTR, "%s: status 0x%x imask 0x%x\n",
422	    __func__, status, sc->malo_imask);
423
424	if (status & MALO_A2HRIC_BIT_RX_RDY)
425		taskqueue_enqueue_fast(sc->malo_tq, &sc->malo_rxtask);
426	if (status & MALO_A2HRIC_BIT_TX_DONE)
427		taskqueue_enqueue_fast(sc->malo_tq, &sc->malo_txtask);
428	if (status & MALO_A2HRIC_BIT_OPC_DONE)
429		malo_hal_cmddone(mh);
430	if (status & MALO_A2HRIC_BIT_MAC_EVENT)
431		;
432	if (status & MALO_A2HRIC_BIT_RX_PROBLEM)
433		;
434	if (status & MALO_A2HRIC_BIT_ICV_ERROR) {
435		/* TKIP ICV error */
436		sc->malo_stats.mst_rx_badtkipicv++;
437	}
438#ifdef MALO_DEBUG
439	if (((status | sc->malo_imask) ^ sc->malo_imask) != 0)
440		DPRINTF(sc, MALO_DEBUG_INTR,
441		    "%s: can't handle interrupt status 0x%x\n",
442		    __func__, status);
443#endif
444	return (FILTER_HANDLED);
445}
446
447static void
448malo_load_cb(void *arg, bus_dma_segment_t *segs, int nsegs, int error)
449{
450	bus_addr_t *paddr = (bus_addr_t*) arg;
451
452	KASSERT(error == 0, ("error %u on bus_dma callback", error));
453
454	*paddr = segs->ds_addr;
455}
456
457static int
458malo_desc_setup(struct malo_softc *sc, const char *name,
459    struct malo_descdma *dd,
460    int nbuf, size_t bufsize, int ndesc, size_t descsize)
461{
462	int error;
463	struct ifnet *ifp = sc->malo_ifp;
464	uint8_t *ds;
465
466	DPRINTF(sc, MALO_DEBUG_RESET,
467	    "%s: %s DMA: %u bufs (%ju) %u desc/buf (%ju)\n",
468	    __func__, name, nbuf, (uintmax_t) bufsize,
469	    ndesc, (uintmax_t) descsize);
470
471	dd->dd_name = name;
472	dd->dd_desc_len = nbuf * ndesc * descsize;
473
474	/*
475	 * Setup DMA descriptor area.
476	 */
477	error = bus_dma_tag_create(bus_get_dma_tag(sc->malo_dev),/* parent */
478		       PAGE_SIZE, 0,		/* alignment, bounds */
479		       BUS_SPACE_MAXADDR_32BIT,	/* lowaddr */
480		       BUS_SPACE_MAXADDR,	/* highaddr */
481		       NULL, NULL,		/* filter, filterarg */
482		       dd->dd_desc_len,		/* maxsize */
483		       1,			/* nsegments */
484		       dd->dd_desc_len,		/* maxsegsize */
485		       BUS_DMA_ALLOCNOW,	/* flags */
486		       NULL,			/* lockfunc */
487		       NULL,			/* lockarg */
488		       &dd->dd_dmat);
489	if (error != 0) {
490		if_printf(ifp, "cannot allocate %s DMA tag\n", dd->dd_name);
491		return error;
492	}
493
494	/* allocate descriptors */
495	error = bus_dmamem_alloc(dd->dd_dmat, (void**) &dd->dd_desc,
496	    BUS_DMA_NOWAIT | BUS_DMA_COHERENT, &dd->dd_dmamap);
497	if (error != 0) {
498		if_printf(ifp, "unable to alloc memory for %u %s descriptors, "
499		    "error %u\n", nbuf * ndesc, dd->dd_name, error);
500		goto fail1;
501	}
502
503	error = bus_dmamap_load(dd->dd_dmat, dd->dd_dmamap,
504	    dd->dd_desc, dd->dd_desc_len,
505	    malo_load_cb, &dd->dd_desc_paddr, BUS_DMA_NOWAIT);
506	if (error != 0) {
507		if_printf(ifp, "unable to map %s descriptors, error %u\n",
508		    dd->dd_name, error);
509		goto fail2;
510	}
511
512	ds = dd->dd_desc;
513	memset(ds, 0, dd->dd_desc_len);
514	DPRINTF(sc, MALO_DEBUG_RESET,
515	    "%s: %s DMA map: %p (%lu) -> 0x%jx (%lu)\n",
516	    __func__, dd->dd_name, ds, (u_long) dd->dd_desc_len,
517	    (uintmax_t) dd->dd_desc_paddr, /*XXX*/ (u_long) dd->dd_desc_len);
518
519	return 0;
520fail2:
521	bus_dmamem_free(dd->dd_dmat, dd->dd_desc, dd->dd_dmamap);
522fail1:
523	bus_dma_tag_destroy(dd->dd_dmat);
524	memset(dd, 0, sizeof(*dd));
525	return error;
526}
527
528#define	DS2PHYS(_dd, _ds) \
529	((_dd)->dd_desc_paddr + ((caddr_t)(_ds) - (caddr_t)(_dd)->dd_desc))
530
531static int
532malo_rxdma_setup(struct malo_softc *sc)
533{
534	struct ifnet *ifp = sc->malo_ifp;
535	int error, bsize, i;
536	struct malo_rxbuf *bf;
537	struct malo_rxdesc *ds;
538
539	error = malo_desc_setup(sc, "rx", &sc->malo_rxdma,
540	    malo_rxbuf, sizeof(struct malo_rxbuf),
541	    1, sizeof(struct malo_rxdesc));
542	if (error != 0)
543		return error;
544
545	/*
546	 * Allocate rx buffers and set them up.
547	 */
548	bsize = malo_rxbuf * sizeof(struct malo_rxbuf);
549	bf = malloc(bsize, M_MALODEV, M_NOWAIT | M_ZERO);
550	if (bf == NULL) {
551		if_printf(ifp, "malloc of %u rx buffers failed\n", bsize);
552		return error;
553	}
554	sc->malo_rxdma.dd_bufptr = bf;
555
556	STAILQ_INIT(&sc->malo_rxbuf);
557	ds = sc->malo_rxdma.dd_desc;
558	for (i = 0; i < malo_rxbuf; i++, bf++, ds++) {
559		bf->bf_desc = ds;
560		bf->bf_daddr = DS2PHYS(&sc->malo_rxdma, ds);
561		error = bus_dmamap_create(sc->malo_dmat, BUS_DMA_NOWAIT,
562		    &bf->bf_dmamap);
563		if (error != 0) {
564			if_printf(ifp, "%s: unable to dmamap for rx buffer, "
565			    "error %d\n", __func__, error);
566			return error;
567		}
568		/* NB: tail is intentional to preserve descriptor order */
569		STAILQ_INSERT_TAIL(&sc->malo_rxbuf, bf, bf_list);
570	}
571	return 0;
572}
573
574static int
575malo_txdma_setup(struct malo_softc *sc, struct malo_txq *txq)
576{
577	struct ifnet *ifp = sc->malo_ifp;
578	int error, bsize, i;
579	struct malo_txbuf *bf;
580	struct malo_txdesc *ds;
581
582	error = malo_desc_setup(sc, "tx", &txq->dma,
583	    malo_txbuf, sizeof(struct malo_txbuf),
584	    MALO_TXDESC, sizeof(struct malo_txdesc));
585	if (error != 0)
586		return error;
587
588	/* allocate and setup tx buffers */
589	bsize = malo_txbuf * sizeof(struct malo_txbuf);
590	bf = malloc(bsize, M_MALODEV, M_NOWAIT | M_ZERO);
591	if (bf == NULL) {
592		if_printf(ifp, "malloc of %u tx buffers failed\n",
593		    malo_txbuf);
594		return ENOMEM;
595	}
596	txq->dma.dd_bufptr = bf;
597
598	STAILQ_INIT(&txq->free);
599	txq->nfree = 0;
600	ds = txq->dma.dd_desc;
601	for (i = 0; i < malo_txbuf; i++, bf++, ds += MALO_TXDESC) {
602		bf->bf_desc = ds;
603		bf->bf_daddr = DS2PHYS(&txq->dma, ds);
604		error = bus_dmamap_create(sc->malo_dmat, BUS_DMA_NOWAIT,
605		    &bf->bf_dmamap);
606		if (error != 0) {
607			if_printf(ifp, "unable to create dmamap for tx "
608			    "buffer %u, error %u\n", i, error);
609			return error;
610		}
611		STAILQ_INSERT_TAIL(&txq->free, bf, bf_list);
612		txq->nfree++;
613	}
614
615	return 0;
616}
617
618static void
619malo_desc_cleanup(struct malo_softc *sc, struct malo_descdma *dd)
620{
621	bus_dmamap_unload(dd->dd_dmat, dd->dd_dmamap);
622	bus_dmamem_free(dd->dd_dmat, dd->dd_desc, dd->dd_dmamap);
623	bus_dma_tag_destroy(dd->dd_dmat);
624
625	memset(dd, 0, sizeof(*dd));
626}
627
628static void
629malo_rxdma_cleanup(struct malo_softc *sc)
630{
631	struct malo_rxbuf *bf;
632
633	STAILQ_FOREACH(bf, &sc->malo_rxbuf, bf_list) {
634		if (bf->bf_m != NULL) {
635			m_freem(bf->bf_m);
636			bf->bf_m = NULL;
637		}
638		if (bf->bf_dmamap != NULL) {
639			bus_dmamap_destroy(sc->malo_dmat, bf->bf_dmamap);
640			bf->bf_dmamap = NULL;
641		}
642	}
643	STAILQ_INIT(&sc->malo_rxbuf);
644	if (sc->malo_rxdma.dd_bufptr != NULL) {
645		free(sc->malo_rxdma.dd_bufptr, M_MALODEV);
646		sc->malo_rxdma.dd_bufptr = NULL;
647	}
648	if (sc->malo_rxdma.dd_desc_len != 0)
649		malo_desc_cleanup(sc, &sc->malo_rxdma);
650}
651
652static void
653malo_txdma_cleanup(struct malo_softc *sc, struct malo_txq *txq)
654{
655	struct malo_txbuf *bf;
656	struct ieee80211_node *ni;
657
658	STAILQ_FOREACH(bf, &txq->free, bf_list) {
659		if (bf->bf_m != NULL) {
660			m_freem(bf->bf_m);
661			bf->bf_m = NULL;
662		}
663		ni = bf->bf_node;
664		bf->bf_node = NULL;
665		if (ni != NULL) {
666			/*
667			 * Reclaim node reference.
668			 */
669			ieee80211_free_node(ni);
670		}
671		if (bf->bf_dmamap != NULL) {
672			bus_dmamap_destroy(sc->malo_dmat, bf->bf_dmamap);
673			bf->bf_dmamap = NULL;
674		}
675	}
676	STAILQ_INIT(&txq->free);
677	txq->nfree = 0;
678	if (txq->dma.dd_bufptr != NULL) {
679		free(txq->dma.dd_bufptr, M_MALODEV);
680		txq->dma.dd_bufptr = NULL;
681	}
682	if (txq->dma.dd_desc_len != 0)
683		malo_desc_cleanup(sc, &txq->dma);
684}
685
686static void
687malo_dma_cleanup(struct malo_softc *sc)
688{
689	int i;
690
691	for (i = 0; i < MALO_NUM_TX_QUEUES; i++)
692		malo_txdma_cleanup(sc, &sc->malo_txq[i]);
693
694	malo_rxdma_cleanup(sc);
695}
696
697static int
698malo_dma_setup(struct malo_softc *sc)
699{
700	int error, i;
701
702	/* rxdma initializing.  */
703	error = malo_rxdma_setup(sc);
704	if (error != 0)
705		return error;
706
707	/* NB: we just have 1 tx queue now.  */
708	for (i = 0; i < MALO_NUM_TX_QUEUES; i++) {
709		error = malo_txdma_setup(sc, &sc->malo_txq[i]);
710		if (error != 0) {
711			malo_dma_cleanup(sc);
712
713			return error;
714		}
715
716		malo_txq_init(sc, &sc->malo_txq[i], i);
717	}
718
719	return 0;
720}
721
722static void
723malo_hal_set_rxtxdma(struct malo_softc *sc)
724{
725	int i;
726
727	malo_bar0_write4(sc, sc->malo_hwspecs.rxdesc_read,
728	    sc->malo_hwdma.rxdesc_read);
729	malo_bar0_write4(sc, sc->malo_hwspecs.rxdesc_write,
730	    sc->malo_hwdma.rxdesc_read);
731
732	for (i = 0; i < MALO_NUM_TX_QUEUES; i++) {
733		malo_bar0_write4(sc,
734		    sc->malo_hwspecs.wcbbase[i], sc->malo_hwdma.wcbbase[i]);
735	}
736}
737
738/*
739 * Inform firmware of our tx/rx dma setup.  The BAR 0 writes below are
740 * for compatibility with older firmware.  For current firmware we send
741 * this information with a cmd block via malo_hal_sethwdma.
742 */
743static int
744malo_setup_hwdma(struct malo_softc *sc)
745{
746	int i;
747	struct malo_txq *txq;
748
749	sc->malo_hwdma.rxdesc_read = sc->malo_rxdma.dd_desc_paddr;
750
751	for (i = 0; i < MALO_NUM_TX_QUEUES; i++) {
752		txq = &sc->malo_txq[i];
753		sc->malo_hwdma.wcbbase[i] = txq->dma.dd_desc_paddr;
754	}
755	sc->malo_hwdma.maxnum_txwcb = malo_txbuf;
756	sc->malo_hwdma.maxnum_wcb = MALO_NUM_TX_QUEUES;
757
758	malo_hal_set_rxtxdma(sc);
759
760	return 0;
761}
762
763static void
764malo_txq_init(struct malo_softc *sc, struct malo_txq *txq, int qnum)
765{
766	struct malo_txbuf *bf, *bn;
767	struct malo_txdesc *ds;
768
769	MALO_TXQ_LOCK_INIT(sc, txq);
770	txq->qnum = qnum;
771	txq->txpri = 0;	/* XXX */
772
773	STAILQ_FOREACH(bf, &txq->free, bf_list) {
774		bf->bf_txq = txq;
775
776		ds = bf->bf_desc;
777		bn = STAILQ_NEXT(bf, bf_list);
778		if (bn == NULL)
779			bn = STAILQ_FIRST(&txq->free);
780		ds->physnext = htole32(bn->bf_daddr);
781	}
782	STAILQ_INIT(&txq->active);
783}
784
785/*
786 * Reclaim resources for a setup queue.
787 */
788static void
789malo_tx_cleanupq(struct malo_softc *sc, struct malo_txq *txq)
790{
791	/* XXX hal work? */
792	MALO_TXQ_LOCK_DESTROY(txq);
793}
794
795/*
796 * Allocate a tx buffer for sending a frame.
797 */
798static struct malo_txbuf *
799malo_getbuf(struct malo_softc *sc, struct malo_txq *txq)
800{
801	struct malo_txbuf *bf;
802
803	MALO_TXQ_LOCK(txq);
804	bf = STAILQ_FIRST(&txq->free);
805	if (bf != NULL) {
806		STAILQ_REMOVE_HEAD(&txq->free, bf_list);
807		txq->nfree--;
808	}
809	MALO_TXQ_UNLOCK(txq);
810	if (bf == NULL) {
811		DPRINTF(sc, MALO_DEBUG_XMIT,
812		    "%s: out of xmit buffers on q %d\n", __func__, txq->qnum);
813		sc->malo_stats.mst_tx_qstop++;
814	}
815	return bf;
816}
817
818static int
819malo_tx_dmasetup(struct malo_softc *sc, struct malo_txbuf *bf, struct mbuf *m0)
820{
821	struct mbuf *m;
822	int error;
823
824	/*
825	 * Load the DMA map so any coalescing is done.  This also calculates
826	 * the number of descriptors we need.
827	 */
828	error = bus_dmamap_load_mbuf_sg(sc->malo_dmat, bf->bf_dmamap, m0,
829				     bf->bf_segs, &bf->bf_nseg,
830				     BUS_DMA_NOWAIT);
831	if (error == EFBIG) {
832		/* XXX packet requires too many descriptors */
833		bf->bf_nseg = MALO_TXDESC + 1;
834	} else if (error != 0) {
835		sc->malo_stats.mst_tx_busdma++;
836		m_freem(m0);
837		return error;
838	}
839	/*
840	 * Discard null packets and check for packets that require too many
841	 * TX descriptors.  We try to convert the latter to a cluster.
842	 */
843	if (error == EFBIG) {		/* too many desc's, linearize */
844		sc->malo_stats.mst_tx_linear++;
845		m = m_defrag(m0, M_NOWAIT);
846		if (m == NULL) {
847			m_freem(m0);
848			sc->malo_stats.mst_tx_nombuf++;
849			return ENOMEM;
850		}
851		m0 = m;
852		error = bus_dmamap_load_mbuf_sg(sc->malo_dmat, bf->bf_dmamap, m0,
853					     bf->bf_segs, &bf->bf_nseg,
854					     BUS_DMA_NOWAIT);
855		if (error != 0) {
856			sc->malo_stats.mst_tx_busdma++;
857			m_freem(m0);
858			return error;
859		}
860		KASSERT(bf->bf_nseg <= MALO_TXDESC,
861		    ("too many segments after defrag; nseg %u", bf->bf_nseg));
862	} else if (bf->bf_nseg == 0) {		/* null packet, discard */
863		sc->malo_stats.mst_tx_nodata++;
864		m_freem(m0);
865		return EIO;
866	}
867	DPRINTF(sc, MALO_DEBUG_XMIT, "%s: m %p len %u\n",
868		__func__, m0, m0->m_pkthdr.len);
869	bus_dmamap_sync(sc->malo_dmat, bf->bf_dmamap, BUS_DMASYNC_PREWRITE);
870	bf->bf_m = m0;
871
872	return 0;
873}
874
875#ifdef MALO_DEBUG
876static void
877malo_printrxbuf(const struct malo_rxbuf *bf, u_int ix)
878{
879	const struct malo_rxdesc *ds = bf->bf_desc;
880	uint32_t status = le32toh(ds->status);
881
882	printf("R[%2u] (DS.V:%p DS.P:0x%jx) NEXT:%08x DATA:%08x RC:%02x%s\n"
883	    "      STAT:%02x LEN:%04x SNR:%02x NF:%02x CHAN:%02x"
884	    " RATE:%02x QOS:%04x\n", ix, ds, (uintmax_t)bf->bf_daddr,
885	    le32toh(ds->physnext), le32toh(ds->physbuffdata),
886	    ds->rxcontrol,
887	    ds->rxcontrol != MALO_RXD_CTRL_DRIVER_OWN ?
888	        "" : (status & MALO_RXD_STATUS_OK) ? " *" : " !",
889	    ds->status, le16toh(ds->pktlen), ds->snr, ds->nf, ds->channel,
890	    ds->rate, le16toh(ds->qosctrl));
891}
892
893static void
894malo_printtxbuf(const struct malo_txbuf *bf, u_int qnum, u_int ix)
895{
896	const struct malo_txdesc *ds = bf->bf_desc;
897	uint32_t status = le32toh(ds->status);
898
899	printf("Q%u[%3u]", qnum, ix);
900	printf(" (DS.V:%p DS.P:0x%jx)\n", ds, (uintmax_t)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
924static __inline void
925malo_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
935static int
936malo_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 */
952static int
953malo_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 */
1047static void
1048malo_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
1070static int
1071malo_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
1255static void
1256malo_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
1327static void
1328malo_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
1349static int
1350malo_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
1377static __inline struct mbuf *
1378malo_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
1405static int
1406malo_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 */
1443static int
1444malo_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
1482static void
1483malo_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
1535static void
1536malo_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 */
1557static void
1558malo_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
1593all:
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
1601static int
1602malo_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
1621static void
1622malo_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
1671static void
1672malo_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
1708static int
1709malo_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 */
1767static void
1768malo_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
1794static int
1795malo_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
1837static int
1838malo_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
1901static void
1902malo_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
1915static void
1916malo_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 */
1937static void
1938malo_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 */
1953static int
1954malo_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
1989static void
1990malo_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
1998static void
1999malo_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
2007static void
2008malo_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
2016static void
2017malo_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);
2171rx_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
2186static void
2187malo_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 */
2199static void
2200malo_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
2208int
2209malo_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
2250void
2251malo_shutdown(struct malo_softc *sc)
2252{
2253	malo_stop(sc->malo_ifp, 1);
2254}
2255
2256void
2257malo_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
2267void
2268malo_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}
2278