if_uath.c revision 191746
1/*-
2 * Copyright (c) 2006 Sam Leffler, Errno Consulting
3 * Copyright (c) 2008-2009 Weongyo Jeong <weongyo@freebsd.org>
4 * All rights reserved.
5 *
6 * Redistribution and use in source and binary forms, with or without
7 * modification, are permitted provided that the following conditions
8 * are met:
9 * 1. Redistributions of source code must retain the above copyright
10 *    notice, this list of conditions and the following disclaimer,
11 *    without modification.
12 * 2. Redistributions in binary form must reproduce at minimum a disclaimer
13 *    similar to the "NO WARRANTY" disclaimer below ("Disclaimer") and any
14 *    redistribution must be conditioned upon including a substantially
15 *    similar Disclaimer requirement for further binary redistribution.
16 *
17 * NO WARRANTY
18 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20 * LIMITED TO, THE IMPLIED WARRANTIES OF NONINFRINGEMENT, MERCHANTIBILITY
21 * AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
22 * THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR SPECIAL, EXEMPLARY,
23 * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
24 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
25 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER
26 * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
27 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
28 * THE POSSIBILITY OF SUCH DAMAGES.
29 */
30
31/*
32 * This driver is distantly derived from a driver of the same name
33 * by Damien Bergamini.  The original copyright is included below:
34 *
35 * Copyright (c) 2006
36 *	Damien Bergamini <damien.bergamini@free.fr>
37 *
38 * Permission to use, copy, modify, and distribute this software for any
39 * purpose with or without fee is hereby granted, provided that the above
40 * copyright notice and this permission notice appear in all copies.
41 *
42 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
43 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
44 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
45 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
46 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
47 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
48 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
49 */
50
51#include <sys/cdefs.h>
52__FBSDID("$FreeBSD: head/sys/dev/usb/wlan/if_uath.c 191746 2009-05-02 15:14:18Z thompsa $");
53
54/*-
55 * Driver for Atheros AR5523 USB parts.
56 *
57 * The driver requires firmware to be loaded into the device.  This
58 * is done on device discovery from a user application (uathload)
59 * that is launched by devd when a device with suitable product ID
60 * is recognized.  Once firmware has been loaded the device will
61 * reset the USB port and re-attach with the original product ID+1
62 * and this driver will be attached.  The firmware is licensed for
63 * general use (royalty free) and may be incorporated in products.
64 * Note that the firmware normally packaged with the NDIS drivers
65 * for these devices does not work in this way and so does not work
66 * with this driver.
67 */
68#include <sys/param.h>
69#include <sys/sockio.h>
70#include <sys/sysctl.h>
71#include <sys/lock.h>
72#include <sys/mutex.h>
73#include <sys/mbuf.h>
74#include <sys/kernel.h>
75#include <sys/socket.h>
76#include <sys/systm.h>
77#include <sys/malloc.h>
78#include <sys/module.h>
79#include <sys/bus.h>
80#include <sys/endian.h>
81#include <sys/kdb.h>
82
83#include <machine/bus.h>
84#include <machine/resource.h>
85#include <sys/rman.h>
86
87#include <net/bpf.h>
88#include <net/if.h>
89#include <net/if_arp.h>
90#include <net/ethernet.h>
91#include <net/if_dl.h>
92#include <net/if_media.h>
93#include <net/if_types.h>
94
95#ifdef INET
96#include <netinet/in.h>
97#include <netinet/in_systm.h>
98#include <netinet/in_var.h>
99#include <netinet/if_ether.h>
100#include <netinet/ip.h>
101#endif
102
103#include <net80211/ieee80211_var.h>
104#include <net80211/ieee80211_regdomain.h>
105#include <net80211/ieee80211_radiotap.h>
106
107#include <dev/usb/usb.h>
108#include <dev/usb/usb_core.h>
109#include <dev/usb/usb_busdma.h>
110#include <dev/usb/usb_debug.h>
111#include <dev/usb/usb_error.h>
112#include <dev/usb/usb_lookup.h>
113#include <dev/usb/usb_util.h>
114#include "usbdevs.h"
115
116#include <dev/usb/wlan/if_uathreg.h>
117#include <dev/usb/wlan/if_uathvar.h>
118
119SYSCTL_NODE(_hw_usb2, OID_AUTO, uath, CTLFLAG_RW, 0, "USB Atheros");
120
121static	int uath_countrycode = CTRY_DEFAULT;	/* country code */
122SYSCTL_INT(_hw_usb2_uath, OID_AUTO, countrycode, CTLFLAG_RW, &uath_countrycode,
123    0, "country code");
124TUNABLE_INT("hw.usb2.uath.countrycode", &uath_countrycode);
125static	int uath_regdomain = 0;			/* regulatory domain */
126SYSCTL_INT(_hw_usb2_uath, OID_AUTO, regdomain, CTLFLAG_RD, &uath_regdomain,
127    0, "regulatory domain");
128
129#ifdef UATH_DEBUG
130int uath_debug = 0;
131SYSCTL_INT(_hw_usb2_uath, OID_AUTO, debug, CTLFLAG_RW, &uath_debug, 0,
132    "uath debug level");
133TUNABLE_INT("hw.usb.uath.debug", &uath_debug);
134enum {
135	UATH_DEBUG_XMIT		= 0x00000001,	/* basic xmit operation */
136	UATH_DEBUG_XMIT_DUMP	= 0x00000002,	/* xmit dump */
137	UATH_DEBUG_RECV		= 0x00000004,	/* basic recv operation */
138	UATH_DEBUG_TX_PROC	= 0x00000008,	/* tx ISR proc */
139	UATH_DEBUG_RX_PROC	= 0x00000010,	/* rx ISR proc */
140	UATH_DEBUG_RECV_ALL	= 0x00000020,	/* trace all frames (beacons) */
141	UATH_DEBUG_INIT		= 0x00000040,	/* initialization of dev */
142	UATH_DEBUG_DEVCAP	= 0x00000080,	/* dev caps */
143	UATH_DEBUG_CMDS		= 0x00000100,	/* commands */
144	UATH_DEBUG_CMDS_DUMP	= 0x00000200,	/* command buffer dump */
145	UATH_DEBUG_RESET	= 0x00000400,	/* reset processing */
146	UATH_DEBUG_STATE	= 0x00000800,	/* 802.11 state transitions */
147	UATH_DEBUG_MULTICAST	= 0x00001000,	/* multicast */
148	UATH_DEBUG_WME		= 0x00002000,	/* WME */
149	UATH_DEBUG_CHANNEL	= 0x00004000,	/* channel */
150	UATH_DEBUG_RATES	= 0x00008000,	/* rates */
151	UATH_DEBUG_CRYPTO	= 0x00010000,	/* crypto */
152	UATH_DEBUG_LED		= 0x00020000,	/* LED */
153	UATH_DEBUG_ANY		= 0xffffffff
154};
155#define	DPRINTF(sc, m, fmt, ...) do {				\
156	if (sc->sc_debug & (m))					\
157		printf(fmt, __VA_ARGS__);			\
158} while (0)
159#else
160#define	DPRINTF(sc, m, fmt, ...) do {				\
161	(void) sc;						\
162} while (0)
163#endif
164
165/* unaligned little endian access */
166#define LE_READ_2(p)							\
167	((u_int16_t)							\
168	 ((((u_int8_t *)(p))[0]      ) | (((u_int8_t *)(p))[1] <<  8)))
169#define LE_READ_4(p)							\
170	((u_int32_t)							\
171	 ((((u_int8_t *)(p))[0]      ) | (((u_int8_t *)(p))[1] <<  8) |	\
172	  (((u_int8_t *)(p))[2] << 16) | (((u_int8_t *)(p))[3] << 24)))
173
174/* recognized device vendors/products */
175static const struct usb2_device_id uath_devs[] = {
176#define	UATH_DEV(v,p) { USB_VP(USB_VENDOR_##v, USB_PRODUCT_##v##_##p) }
177	UATH_DEV(ATHEROS,		AR5523),
178	UATH_DEV(ATHEROS2,		AR5523_1),
179	UATH_DEV(ATHEROS2,		AR5523_2),
180	UATH_DEV(ATHEROS2,		AR5523_3),
181	UATH_DEV(CONCEPTRONIC,		AR5523_1),
182	UATH_DEV(CONCEPTRONIC,		AR5523_2),
183	UATH_DEV(DLINK,			DWLAG122),
184	UATH_DEV(DLINK,			DWLAG132),
185	UATH_DEV(DLINK,			DWLG132),
186	UATH_DEV(GIGASET,		AR5523),
187	UATH_DEV(GIGASET,		SMCWUSBTG),
188	UATH_DEV(GLOBALSUN,		AR5523_1),
189	UATH_DEV(GLOBALSUN,		AR5523_2),
190	UATH_DEV(NETGEAR,		WG111U),
191	UATH_DEV(NETGEAR3,		WG111T),
192	UATH_DEV(NETGEAR3,		WPN111),
193	UATH_DEV(UMEDIA,		TEW444UBEU),
194	UATH_DEV(UMEDIA,		AR5523_2),
195	UATH_DEV(WISTRONNEWEB,		AR5523_1),
196	UATH_DEV(WISTRONNEWEB,		AR5523_2),
197	UATH_DEV(ZCOM,			AR5523)
198#undef UATH_DEV
199};
200
201static usb2_callback_t uath_intr_rx_callback;
202static usb2_callback_t uath_intr_tx_callback;
203static usb2_callback_t uath_bulk_rx_callback;
204static usb2_callback_t uath_bulk_tx_callback;
205
206static const struct usb2_config uath_usbconfig[UATH_N_XFERS] = {
207	[UATH_INTR_RX] = {
208		.type = UE_BULK,
209		.endpoint = 0x1,
210		.direction = UE_DIR_IN,
211		.bufsize = UATH_MAX_CMDSZ,
212		.flags = {
213			.pipe_bof = 1,
214			.short_xfer_ok = 1
215		},
216		.callback = uath_intr_rx_callback
217	},
218	[UATH_INTR_TX] = {
219		.type = UE_BULK,
220		.endpoint = 0x1,
221		.direction = UE_DIR_OUT,
222		.bufsize = UATH_MAX_CMDSZ,
223		.flags = {
224			.ext_buffer = 1,
225			.force_short_xfer = 1,
226			.pipe_bof = 1,
227		},
228		.callback = uath_intr_tx_callback,
229		.timeout = UATH_CMD_TIMEOUT
230	},
231	[UATH_BULK_RX] = {
232		.type = UE_BULK,
233		.endpoint = 0x2,
234		.direction = UE_DIR_IN,
235		.bufsize = MCLBYTES,
236		.flags = {
237			.ext_buffer = 1,
238			.pipe_bof = 1,
239			.short_xfer_ok = 1
240		},
241		.callback = uath_bulk_rx_callback
242	},
243	[UATH_BULK_TX] = {
244		.type = UE_BULK,
245		.endpoint = 0x2,
246		.direction = UE_DIR_OUT,
247		.bufsize = UATH_MAX_TXBUFSZ,
248		.flags = {
249			.ext_buffer = 1,
250			.force_short_xfer = 1,
251			.pipe_bof = 1
252		},
253		.callback = uath_bulk_tx_callback,
254		.timeout = UATH_DATA_TIMEOUT
255	}
256};
257
258static struct ieee80211vap *uath_vap_create(struct ieee80211com *,
259		    const char name[IFNAMSIZ], int unit, int opmode,
260		    int flags, const uint8_t bssid[IEEE80211_ADDR_LEN],
261		    const uint8_t mac[IEEE80211_ADDR_LEN]);
262static void	uath_vap_delete(struct ieee80211vap *);
263static int	uath_alloc_cmd_list(struct uath_softc *, struct uath_cmd [],
264		    int, int);
265static void	uath_free_cmd_list(struct uath_softc *, struct uath_cmd [],
266		    int);
267static int	uath_host_available(struct uath_softc *);
268static int	uath_get_capability(struct uath_softc *, uint32_t, uint32_t *);
269static int	uath_get_devcap(struct uath_softc *);
270static struct uath_cmd *
271		uath_get_cmdbuf(struct uath_softc *);
272static int	uath_cmd_read(struct uath_softc *, uint32_t, const void *,
273		    int, void *, int, int);
274static int	uath_cmd_write(struct uath_softc *, uint32_t, const void *,
275		    int, int);
276static void	uath_stat(void *);
277#ifdef UATH_DEBUG
278static void	uath_dump_cmd(const uint8_t *, int, char);
279static const char *
280		uath_codename(int);
281#endif
282static int	uath_get_devstatus(struct uath_softc *,
283		    uint8_t macaddr[IEEE80211_ADDR_LEN]);
284static int	uath_get_status(struct uath_softc *, uint32_t, void *, int);
285static int	uath_alloc_rx_data_list(struct uath_softc *);
286static int	uath_alloc_tx_data_list(struct uath_softc *);
287static void	uath_free_rx_data_list(struct uath_softc *);
288static void	uath_free_tx_data_list(struct uath_softc *);
289static int	uath_init_locked(void *);
290static void	uath_init(void *);
291static void	uath_stop_locked(struct ifnet *);
292static void	uath_stop(struct ifnet *);
293static int	uath_ioctl(struct ifnet *, u_long, caddr_t);
294static void	uath_start(struct ifnet *);
295static int	uath_raw_xmit(struct ieee80211_node *, struct mbuf *,
296		    const struct ieee80211_bpf_params *);
297static void	uath_scan_start(struct ieee80211com *);
298static void	uath_scan_end(struct ieee80211com *);
299static void	uath_set_channel(struct ieee80211com *);
300static void	uath_update_mcast(struct ifnet *);
301static void	uath_update_promisc(struct ifnet *);
302static int	uath_config(struct uath_softc *, uint32_t, uint32_t);
303static int	uath_config_multi(struct uath_softc *, uint32_t, const void *,
304		    int);
305static int	uath_switch_channel(struct uath_softc *,
306		    struct ieee80211_channel *);
307static int	uath_set_rxfilter(struct uath_softc *, uint32_t, uint32_t);
308static void	uath_watchdog(void *);
309static void	uath_abort_xfers(struct uath_softc *);
310static int	uath_dataflush(struct uath_softc *);
311static int	uath_cmdflush(struct uath_softc *);
312static int	uath_flush(struct uath_softc *);
313static int	uath_set_ledstate(struct uath_softc *, int);
314static int	uath_set_chan(struct uath_softc *, struct ieee80211_channel *);
315static int	uath_reset_tx_queues(struct uath_softc *);
316static int	uath_wme_init(struct uath_softc *);
317static struct uath_data *
318		uath_getbuf(struct uath_softc *);
319static int	uath_newstate(struct ieee80211vap *, enum ieee80211_state,
320		    int);
321static int	uath_set_key(struct uath_softc *,
322		    const struct ieee80211_key *, int);
323static int	uath_set_keys(struct uath_softc *, struct ieee80211vap *);
324static void	uath_sysctl_node(struct uath_softc *);
325
326static int
327uath_match(device_t dev)
328{
329	struct usb2_attach_arg *uaa = device_get_ivars(dev);
330
331	if (uaa->usb2_mode != USB_MODE_HOST)
332		return (ENXIO);
333	if (uaa->info.bConfigIndex != UATH_CONFIG_INDEX)
334		return (ENXIO);
335	if (uaa->info.bIfaceIndex != UATH_IFACE_INDEX)
336		return (ENXIO);
337
338	return (usb2_lookup_id_by_uaa(uath_devs, sizeof(uath_devs), uaa));
339}
340
341static int
342uath_attach(device_t dev)
343{
344	struct uath_softc *sc = device_get_softc(dev);
345	struct usb2_attach_arg *uaa = device_get_ivars(dev);
346	struct ieee80211com *ic;
347	struct ifnet *ifp;
348	uint8_t bands, iface_index = UATH_IFACE_INDEX;		/* XXX */
349	usb2_error_t error;
350	uint8_t macaddr[IEEE80211_ADDR_LEN];
351
352	sc->sc_dev = dev;
353	sc->sc_udev = uaa->device;
354#ifdef UATH_DEBUG
355	sc->sc_debug = uath_debug;
356#endif
357
358	/*
359	 * Only post-firmware devices here.
360	 */
361	mtx_init(&sc->sc_mtx, device_get_nameunit(sc->sc_dev), MTX_NETWORK_LOCK,
362	    MTX_DEF);
363	callout_init(&sc->stat_ch, 0);
364	callout_init_mtx(&sc->watchdog_ch, &sc->sc_mtx, 0);
365
366	/*
367	 * Allocate xfers for firmware commands.
368	 */
369	error = uath_alloc_cmd_list(sc, sc->sc_cmd, UATH_CMD_LIST_COUNT,
370	    UATH_MAX_CMDSZ);
371	if (error != 0) {
372		device_printf(sc->sc_dev,
373		    "could not allocate Tx command list\n");
374		goto fail;
375	}
376
377	error = usb2_transfer_setup(uaa->device, &iface_index, sc->sc_xfer,
378	    uath_usbconfig, UATH_N_XFERS, sc, &sc->sc_mtx);
379	if (error) {
380		device_printf(dev, "could not allocate USB transfers, "
381		    "err=%s\n", usb2_errstr(error));
382		goto fail1;
383	}
384
385	/*
386	 * We're now ready to send+receive firmware commands.
387	 */
388	UATH_LOCK(sc);
389	error = uath_host_available(sc);
390	if (error != 0) {
391		device_printf(sc->sc_dev, "could not initialize adapter\n");
392		goto fail3;
393	}
394	error = uath_get_devcap(sc);
395	if (error != 0) {
396		device_printf(sc->sc_dev,
397		    "could not get device capabilities\n");
398		goto fail3;
399	}
400	UATH_UNLOCK(sc);
401
402	/* Create device sysctl node. */
403	uath_sysctl_node(sc);
404
405	ifp = sc->sc_ifp = if_alloc(IFT_IEEE80211);
406	if (ifp == NULL) {
407		device_printf(sc->sc_dev, "can not allocate ifnet\n");
408		error = ENXIO;
409		goto fail2;
410	}
411
412	UATH_LOCK(sc);
413	error = uath_get_devstatus(sc, macaddr);
414	if (error != 0) {
415		device_printf(sc->sc_dev, "could not get device status\n");
416		goto fail4;
417	}
418
419	/*
420	 * Allocate xfers for Rx/Tx data pipes.
421	 */
422	error = uath_alloc_rx_data_list(sc);
423	if (error != 0) {
424		device_printf(sc->sc_dev, "could not allocate Rx data list\n");
425		goto fail4;
426	}
427	error = uath_alloc_tx_data_list(sc);
428	if (error != 0) {
429		device_printf(sc->sc_dev, "could not allocate Tx data list\n");
430		goto fail4;
431	}
432	UATH_UNLOCK(sc);
433
434	ifp->if_softc = sc;
435	if_initname(ifp, "uath", device_get_unit(sc->sc_dev));
436	ifp->if_flags = IFF_BROADCAST | IFF_SIMPLEX | IFF_MULTICAST;
437	ifp->if_init = uath_init;
438	ifp->if_ioctl = uath_ioctl;
439	ifp->if_start = uath_start;
440	/* XXX UATH_TX_DATA_LIST_COUNT */
441	IFQ_SET_MAXLEN(&ifp->if_snd, IFQ_MAXLEN);
442	ifp->if_snd.ifq_drv_maxlen = IFQ_MAXLEN;
443	IFQ_SET_READY(&ifp->if_snd);
444
445	ic = ifp->if_l2com;
446	ic->ic_ifp = ifp;
447	ic->ic_phytype = IEEE80211_T_OFDM;	/* not only, but not used */
448	ic->ic_opmode = IEEE80211_M_STA;	/* default to BSS mode */
449
450	/* set device capabilities */
451	ic->ic_caps =
452	    IEEE80211_C_STA |		/* station mode */
453	    IEEE80211_C_MONITOR |	/* monitor mode supported */
454	    IEEE80211_C_TXPMGT |	/* tx power management */
455	    IEEE80211_C_SHPREAMBLE |	/* short preamble supported */
456	    IEEE80211_C_SHSLOT |	/* short slot time supported */
457	    IEEE80211_C_WPA |		/* 802.11i */
458	    IEEE80211_C_BGSCAN |	/* capable of bg scanning */
459	    IEEE80211_C_TXFRAG;		/* handle tx frags */
460
461	/* put a regulatory domain to reveal informations.  */
462	uath_regdomain = sc->sc_devcap.regDomain;
463
464	bands = 0;
465	setbit(&bands, IEEE80211_MODE_11B);
466	setbit(&bands, IEEE80211_MODE_11G);
467	if ((sc->sc_devcap.analog5GhzRevision & 0xf0) == 0x30)
468		setbit(&bands, IEEE80211_MODE_11A);
469	/* XXX turbo */
470	ieee80211_init_channels(ic, NULL, &bands);
471
472	ieee80211_ifattach(ic, macaddr);
473	ic->ic_raw_xmit = uath_raw_xmit;
474	ic->ic_scan_start = uath_scan_start;
475	ic->ic_scan_end = uath_scan_end;
476	ic->ic_set_channel = uath_set_channel;
477
478	ic->ic_vap_create = uath_vap_create;
479	ic->ic_vap_delete = uath_vap_delete;
480	ic->ic_update_mcast = uath_update_mcast;
481	ic->ic_update_promisc = uath_update_promisc;
482
483	bpfattach(ifp, DLT_IEEE802_11_RADIO,
484	    sizeof (struct ieee80211_frame) + sizeof(sc->sc_txtap));
485
486	sc->sc_rxtap_len = sizeof sc->sc_rxtap;
487	sc->sc_rxtap.wr_ihdr.it_len = htole16(sc->sc_rxtap_len);
488	sc->sc_rxtap.wr_ihdr.it_present = htole32(UATH_RX_RADIOTAP_PRESENT);
489
490	sc->sc_txtap_len = sizeof sc->sc_txtap;
491	sc->sc_txtap.wt_ihdr.it_len = htole16(sc->sc_txtap_len);
492	sc->sc_txtap.wt_ihdr.it_present = htole32(UATH_TX_RADIOTAP_PRESENT);
493
494	if (bootverbose)
495		ieee80211_announce(ic);
496
497	return (0);
498
499fail4:	if_free(ifp);
500fail3:	UATH_UNLOCK(sc);
501fail2:	usb2_transfer_unsetup(sc->sc_xfer, UATH_N_XFERS);
502fail1:	uath_free_cmd_list(sc, sc->sc_cmd, UATH_CMD_LIST_COUNT);
503fail:
504	return (error);
505}
506
507static int
508uath_detach(device_t dev)
509{
510	struct uath_softc *sc = device_get_softc(dev);
511	struct ifnet *ifp = sc->sc_ifp;
512	struct ieee80211com *ic = ifp->if_l2com;
513
514	if (!device_is_attached(dev))
515		return (0);
516
517	sc->sc_flags |= UATH_FLAG_INVALID;
518	uath_stop(ifp);
519	ieee80211_ifdetach(ic);
520
521	callout_drain(&sc->stat_ch);
522	callout_drain(&sc->watchdog_ch);
523
524	usb2_transfer_unsetup(sc->sc_xfer, UATH_N_XFERS);
525
526	/* free buffers */
527	UATH_LOCK(sc);
528	uath_free_rx_data_list(sc);
529	uath_free_tx_data_list(sc);
530	uath_free_cmd_list(sc, sc->sc_cmd, UATH_CMD_LIST_COUNT);
531	UATH_UNLOCK(sc);
532
533	bpfdetach(ifp);
534	if_free(ifp);
535	mtx_destroy(&sc->sc_mtx);
536	return (0);
537}
538
539static void
540uath_free_cmd_list(struct uath_softc *sc, struct uath_cmd cmds[], int ncmd)
541{
542	int i;
543
544	for (i = 0; i < ncmd; i++)
545		if (cmds[i].buf != NULL)
546			free(cmds[i].buf, M_USBDEV);
547}
548
549static int
550uath_alloc_cmd_list(struct uath_softc *sc, struct uath_cmd cmds[],
551	int ncmd, int maxsz)
552{
553	int i, error;
554
555	STAILQ_INIT(&sc->sc_cmd_active);
556	STAILQ_INIT(&sc->sc_cmd_pending);
557	STAILQ_INIT(&sc->sc_cmd_waiting);
558	STAILQ_INIT(&sc->sc_cmd_inactive);
559
560	for (i = 0; i < ncmd; i++) {
561		struct uath_cmd *cmd = &cmds[i];
562
563		cmd->sc = sc;	/* backpointer for callbacks */
564		cmd->msgid = i;
565		cmd->buf = malloc(maxsz, M_USBDEV, M_NOWAIT);
566		if (cmd->buf == NULL) {
567			device_printf(sc->sc_dev,
568			    "could not allocate xfer buffer\n");
569			error = ENOMEM;
570			goto fail;
571		}
572		STAILQ_INSERT_TAIL(&sc->sc_cmd_inactive, cmd, next);
573		UATH_STAT_INC(sc, st_cmd_inactive);
574	}
575	return (0);
576
577fail:	uath_free_cmd_list(sc, cmds, ncmd);
578	return (error);
579}
580
581static int
582uath_host_available(struct uath_softc *sc)
583{
584	struct uath_cmd_host_available setup;
585
586	UATH_ASSERT_LOCKED(sc);
587
588	/* inform target the host is available */
589	setup.sw_ver_major = htobe32(ATH_SW_VER_MAJOR);
590	setup.sw_ver_minor = htobe32(ATH_SW_VER_MINOR);
591	setup.sw_ver_patch = htobe32(ATH_SW_VER_PATCH);
592	setup.sw_ver_build = htobe32(ATH_SW_VER_BUILD);
593	return uath_cmd_read(sc, WDCMSG_HOST_AVAILABLE,
594		&setup, sizeof setup, NULL, 0, 0);
595}
596
597#ifdef UATH_DEBUG
598static void
599uath_dump_cmd(const uint8_t *buf, int len, char prefix)
600{
601	const char *sep = "";
602	int i;
603
604	for (i = 0; i < len; i++) {
605		if ((i % 16) == 0) {
606			printf("%s%c ", sep, prefix);
607			sep = "\n";
608		}
609		else if ((i % 4) == 0)
610			printf(" ");
611		printf("%02x", buf[i]);
612	}
613	printf("\n");
614}
615
616static const char *
617uath_codename(int code)
618{
619#define	N(a)	(sizeof(a)/sizeof(a[0]))
620	static const char *names[] = {
621	    "0x00",
622	    "HOST_AVAILABLE",
623	    "BIND",
624	    "TARGET_RESET",
625	    "TARGET_GET_CAPABILITY",
626	    "TARGET_SET_CONFIG",
627	    "TARGET_GET_STATUS",
628	    "TARGET_GET_STATS",
629	    "TARGET_START",
630	    "TARGET_STOP",
631	    "TARGET_ENABLE",
632	    "TARGET_DISABLE",
633	    "CREATE_CONNECTION",
634	    "UPDATE_CONNECT_ATTR",
635	    "DELETE_CONNECT",
636	    "SEND",
637	    "FLUSH",
638	    "STATS_UPDATE",
639	    "BMISS",
640	    "DEVICE_AVAIL",
641	    "SEND_COMPLETE",
642	    "DATA_AVAIL",
643	    "SET_PWR_MODE",
644	    "BMISS_ACK",
645	    "SET_LED_STEADY",
646	    "SET_LED_BLINK",
647	    "SETUP_BEACON_DESC",
648	    "BEACON_INIT",
649	    "RESET_KEY_CACHE",
650	    "RESET_KEY_CACHE_ENTRY",
651	    "SET_KEY_CACHE_ENTRY",
652	    "SET_DECOMP_MASK",
653	    "SET_REGULATORY_DOMAIN",
654	    "SET_LED_STATE",
655	    "WRITE_ASSOCID",
656	    "SET_STA_BEACON_TIMERS",
657	    "GET_TSF",
658	    "RESET_TSF",
659	    "SET_ADHOC_MODE",
660	    "SET_BASIC_RATE",
661	    "MIB_CONTROL",
662	    "GET_CHANNEL_DATA",
663	    "GET_CUR_RSSI",
664	    "SET_ANTENNA_SWITCH",
665	    "0x2c", "0x2d", "0x2e",
666	    "USE_SHORT_SLOT_TIME",
667	    "SET_POWER_MODE",
668	    "SETUP_PSPOLL_DESC",
669	    "SET_RX_MULTICAST_FILTER",
670	    "RX_FILTER",
671	    "PER_CALIBRATION",
672	    "RESET",
673	    "DISABLE",
674	    "PHY_DISABLE",
675	    "SET_TX_POWER_LIMIT",
676	    "SET_TX_QUEUE_PARAMS",
677	    "SETUP_TX_QUEUE",
678	    "RELEASE_TX_QUEUE",
679	};
680	static char buf[8];
681
682	if (code < N(names))
683		return names[code];
684	if (code == WDCMSG_SET_DEFAULT_KEY)
685		return "SET_DEFAULT_KEY";
686	snprintf(buf, sizeof(buf), "0x%02x", code);
687	return buf;
688#undef N
689}
690#endif
691
692/*
693 * Low-level function to send read or write commands to the firmware.
694 */
695static int
696uath_cmdsend(struct uath_softc *sc, uint32_t code, const void *idata, int ilen,
697    void *odata, int olen, int flags)
698{
699	struct uath_cmd_hdr *hdr;
700	struct uath_cmd *cmd;
701	int error;
702
703	UATH_ASSERT_LOCKED(sc);
704
705	/* grab a xfer */
706	cmd = uath_get_cmdbuf(sc);
707	if (cmd == NULL) {
708		device_printf(sc->sc_dev, "%s: empty inactive queue\n",
709		    __func__);
710		return (ENOBUFS);
711	}
712	cmd->flags = flags;
713	/* always bulk-out a multiple of 4 bytes */
714	cmd->buflen = roundup2(sizeof(struct uath_cmd_hdr) + ilen, 4);
715
716	hdr = (struct uath_cmd_hdr *)cmd->buf;
717	bzero(hdr, sizeof (struct uath_cmd_hdr));	/* XXX not needed */
718	hdr->len   = htobe32(cmd->buflen);
719	hdr->code  = htobe32(code);
720	hdr->msgid = cmd->msgid;	/* don't care about endianness */
721	hdr->magic = htobe32((cmd->flags & UATH_CMD_FLAG_MAGIC) ? 1 << 24 : 0);
722	bcopy(idata, (uint8_t *)(hdr + 1), ilen);
723
724#ifdef UATH_DEBUG
725	if (sc->sc_debug & UATH_DEBUG_CMDS) {
726		printf("%s: send  %s [flags 0x%x] olen %d\n",
727		    __func__, uath_codename(code), cmd->flags, olen);
728		if (sc->sc_debug & UATH_DEBUG_CMDS_DUMP)
729			uath_dump_cmd(cmd->buf, cmd->buflen, '+');
730	}
731#endif
732	cmd->odata = odata;
733	KASSERT(odata == NULL ||
734	    olen < UATH_MAX_CMDSZ - sizeof(*hdr) + sizeof(uint32_t),
735	    ("odata %p olen %u", odata, olen));
736	cmd->olen = olen;
737
738	STAILQ_INSERT_TAIL(&sc->sc_cmd_pending, cmd, next);
739	UATH_STAT_INC(sc, st_cmd_pending);
740	usb2_transfer_start(sc->sc_xfer[UATH_INTR_TX]);
741
742	if (cmd->flags & UATH_CMD_FLAG_READ) {
743		usb2_transfer_start(sc->sc_xfer[UATH_INTR_RX]);
744
745		/* wait at most two seconds for command reply */
746		error = mtx_sleep(cmd, &sc->sc_mtx, 0, "uathcmd", 2 * hz);
747		cmd->odata = NULL;	/* in case reply comes too late */
748		if (error != 0) {
749			device_printf(sc->sc_dev, "timeout waiting for reply "
750			    "to cmd 0x%x (%u)\n", code, code);
751		} else if (cmd->olen != olen) {
752			device_printf(sc->sc_dev, "unexpected reply data count "
753			    "to cmd 0x%x (%u), got %u, expected %u\n",
754			    code, code, cmd->olen, olen);
755			error = EINVAL;
756		}
757		return (error);
758	}
759	return (0);
760}
761
762static int
763uath_cmd_read(struct uath_softc *sc, uint32_t code, const void *idata,
764    int ilen, void *odata, int olen, int flags)
765{
766
767	flags |= UATH_CMD_FLAG_READ;
768	return uath_cmdsend(sc, code, idata, ilen, odata, olen, flags);
769}
770
771static int
772uath_cmd_write(struct uath_softc *sc, uint32_t code, const void *data, int len,
773    int flags)
774{
775
776	flags &= ~UATH_CMD_FLAG_READ;
777	return uath_cmdsend(sc, code, data, len, NULL, 0, flags);
778}
779
780static struct uath_cmd *
781uath_get_cmdbuf(struct uath_softc *sc)
782{
783	struct uath_cmd *uc;
784
785	UATH_ASSERT_LOCKED(sc);
786
787	uc = STAILQ_FIRST(&sc->sc_cmd_inactive);
788	if (uc != NULL) {
789		STAILQ_REMOVE_HEAD(&sc->sc_cmd_inactive, next);
790		UATH_STAT_DEC(sc, st_cmd_inactive);
791	} else
792		uc = NULL;
793	if (uc == NULL)
794		DPRINTF(sc, UATH_DEBUG_XMIT, "%s: %s\n", __func__,
795		    "out of command xmit buffers");
796	return (uc);
797}
798
799/*
800 * This function is called periodically (every second) when associated to
801 * query device statistics.
802 */
803static void
804uath_stat(void *arg)
805{
806	struct uath_softc *sc = arg;
807	int error;
808
809	UATH_LOCK(sc);
810	/*
811	 * Send request for statistics asynchronously. The timer will be
812	 * restarted when we'll get the stats notification.
813	 */
814	error = uath_cmd_write(sc, WDCMSG_TARGET_GET_STATS, NULL, 0,
815	    UATH_CMD_FLAG_ASYNC);
816	if (error != 0) {
817		device_printf(sc->sc_dev,
818		    "could not query stats, error %d\n", error);
819	}
820	UATH_UNLOCK(sc);
821}
822
823static int
824uath_get_capability(struct uath_softc *sc, uint32_t cap, uint32_t *val)
825{
826	int error;
827
828	cap = htobe32(cap);
829	error = uath_cmd_read(sc, WDCMSG_TARGET_GET_CAPABILITY,
830	    &cap, sizeof cap, val, sizeof(uint32_t), UATH_CMD_FLAG_MAGIC);
831	if (error != 0) {
832		device_printf(sc->sc_dev, "could not read capability %u\n",
833		    be32toh(cap));
834		return (error);
835	}
836	*val = be32toh(*val);
837	return (error);
838}
839
840static int
841uath_get_devcap(struct uath_softc *sc)
842{
843#define	GETCAP(x, v) do {				\
844	error = uath_get_capability(sc, x, &v);		\
845	if (error != 0)					\
846		return (error);				\
847	DPRINTF(sc, UATH_DEBUG_DEVCAP,			\
848	    "%s: %s=0x%08x\n", __func__, #x, v);	\
849} while (0)
850	struct uath_devcap *cap = &sc->sc_devcap;
851	int error;
852
853	/* collect device capabilities */
854	GETCAP(CAP_TARGET_VERSION, cap->targetVersion);
855	GETCAP(CAP_TARGET_REVISION, cap->targetRevision);
856	GETCAP(CAP_MAC_VERSION, cap->macVersion);
857	GETCAP(CAP_MAC_REVISION, cap->macRevision);
858	GETCAP(CAP_PHY_REVISION, cap->phyRevision);
859	GETCAP(CAP_ANALOG_5GHz_REVISION, cap->analog5GhzRevision);
860	GETCAP(CAP_ANALOG_2GHz_REVISION, cap->analog2GhzRevision);
861
862	GETCAP(CAP_REG_DOMAIN, cap->regDomain);
863	GETCAP(CAP_REG_CAP_BITS, cap->regCapBits);
864#if 0
865	/* NB: not supported in rev 1.5 */
866	GETCAP(CAP_COUNTRY_CODE, cap->countryCode);
867#endif
868	GETCAP(CAP_WIRELESS_MODES, cap->wirelessModes);
869	GETCAP(CAP_CHAN_SPREAD_SUPPORT, cap->chanSpreadSupport);
870	GETCAP(CAP_COMPRESS_SUPPORT, cap->compressSupport);
871	GETCAP(CAP_BURST_SUPPORT, cap->burstSupport);
872	GETCAP(CAP_FAST_FRAMES_SUPPORT, cap->fastFramesSupport);
873	GETCAP(CAP_CHAP_TUNING_SUPPORT, cap->chapTuningSupport);
874	GETCAP(CAP_TURBOG_SUPPORT, cap->turboGSupport);
875	GETCAP(CAP_TURBO_PRIME_SUPPORT, cap->turboPrimeSupport);
876	GETCAP(CAP_DEVICE_TYPE, cap->deviceType);
877	GETCAP(CAP_WME_SUPPORT, cap->wmeSupport);
878	GETCAP(CAP_TOTAL_QUEUES, cap->numTxQueues);
879	GETCAP(CAP_CONNECTION_ID_MAX, cap->connectionIdMax);
880
881	GETCAP(CAP_LOW_5GHZ_CHAN, cap->low5GhzChan);
882	GETCAP(CAP_HIGH_5GHZ_CHAN, cap->high5GhzChan);
883	GETCAP(CAP_LOW_2GHZ_CHAN, cap->low2GhzChan);
884	GETCAP(CAP_HIGH_2GHZ_CHAN, cap->high2GhzChan);
885	GETCAP(CAP_TWICE_ANTENNAGAIN_5G, cap->twiceAntennaGain5G);
886	GETCAP(CAP_TWICE_ANTENNAGAIN_2G, cap->twiceAntennaGain2G);
887
888	GETCAP(CAP_CIPHER_AES_CCM, cap->supportCipherAES_CCM);
889	GETCAP(CAP_CIPHER_TKIP, cap->supportCipherTKIP);
890	GETCAP(CAP_MIC_TKIP, cap->supportMicTKIP);
891
892	cap->supportCipherWEP = 1;	/* NB: always available */
893
894	return (0);
895}
896
897static int
898uath_get_devstatus(struct uath_softc *sc, uint8_t macaddr[IEEE80211_ADDR_LEN])
899{
900	int error;
901
902	/* retrieve MAC address */
903	error = uath_get_status(sc, ST_MAC_ADDR, macaddr, IEEE80211_ADDR_LEN);
904	if (error != 0) {
905		device_printf(sc->sc_dev, "could not read MAC address\n");
906		return (error);
907	}
908
909	error = uath_get_status(sc, ST_SERIAL_NUMBER,
910	    &sc->sc_serial[0], sizeof(sc->sc_serial));
911	if (error != 0) {
912		device_printf(sc->sc_dev,
913		    "could not read device serial number\n");
914		return (error);
915	}
916	return (0);
917}
918
919static int
920uath_get_status(struct uath_softc *sc, uint32_t which, void *odata, int olen)
921{
922	int error;
923
924	which = htobe32(which);
925	error = uath_cmd_read(sc, WDCMSG_TARGET_GET_STATUS,
926	    &which, sizeof(which), odata, olen, UATH_CMD_FLAG_MAGIC);
927	if (error != 0)
928		device_printf(sc->sc_dev,
929		    "could not read EEPROM offset 0x%02x\n", be32toh(which));
930	return (error);
931}
932
933static void
934uath_free_data_list(struct uath_softc *sc, struct uath_data data[], int ndata,
935    int fillmbuf)
936{
937	int i;
938
939	for (i = 0; i < ndata; i++) {
940		struct uath_data *dp = &data[i];
941
942		if (fillmbuf == 1) {
943			if (dp->m != NULL) {
944				m_freem(dp->m);
945				dp->m = NULL;
946				dp->buf = NULL;
947			}
948		} else {
949			if (dp->buf != NULL) {
950				free(dp->buf, M_USBDEV);
951				dp->buf = NULL;
952			}
953		}
954#ifdef UATH_DEBUG
955		if (dp->ni != NULL)
956			device_printf(sc->sc_dev, "Node isn't NULL\n");
957#endif
958	}
959}
960
961static int
962uath_alloc_data_list(struct uath_softc *sc, struct uath_data data[],
963	int ndata, int maxsz, int fillmbuf)
964{
965	int i, error;
966
967	for (i = 0; i < ndata; i++) {
968		struct uath_data *dp = &data[i];
969
970		dp->sc = sc;
971		if (fillmbuf) {
972			/* XXX check maxsz */
973			dp->m = m_getcl(M_DONTWAIT, MT_DATA, M_PKTHDR);
974			if (dp->m == NULL) {
975				device_printf(sc->sc_dev,
976				    "could not allocate rx mbuf\n");
977				error = ENOMEM;
978				goto fail;
979			}
980			dp->buf = mtod(dp->m, uint8_t *);
981		} else {
982			dp->m = NULL;
983			dp->buf = malloc(maxsz, M_USBDEV, M_NOWAIT);
984			if (dp->buf == NULL) {
985				device_printf(sc->sc_dev,
986				    "could not allocate buffer\n");
987				error = ENOMEM;
988				goto fail;
989			}
990		}
991		dp->ni = NULL;
992	}
993
994	return (0);
995
996fail:	uath_free_data_list(sc, data, ndata, fillmbuf);
997	return (error);
998}
999
1000static int
1001uath_alloc_rx_data_list(struct uath_softc *sc)
1002{
1003	int error, i;
1004
1005	/* XXX is it enough to store the RX packet with MCLBYTES bytes?  */
1006	error = uath_alloc_data_list(sc,
1007	    sc->sc_rx, UATH_RX_DATA_LIST_COUNT, MCLBYTES,
1008	    1 /* setup mbufs */);
1009	if (error != 0)
1010		return (error);
1011
1012	STAILQ_INIT(&sc->sc_rx_active);
1013	STAILQ_INIT(&sc->sc_rx_inactive);
1014
1015	for (i = 0; i < UATH_RX_DATA_LIST_COUNT; i++) {
1016		STAILQ_INSERT_HEAD(&sc->sc_rx_inactive, &sc->sc_rx[i],
1017		    next);
1018		UATH_STAT_INC(sc, st_rx_inactive);
1019	}
1020
1021	return (0);
1022}
1023
1024static int
1025uath_alloc_tx_data_list(struct uath_softc *sc)
1026{
1027	int error, i;
1028
1029	error = uath_alloc_data_list(sc,
1030	    sc->sc_tx, UATH_TX_DATA_LIST_COUNT, UATH_MAX_TXBUFSZ,
1031	    0 /* no mbufs */);
1032	if (error != 0)
1033		return (error);
1034
1035	STAILQ_INIT(&sc->sc_tx_active);
1036	STAILQ_INIT(&sc->sc_tx_inactive);
1037	STAILQ_INIT(&sc->sc_tx_pending);
1038
1039	for (i = 0; i < UATH_TX_DATA_LIST_COUNT; i++) {
1040		STAILQ_INSERT_HEAD(&sc->sc_tx_inactive, &sc->sc_tx[i],
1041		    next);
1042		UATH_STAT_INC(sc, st_tx_inactive);
1043	}
1044
1045	return (0);
1046}
1047
1048static void
1049uath_free_rx_data_list(struct uath_softc *sc)
1050{
1051
1052	STAILQ_INIT(&sc->sc_rx_active);
1053	STAILQ_INIT(&sc->sc_rx_inactive);
1054
1055	uath_free_data_list(sc, sc->sc_rx, UATH_RX_DATA_LIST_COUNT,
1056	    1 /* free mbufs */);
1057}
1058
1059static void
1060uath_free_tx_data_list(struct uath_softc *sc)
1061{
1062
1063	STAILQ_INIT(&sc->sc_tx_active);
1064	STAILQ_INIT(&sc->sc_tx_inactive);
1065	STAILQ_INIT(&sc->sc_tx_pending);
1066
1067	uath_free_data_list(sc, sc->sc_tx, UATH_TX_DATA_LIST_COUNT,
1068	    0 /* no mbufs */);
1069}
1070
1071static struct ieee80211vap *
1072uath_vap_create(struct ieee80211com *ic,
1073	const char name[IFNAMSIZ], int unit, int opmode, int flags,
1074	const uint8_t bssid[IEEE80211_ADDR_LEN],
1075	const uint8_t mac[IEEE80211_ADDR_LEN])
1076{
1077	struct uath_vap *uvp;
1078	struct ieee80211vap *vap;
1079
1080	if (!TAILQ_EMPTY(&ic->ic_vaps))		/* only one at a time */
1081		return (NULL);
1082	uvp = (struct uath_vap *) malloc(sizeof(struct uath_vap),
1083	    M_80211_VAP, M_NOWAIT | M_ZERO);
1084	if (uvp == NULL)
1085		return (NULL);
1086	vap = &uvp->vap;
1087	/* enable s/w bmiss handling for sta mode */
1088	ieee80211_vap_setup(ic, vap, name, unit, opmode,
1089	    flags | IEEE80211_CLONE_NOBEACONS, bssid, mac);
1090
1091	/* override state transition machine */
1092	uvp->newstate = vap->iv_newstate;
1093	vap->iv_newstate = uath_newstate;
1094
1095	/* complete setup */
1096	ieee80211_vap_attach(vap, ieee80211_media_change,
1097	    ieee80211_media_status);
1098	ic->ic_opmode = opmode;
1099	return (vap);
1100}
1101
1102static void
1103uath_vap_delete(struct ieee80211vap *vap)
1104{
1105	struct uath_vap *uvp = UATH_VAP(vap);
1106
1107	ieee80211_vap_detach(vap);
1108	free(uvp, M_80211_VAP);
1109}
1110
1111static int
1112uath_init_locked(void *arg)
1113{
1114	struct uath_softc *sc = arg;
1115	struct ifnet *ifp = sc->sc_ifp;
1116	struct ieee80211com *ic = ifp->if_l2com;
1117	uint32_t val;
1118	int error;
1119
1120	UATH_ASSERT_LOCKED(sc);
1121
1122	if (ifp->if_drv_flags & IFF_DRV_RUNNING)
1123		uath_stop_locked(ifp);
1124
1125	/* reset variables */
1126	sc->sc_intrx_nextnum = sc->sc_msgid = 0;
1127
1128	val = htobe32(0);
1129	uath_cmd_write(sc, WDCMSG_BIND, &val, sizeof val, 0);
1130
1131	/* set MAC address */
1132	uath_config_multi(sc, CFG_MAC_ADDR, IF_LLADDR(ifp), IEEE80211_ADDR_LEN);
1133
1134	/* XXX honor net80211 state */
1135	uath_config(sc, CFG_RATE_CONTROL_ENABLE, 0x00000001);
1136	uath_config(sc, CFG_DIVERSITY_CTL, 0x00000001);
1137	uath_config(sc, CFG_ABOLT, 0x0000003f);
1138	uath_config(sc, CFG_WME_ENABLED, 0x00000001);
1139
1140	uath_config(sc, CFG_SERVICE_TYPE, 1);
1141	uath_config(sc, CFG_TP_SCALE, 0x00000000);
1142	uath_config(sc, CFG_TPC_HALF_DBM5, 0x0000003c);
1143	uath_config(sc, CFG_TPC_HALF_DBM2, 0x0000003c);
1144	uath_config(sc, CFG_OVERRD_TX_POWER, 0x00000000);
1145	uath_config(sc, CFG_GMODE_PROTECTION, 0x00000000);
1146	uath_config(sc, CFG_GMODE_PROTECT_RATE_INDEX, 0x00000003);
1147	uath_config(sc, CFG_PROTECTION_TYPE, 0x00000000);
1148	uath_config(sc, CFG_MODE_CTS, 0x00000002);
1149
1150	error = uath_cmd_read(sc, WDCMSG_TARGET_START, NULL, 0,
1151	    &val, sizeof(val), UATH_CMD_FLAG_MAGIC);
1152	if (error) {
1153		device_printf(sc->sc_dev,
1154		    "could not start target, error %d\n", error);
1155		goto fail;
1156	}
1157	DPRINTF(sc, UATH_DEBUG_INIT, "%s returns handle: 0x%x\n",
1158	    uath_codename(WDCMSG_TARGET_START), be32toh(val));
1159
1160	/* set default channel */
1161	error = uath_switch_channel(sc, ic->ic_curchan);
1162	if (error) {
1163		device_printf(sc->sc_dev,
1164		    "could not switch channel, error %d\n", error);
1165		goto fail;
1166	}
1167
1168	val = htobe32(TARGET_DEVICE_AWAKE);
1169	uath_cmd_write(sc, WDCMSG_SET_PWR_MODE, &val, sizeof val, 0);
1170	/* XXX? check */
1171	uath_cmd_write(sc, WDCMSG_RESET_KEY_CACHE, NULL, 0, 0);
1172
1173	usb2_transfer_start(sc->sc_xfer[UATH_BULK_RX]);
1174	/* enable Rx */
1175	uath_set_rxfilter(sc, 0x0, UATH_FILTER_OP_INIT);
1176	uath_set_rxfilter(sc,
1177	    UATH_FILTER_RX_UCAST | UATH_FILTER_RX_MCAST |
1178	    UATH_FILTER_RX_BCAST | UATH_FILTER_RX_BEACON,
1179	    UATH_FILTER_OP_SET);
1180
1181	ifp->if_drv_flags &= ~IFF_DRV_OACTIVE;
1182	ifp->if_drv_flags |= IFF_DRV_RUNNING;
1183	sc->sc_flags |= UATH_FLAG_INITDONE;
1184
1185	callout_reset(&sc->watchdog_ch, hz, uath_watchdog, sc);
1186
1187	return (0);
1188
1189fail:
1190	uath_stop_locked(ifp);
1191	return (error);
1192}
1193
1194static void
1195uath_init(void *arg)
1196{
1197	struct uath_softc *sc = arg;
1198
1199	UATH_LOCK(sc);
1200	(void)uath_init_locked(sc);
1201	UATH_UNLOCK(sc);
1202}
1203
1204static void
1205uath_stop_locked(struct ifnet *ifp)
1206{
1207	struct uath_softc *sc = ifp->if_softc;
1208
1209	UATH_ASSERT_LOCKED(sc);
1210
1211	ifp->if_drv_flags &= ~(IFF_DRV_RUNNING | IFF_DRV_OACTIVE);
1212	sc->sc_flags &= ~UATH_FLAG_INITDONE;
1213
1214	callout_stop(&sc->stat_ch);
1215	callout_stop(&sc->watchdog_ch);
1216	sc->sc_tx_timer = 0;
1217	/* abort pending transmits  */
1218	uath_abort_xfers(sc);
1219	/* flush data & control requests into the target  */
1220	(void)uath_flush(sc);
1221	/* set a LED status to the disconnected.  */
1222	uath_set_ledstate(sc, 0);
1223	/* stop the target  */
1224	uath_cmd_write(sc, WDCMSG_TARGET_STOP, NULL, 0, 0);
1225}
1226
1227static void
1228uath_stop(struct ifnet *ifp)
1229{
1230	struct uath_softc *sc = ifp->if_softc;
1231
1232	UATH_LOCK(sc);
1233	uath_stop_locked(ifp);
1234	UATH_UNLOCK(sc);
1235}
1236
1237static int
1238uath_config(struct uath_softc *sc, uint32_t reg, uint32_t val)
1239{
1240	struct uath_write_mac write;
1241	int error;
1242
1243	write.reg = htobe32(reg);
1244	write.len = htobe32(0);	/* 0 = single write */
1245	*(uint32_t *)write.data = htobe32(val);
1246
1247	error = uath_cmd_write(sc, WDCMSG_TARGET_SET_CONFIG, &write,
1248	    3 * sizeof (uint32_t), 0);
1249	if (error != 0) {
1250		device_printf(sc->sc_dev, "could not write register 0x%02x\n",
1251		    reg);
1252	}
1253	return (error);
1254}
1255
1256static int
1257uath_config_multi(struct uath_softc *sc, uint32_t reg, const void *data,
1258    int len)
1259{
1260	struct uath_write_mac write;
1261	int error;
1262
1263	write.reg = htobe32(reg);
1264	write.len = htobe32(len);
1265	bcopy(data, write.data, len);
1266
1267	/* properly handle the case where len is zero (reset) */
1268	error = uath_cmd_write(sc, WDCMSG_TARGET_SET_CONFIG, &write,
1269	    (len == 0) ? sizeof (uint32_t) : 2 * sizeof (uint32_t) + len, 0);
1270	if (error != 0) {
1271		device_printf(sc->sc_dev,
1272		    "could not write %d bytes to register 0x%02x\n", len, reg);
1273	}
1274	return (error);
1275}
1276
1277static int
1278uath_switch_channel(struct uath_softc *sc, struct ieee80211_channel *c)
1279{
1280	int error;
1281
1282	UATH_ASSERT_LOCKED(sc);
1283
1284	/* set radio frequency */
1285	error = uath_set_chan(sc, c);
1286	if (error) {
1287		device_printf(sc->sc_dev,
1288		    "could not set channel, error %d\n", error);
1289		goto failed;
1290	}
1291	/* reset Tx rings */
1292	error = uath_reset_tx_queues(sc);
1293	if (error) {
1294		device_printf(sc->sc_dev,
1295		    "could not reset Tx queues, error %d\n", error);
1296		goto failed;
1297	}
1298	/* set Tx rings WME properties */
1299	error = uath_wme_init(sc);
1300	if (error) {
1301		device_printf(sc->sc_dev,
1302		    "could not init Tx queues, error %d\n", error);
1303		goto failed;
1304	}
1305	error = uath_set_ledstate(sc, 0);
1306	if (error) {
1307		device_printf(sc->sc_dev,
1308		    "could not set led state, error %d\n", error);
1309		goto failed;
1310	}
1311	error = uath_flush(sc);
1312	if (error) {
1313		device_printf(sc->sc_dev,
1314		    "could not flush pipes, error %d\n", error);
1315		goto failed;
1316	}
1317failed:
1318	return (error);
1319}
1320
1321static int
1322uath_set_rxfilter(struct uath_softc *sc, uint32_t bits, uint32_t op)
1323{
1324	struct uath_cmd_rx_filter rxfilter;
1325
1326	rxfilter.bits = htobe32(bits);
1327	rxfilter.op = htobe32(op);
1328
1329	DPRINTF(sc, UATH_DEBUG_RECV | UATH_DEBUG_RECV_ALL,
1330	    "setting Rx filter=0x%x flags=0x%x\n", bits, op);
1331	return uath_cmd_write(sc, WDCMSG_RX_FILTER, &rxfilter,
1332	    sizeof rxfilter, 0);
1333}
1334
1335static void
1336uath_watchdog(void *arg)
1337{
1338	struct uath_softc *sc = arg;
1339	struct ifnet *ifp = sc->sc_ifp;
1340
1341	if (sc->sc_tx_timer > 0) {
1342		if (--sc->sc_tx_timer == 0) {
1343			device_printf(sc->sc_dev, "device timeout\n");
1344			/*uath_init(ifp); XXX needs a process context! */
1345			ifp->if_oerrors++;
1346			return;
1347		}
1348		callout_reset(&sc->watchdog_ch, hz, uath_watchdog, sc);
1349	}
1350}
1351
1352static void
1353uath_abort_xfers(struct uath_softc *sc)
1354{
1355	int i;
1356
1357	UATH_ASSERT_LOCKED(sc);
1358	/* abort any pending transfers */
1359	for (i = 0; i < UATH_N_XFERS; i++)
1360		usb2_transfer_stop(sc->sc_xfer[i]);
1361}
1362
1363static int
1364uath_flush(struct uath_softc *sc)
1365{
1366	int error;
1367
1368	error = uath_dataflush(sc);
1369	if (error != 0)
1370		goto failed;
1371
1372	error = uath_cmdflush(sc);
1373	if (error != 0)
1374		goto failed;
1375
1376failed:
1377	return (error);
1378}
1379
1380static int
1381uath_cmdflush(struct uath_softc *sc)
1382{
1383
1384	return uath_cmd_write(sc, WDCMSG_FLUSH, NULL, 0, 0);
1385}
1386
1387static int
1388uath_dataflush(struct uath_softc *sc)
1389{
1390	struct uath_data *data;
1391	struct uath_chunk *chunk;
1392	struct uath_tx_desc *desc;
1393
1394	UATH_ASSERT_LOCKED(sc);
1395
1396	data = uath_getbuf(sc);
1397	if (data == NULL)
1398		return (ENOBUFS);
1399	data->buflen = sizeof(struct uath_chunk) + sizeof(struct uath_tx_desc);
1400	data->m = NULL;
1401	data->ni = NULL;
1402	chunk = (struct uath_chunk *)data->buf;
1403	desc = (struct uath_tx_desc *)(chunk + 1);
1404
1405	/* one chunk only */
1406	chunk->seqnum = 0;
1407	chunk->flags = UATH_CFLAGS_FINAL;
1408	chunk->length = htobe16(sizeof (struct uath_tx_desc));
1409
1410	bzero(desc, sizeof(struct uath_tx_desc));
1411	desc->msglen = htobe32(sizeof(struct uath_tx_desc));
1412	desc->msgid  = (sc->sc_msgid++) + 1; /* don't care about endianness */
1413	desc->type   = htobe32(WDCMSG_FLUSH);
1414	desc->txqid  = htobe32(0);
1415	desc->connid = htobe32(0);
1416	desc->flags  = htobe32(0);
1417
1418#ifdef UATH_DEBUG
1419	if (sc->sc_debug & UATH_DEBUG_CMDS) {
1420		DPRINTF(sc, UATH_DEBUG_RESET, "send flush ix %d\n",
1421		    desc->msgid);
1422		if (sc->sc_debug & UATH_DEBUG_CMDS_DUMP)
1423			uath_dump_cmd(data->buf, data->buflen, '+');
1424	}
1425#endif
1426
1427	STAILQ_INSERT_TAIL(&sc->sc_tx_pending, data, next);
1428	UATH_STAT_INC(sc, st_tx_pending);
1429	sc->sc_tx_timer = 5;
1430	usb2_transfer_start(sc->sc_xfer[UATH_BULK_TX]);
1431
1432	return (0);
1433}
1434
1435static struct uath_data *
1436_uath_getbuf(struct uath_softc *sc)
1437{
1438	struct uath_data *bf;
1439
1440	bf = STAILQ_FIRST(&sc->sc_tx_inactive);
1441	if (bf != NULL) {
1442		STAILQ_REMOVE_HEAD(&sc->sc_tx_inactive, next);
1443		UATH_STAT_DEC(sc, st_tx_inactive);
1444	} else
1445		bf = NULL;
1446	if (bf == NULL)
1447		DPRINTF(sc, UATH_DEBUG_XMIT, "%s: %s\n", __func__,
1448		    "out of xmit buffers");
1449	return (bf);
1450}
1451
1452static struct uath_data *
1453uath_getbuf(struct uath_softc *sc)
1454{
1455	struct uath_data *bf;
1456
1457	UATH_ASSERT_LOCKED(sc);
1458
1459	bf = _uath_getbuf(sc);
1460	if (bf == NULL) {
1461		struct ifnet *ifp = sc->sc_ifp;
1462
1463		DPRINTF(sc, UATH_DEBUG_XMIT, "%s: stop queue\n", __func__);
1464		ifp->if_drv_flags |= IFF_DRV_OACTIVE;
1465	}
1466	return (bf);
1467}
1468
1469static int
1470uath_set_ledstate(struct uath_softc *sc, int connected)
1471{
1472
1473	DPRINTF(sc, UATH_DEBUG_LED,
1474	    "set led state %sconnected\n", connected ? "" : "!");
1475	connected = htobe32(connected);
1476	return uath_cmd_write(sc, WDCMSG_SET_LED_STATE,
1477	     &connected, sizeof connected, 0);
1478}
1479
1480static int
1481uath_set_chan(struct uath_softc *sc, struct ieee80211_channel *c)
1482{
1483#ifdef UATH_DEBUG
1484	struct ifnet *ifp = sc->sc_ifp;
1485	struct ieee80211com *ic = ifp->if_l2com;
1486#endif
1487	struct uath_cmd_reset reset;
1488
1489	bzero(&reset, sizeof reset);
1490	if (IEEE80211_IS_CHAN_2GHZ(c))
1491		reset.flags |= htobe32(UATH_CHAN_2GHZ);
1492	if (IEEE80211_IS_CHAN_5GHZ(c))
1493		reset.flags |= htobe32(UATH_CHAN_5GHZ);
1494	/* NB: 11g =>'s 11b so don't specify both OFDM and CCK */
1495	if (IEEE80211_IS_CHAN_G(c))
1496		reset.flags |= htobe32(UATH_CHAN_OFDM);
1497	else if (IEEE80211_IS_CHAN_B(c))
1498		reset.flags |= htobe32(UATH_CHAN_CCK);
1499	/* turbo can be used in either 2GHz or 5GHz */
1500	if (c->ic_flags & IEEE80211_CHAN_TURBO)
1501		reset.flags |= htobe32(UATH_CHAN_TURBO);
1502	reset.freq = htobe32(c->ic_freq);
1503	reset.maxrdpower = htobe32(50);	/* XXX */
1504	reset.channelchange = htobe32(1);
1505	reset.keeprccontent = htobe32(0);
1506
1507	DPRINTF(sc, UATH_DEBUG_CHANNEL, "set channel %d, flags 0x%x freq %u\n",
1508	    ieee80211_chan2ieee(ic, c),
1509	    be32toh(reset.flags), be32toh(reset.freq));
1510	return uath_cmd_write(sc, WDCMSG_RESET, &reset, sizeof reset, 0);
1511}
1512
1513static int
1514uath_reset_tx_queues(struct uath_softc *sc)
1515{
1516	int ac, error;
1517
1518	DPRINTF(sc, UATH_DEBUG_RESET, "%s: reset Tx queues\n", __func__);
1519	for (ac = 0; ac < 4; ac++) {
1520		const uint32_t qid = htobe32(ac);
1521
1522		error = uath_cmd_write(sc, WDCMSG_RELEASE_TX_QUEUE, &qid,
1523		    sizeof qid, 0);
1524		if (error != 0)
1525			break;
1526	}
1527	return (error);
1528}
1529
1530static int
1531uath_wme_init(struct uath_softc *sc)
1532{
1533	/* XXX get from net80211 */
1534	static const struct uath_wme_settings uath_wme_11g[4] = {
1535		{ 7, 4, 10,  0, 0 },	/* Background */
1536		{ 3, 4, 10,  0, 0 },	/* Best-Effort */
1537		{ 3, 3,  4, 26, 0 },	/* Video */
1538		{ 2, 2,  3, 47, 0 }	/* Voice */
1539	};
1540	struct uath_cmd_txq_setup qinfo;
1541	int ac, error;
1542
1543	DPRINTF(sc, UATH_DEBUG_WME, "%s: setup Tx queues\n", __func__);
1544	for (ac = 0; ac < 4; ac++) {
1545		qinfo.qid		= htobe32(ac);
1546		qinfo.len		= htobe32(sizeof(qinfo.attr));
1547		qinfo.attr.priority	= htobe32(ac);	/* XXX */
1548		qinfo.attr.aifs		= htobe32(uath_wme_11g[ac].aifsn);
1549		qinfo.attr.logcwmin	= htobe32(uath_wme_11g[ac].logcwmin);
1550		qinfo.attr.logcwmax	= htobe32(uath_wme_11g[ac].logcwmax);
1551		qinfo.attr.bursttime	= htobe32(UATH_TXOP_TO_US(
1552					    uath_wme_11g[ac].txop));
1553		qinfo.attr.mode		= htobe32(uath_wme_11g[ac].acm);/*XXX? */
1554		qinfo.attr.qflags	= htobe32(1);	/* XXX? */
1555
1556		error = uath_cmd_write(sc, WDCMSG_SETUP_TX_QUEUE, &qinfo,
1557		    sizeof qinfo, 0);
1558		if (error != 0)
1559			break;
1560	}
1561	return (error);
1562}
1563
1564static int
1565uath_ioctl(struct ifnet *ifp, u_long cmd, caddr_t data)
1566{
1567	struct ieee80211com *ic = ifp->if_l2com;
1568	struct ifreq *ifr = (struct ifreq *) data;
1569	int error = 0, startall = 0;
1570
1571	switch (cmd) {
1572	case SIOCSIFFLAGS:
1573		if (ifp->if_flags & IFF_UP) {
1574			if (!(ifp->if_drv_flags & IFF_DRV_RUNNING)) {
1575				uath_init(ifp->if_softc);
1576				startall = 1;
1577			}
1578		} else {
1579			if (ifp->if_drv_flags & IFF_DRV_RUNNING)
1580				uath_stop(ifp);
1581		}
1582		if (startall)
1583			ieee80211_start_all(ic);
1584		break;
1585	case SIOCGIFMEDIA:
1586		error = ifmedia_ioctl(ifp, ifr, &ic->ic_media, cmd);
1587		break;
1588	case SIOCGIFADDR:
1589		error = ether_ioctl(ifp, cmd, data);
1590		break;
1591	default:
1592		error = EINVAL;
1593		break;
1594	}
1595
1596	return (error);
1597}
1598
1599static int
1600uath_tx_start(struct uath_softc *sc, struct mbuf *m0, struct ieee80211_node *ni,
1601    struct uath_data *data)
1602{
1603	struct ifnet *ifp = sc->sc_ifp;
1604	struct ieee80211com *ic = ifp->if_l2com;
1605	struct ieee80211vap *vap = ni->ni_vap;
1606	struct uath_chunk *chunk;
1607	struct uath_tx_desc *desc;
1608	const struct ieee80211_frame *wh;
1609	struct ieee80211_key *k;
1610	int framelen, msglen;
1611
1612	UATH_ASSERT_LOCKED(sc);
1613
1614	data->ni = ni;
1615	data->m = m0;
1616	chunk = (struct uath_chunk *)data->buf;
1617	desc = (struct uath_tx_desc *)(chunk + 1);
1618
1619	if (bpf_peers_present(ifp->if_bpf)) {
1620		struct uath_tx_radiotap_header *tap = &sc->sc_txtap;
1621
1622		tap->wt_flags = 0;
1623		if (m0->m_flags & M_FRAG)
1624			tap->wt_flags |= IEEE80211_RADIOTAP_F_FRAG;
1625		tap->wt_chan_freq = htole16(ic->ic_curchan->ic_freq);
1626		tap->wt_chan_flags = htole16(ic->ic_curchan->ic_flags);
1627
1628		bpf_mtap2(ifp->if_bpf, tap, sc->sc_txtap_len, m0);
1629	}
1630
1631	wh = mtod(m0, struct ieee80211_frame *);
1632	if (wh->i_fc[1] & IEEE80211_FC1_WEP) {
1633		k = ieee80211_crypto_encap(ni, m0);
1634		if (k == NULL) {
1635			m_freem(m0);
1636			return (ENOBUFS);
1637		}
1638
1639		/* packet header may have moved, reset our local pointer */
1640		wh = mtod(m0, struct ieee80211_frame *);
1641	}
1642	m_copydata(m0, 0, m0->m_pkthdr.len, (uint8_t *)(desc + 1));
1643
1644	framelen = m0->m_pkthdr.len + IEEE80211_CRC_LEN;
1645	msglen = framelen + sizeof (struct uath_tx_desc);
1646	data->buflen = msglen + sizeof (struct uath_chunk);
1647
1648	/* one chunk only for now */
1649	chunk->seqnum = sc->sc_seqnum++;
1650	chunk->flags = (m0->m_flags & M_FRAG) ? 0 : UATH_CFLAGS_FINAL;
1651	if (m0->m_flags & M_LASTFRAG)
1652		chunk->flags |= UATH_CFLAGS_FINAL;
1653	chunk->flags = UATH_CFLAGS_FINAL;
1654	chunk->length = htobe16(msglen);
1655
1656	/* fill Tx descriptor */
1657	desc->msglen = htobe32(msglen);
1658	/* NB: to get UATH_TX_NOTIFY reply, `msgid' must be larger than 0  */
1659	desc->msgid  = (sc->sc_msgid++) + 1; /* don't care about endianness */
1660	desc->type   = htobe32(WDCMSG_SEND);
1661	switch (wh->i_fc[0] & IEEE80211_FC0_TYPE_MASK) {
1662	case IEEE80211_FC0_TYPE_CTL:
1663	case IEEE80211_FC0_TYPE_MGT:
1664		/* NB: force all management frames to highest queue */
1665		if (ni->ni_flags & IEEE80211_NODE_QOS) {
1666			/* NB: force all management frames to highest queue */
1667			desc->txqid = htobe32(WME_AC_VO | UATH_TXQID_MINRATE);
1668		} else
1669			desc->txqid = htobe32(WME_AC_BE | UATH_TXQID_MINRATE);
1670		break;
1671	case IEEE80211_FC0_TYPE_DATA:
1672		/* XXX multicast frames should honor mcastrate */
1673		desc->txqid = htobe32(M_WME_GETAC(m0));
1674		break;
1675	default:
1676		device_printf(sc->sc_dev, "bogus frame type 0x%x (%s)\n",
1677			wh->i_fc[0] & IEEE80211_FC0_TYPE_MASK, __func__);
1678		m_freem(m0);
1679		return (EIO);
1680	}
1681	if (vap->iv_state == IEEE80211_S_AUTH ||
1682	    vap->iv_state == IEEE80211_S_ASSOC ||
1683	    vap->iv_state == IEEE80211_S_RUN)
1684		desc->connid = htobe32(UATH_ID_BSS);
1685	else
1686		desc->connid = htobe32(UATH_ID_INVALID);
1687	desc->flags  = htobe32(0 /* no UATH_TX_NOTIFY */);
1688	desc->buflen = htobe32(m0->m_pkthdr.len);
1689
1690#ifdef UATH_DEBUG
1691	DPRINTF(sc, UATH_DEBUG_XMIT,
1692	    "send frame ix %u framelen %d msglen %d connid 0x%x txqid 0x%x\n",
1693	    desc->msgid, framelen, msglen, be32toh(desc->connid),
1694	    be32toh(desc->txqid));
1695	if (sc->sc_debug & UATH_DEBUG_XMIT_DUMP)
1696		uath_dump_cmd(data->buf, data->buflen, '+');
1697#endif
1698
1699	STAILQ_INSERT_TAIL(&sc->sc_tx_pending, data, next);
1700	UATH_STAT_INC(sc, st_tx_pending);
1701	usb2_transfer_start(sc->sc_xfer[UATH_BULK_TX]);
1702
1703	return (0);
1704}
1705
1706/*
1707 * Cleanup driver resources when we run out of buffers while processing
1708 * fragments; return the tx buffers allocated and drop node references.
1709 */
1710static void
1711uath_txfrag_cleanup(struct uath_softc *sc,
1712    uath_datahead *frags, struct ieee80211_node *ni)
1713{
1714	struct uath_data *bf, *next;
1715
1716	UATH_ASSERT_LOCKED(sc);
1717
1718	STAILQ_FOREACH_SAFE(bf, frags, next, next) {
1719		/* NB: bf assumed clean */
1720		STAILQ_REMOVE_HEAD(frags, next);
1721		STAILQ_INSERT_HEAD(&sc->sc_tx_inactive, bf, next);
1722		UATH_STAT_INC(sc, st_tx_inactive);
1723		ieee80211_node_decref(ni);
1724	}
1725}
1726
1727/*
1728 * Setup xmit of a fragmented frame.  Allocate a buffer for each frag and bump
1729 * the node reference count to reflect the held reference to be setup by
1730 * uath_tx_start.
1731 */
1732static int
1733uath_txfrag_setup(struct uath_softc *sc, uath_datahead *frags,
1734    struct mbuf *m0, struct ieee80211_node *ni)
1735{
1736	struct mbuf *m;
1737	struct uath_data *bf;
1738
1739	UATH_ASSERT_LOCKED(sc);
1740	for (m = m0->m_nextpkt; m != NULL; m = m->m_nextpkt) {
1741		bf = uath_getbuf(sc);
1742		if (bf == NULL) {       /* out of buffers, cleanup */
1743			uath_txfrag_cleanup(sc, frags, ni);
1744			break;
1745		}
1746		ieee80211_node_incref(ni);
1747		STAILQ_INSERT_TAIL(frags, bf, next);
1748	}
1749
1750	return !STAILQ_EMPTY(frags);
1751}
1752
1753/*
1754 * Reclaim mbuf resources.  For fragmented frames we need to claim each frag
1755 * chained with m_nextpkt.
1756 */
1757static void
1758uath_freetx(struct mbuf *m)
1759{
1760	struct mbuf *next;
1761
1762	do {
1763		next = m->m_nextpkt;
1764		m->m_nextpkt = NULL;
1765		m_freem(m);
1766	} while ((m = next) != NULL);
1767}
1768
1769static void
1770uath_start(struct ifnet *ifp)
1771{
1772	struct uath_data *bf;
1773	struct uath_softc *sc = ifp->if_softc;
1774	struct ieee80211_node *ni;
1775	struct mbuf *m, *next;
1776	uath_datahead frags;
1777
1778	if ((ifp->if_drv_flags & IFF_DRV_RUNNING) == 0 ||
1779	    (sc->sc_flags & UATH_FLAG_INVALID))
1780		return;
1781
1782	UATH_LOCK(sc);
1783	for (;;) {
1784		bf = uath_getbuf(sc);
1785		if (bf == NULL)
1786			break;
1787
1788		IFQ_DRV_DEQUEUE(&ifp->if_snd, m);
1789		if (m == NULL) {
1790			STAILQ_INSERT_HEAD(&sc->sc_tx_inactive, bf, next);
1791			UATH_STAT_INC(sc, st_tx_inactive);
1792			break;
1793		}
1794		ni = (struct ieee80211_node *)m->m_pkthdr.rcvif;
1795		m->m_pkthdr.rcvif = NULL;
1796
1797		/*
1798		 * Check for fragmentation.  If this frame has been broken up
1799		 * verify we have enough buffers to send all the fragments
1800		 * so all go out or none...
1801		 */
1802		STAILQ_INIT(&frags);
1803		if ((m->m_flags & M_FRAG) &&
1804		    !uath_txfrag_setup(sc, &frags, m, ni)) {
1805			DPRINTF(sc, UATH_DEBUG_XMIT,
1806			    "%s: out of txfrag buffers\n", __func__);
1807			uath_freetx(m);
1808			goto bad;
1809		}
1810		sc->sc_seqnum = 0;
1811	nextfrag:
1812		/*
1813		 * Pass the frame to the h/w for transmission.
1814		 * Fragmented frames have each frag chained together
1815		 * with m_nextpkt.  We know there are sufficient uath_data's
1816		 * to send all the frags because of work done by
1817		 * uath_txfrag_setup.
1818		 */
1819		next = m->m_nextpkt;
1820		if (uath_tx_start(sc, m, ni, bf) != 0) {
1821	bad:
1822			ifp->if_oerrors++;
1823	reclaim:
1824			STAILQ_INSERT_HEAD(&sc->sc_tx_inactive, bf, next);
1825			UATH_STAT_INC(sc, st_tx_inactive);
1826			uath_txfrag_cleanup(sc, &frags, ni);
1827			ieee80211_free_node(ni);
1828			continue;
1829		}
1830
1831		if (next != NULL) {
1832			/*
1833			 * Beware of state changing between frags.
1834			 XXX check sta power-save state?
1835			*/
1836			if (ni->ni_vap->iv_state != IEEE80211_S_RUN) {
1837				DPRINTF(sc, UATH_DEBUG_XMIT,
1838				    "%s: flush fragmented packet, state %s\n",
1839				    __func__,
1840				    ieee80211_state_name[ni->ni_vap->iv_state]);
1841				uath_freetx(next);
1842				goto reclaim;
1843			}
1844			m = next;
1845			bf = STAILQ_FIRST(&frags);
1846			KASSERT(bf != NULL, ("no buf for txfrag"));
1847			STAILQ_REMOVE_HEAD(&frags, next);
1848			goto nextfrag;
1849		}
1850
1851		sc->sc_tx_timer = 5;
1852	}
1853	UATH_UNLOCK(sc);
1854}
1855
1856static int
1857uath_raw_xmit(struct ieee80211_node *ni, struct mbuf *m,
1858    const struct ieee80211_bpf_params *params)
1859{
1860	struct ieee80211com *ic = ni->ni_ic;
1861	struct ifnet *ifp = ic->ic_ifp;
1862	struct uath_data *bf;
1863	struct uath_softc *sc = ifp->if_softc;
1864
1865	/* prevent management frames from being sent if we're not ready */
1866	if (!(ifp->if_drv_flags & IFF_DRV_RUNNING)) {
1867		m_freem(m);
1868		ieee80211_free_node(ni);
1869		return (ENETDOWN);
1870	}
1871
1872	UATH_LOCK(sc);
1873	/* grab a TX buffer  */
1874	bf = uath_getbuf(sc);
1875	if (bf == NULL) {
1876		ieee80211_free_node(ni);
1877		m_freem(m);
1878		UATH_UNLOCK(sc);
1879		return (ENOBUFS);
1880	}
1881
1882	sc->sc_seqnum = 0;
1883	if (uath_tx_start(sc, m, ni, bf) != 0) {
1884		ieee80211_free_node(ni);
1885		ifp->if_oerrors++;
1886		STAILQ_INSERT_HEAD(&sc->sc_tx_inactive, bf, next);
1887		UATH_STAT_INC(sc, st_tx_inactive);
1888		UATH_UNLOCK(sc);
1889		return (EIO);
1890	}
1891	UATH_UNLOCK(sc);
1892
1893	sc->sc_tx_timer = 5;
1894	return (0);
1895}
1896
1897static void
1898uath_scan_start(struct ieee80211com *ic)
1899{
1900	/* do nothing  */
1901}
1902
1903static void
1904uath_scan_end(struct ieee80211com *ic)
1905{
1906	/* do nothing  */
1907}
1908
1909static void
1910uath_set_channel(struct ieee80211com *ic)
1911{
1912	struct ifnet *ifp = ic->ic_ifp;
1913	struct uath_softc *sc = ifp->if_softc;
1914
1915	UATH_LOCK(sc);
1916	(void)uath_switch_channel(sc, ic->ic_curchan);
1917	UATH_UNLOCK(sc);
1918}
1919
1920static int
1921uath_set_rxmulti_filter(struct uath_softc *sc)
1922{
1923
1924	return (0);
1925}
1926static void
1927uath_update_mcast(struct ifnet *ifp)
1928{
1929	struct uath_softc *sc = ifp->if_softc;
1930
1931	/*
1932	 * this is for avoiding the race condition when we're try to
1933	 * connect to the AP with WPA.
1934	 */
1935	if (!(sc->sc_flags & UATH_FLAG_INITDONE))
1936		return;
1937	(void)uath_set_rxmulti_filter(sc);
1938}
1939
1940static void
1941uath_update_promisc(struct ifnet *ifp)
1942{
1943	struct uath_softc *sc = ifp->if_softc;
1944
1945	if (!(sc->sc_flags & UATH_FLAG_INITDONE))
1946		return;
1947	uath_set_rxfilter(sc,
1948	    UATH_FILTER_RX_UCAST | UATH_FILTER_RX_MCAST |
1949	    UATH_FILTER_RX_BCAST | UATH_FILTER_RX_BEACON |
1950	    UATH_FILTER_RX_PROM, UATH_FILTER_OP_SET);
1951}
1952
1953static int
1954uath_create_connection(struct uath_softc *sc, uint32_t connid)
1955{
1956	const struct ieee80211_rateset *rs;
1957	struct ieee80211com *ic = sc->sc_ifp->if_l2com;
1958	struct ieee80211vap *vap = TAILQ_FIRST(&ic->ic_vaps);
1959	struct ieee80211_node *ni = vap->iv_bss;
1960	struct uath_cmd_create_connection create;
1961
1962	bzero(&create, sizeof create);
1963	create.connid = htobe32(connid);
1964	create.bssid = htobe32(0);
1965	/* XXX packed or not?  */
1966	create.size = htobe32(sizeof(struct uath_cmd_rateset));
1967
1968	rs = &ni->ni_rates;
1969	create.connattr.rateset.length = rs->rs_nrates;
1970	bcopy(rs->rs_rates, &create.connattr.rateset.set[0],
1971	    rs->rs_nrates);
1972
1973	/* XXX turbo */
1974	if (IEEE80211_IS_CHAN_A(ni->ni_chan))
1975		create.connattr.wlanmode = htobe32(WLAN_MODE_11a);
1976	else if (IEEE80211_IS_CHAN_ANYG(ni->ni_chan))
1977		create.connattr.wlanmode = htobe32(WLAN_MODE_11g);
1978	else
1979		create.connattr.wlanmode = htobe32(WLAN_MODE_11b);
1980
1981	return uath_cmd_write(sc, WDCMSG_CREATE_CONNECTION, &create,
1982	    sizeof create, 0);
1983}
1984
1985static int
1986uath_set_rates(struct uath_softc *sc, const struct ieee80211_rateset *rs)
1987{
1988	struct uath_cmd_rates rates;
1989
1990	bzero(&rates, sizeof rates);
1991	rates.connid = htobe32(UATH_ID_BSS);		/* XXX */
1992	rates.size   = htobe32(sizeof(struct uath_cmd_rateset));
1993	/* XXX bounds check rs->rs_nrates */
1994	rates.rateset.length = rs->rs_nrates;
1995	bcopy(rs->rs_rates, &rates.rateset.set[0], rs->rs_nrates);
1996
1997	DPRINTF(sc, UATH_DEBUG_RATES,
1998	    "setting supported rates nrates=%d\n", rs->rs_nrates);
1999	return uath_cmd_write(sc, WDCMSG_SET_BASIC_RATE,
2000	    &rates, sizeof rates, 0);
2001}
2002
2003static int
2004uath_write_associd(struct uath_softc *sc)
2005{
2006	struct ieee80211com *ic = sc->sc_ifp->if_l2com;
2007	struct ieee80211vap *vap = TAILQ_FIRST(&ic->ic_vaps);
2008	struct ieee80211_node *ni = vap->iv_bss;
2009	struct uath_cmd_set_associd associd;
2010
2011	bzero(&associd, sizeof associd);
2012	associd.defaultrateix = htobe32(1);	/* XXX */
2013	associd.associd = htobe32(ni->ni_associd);
2014	associd.timoffset = htobe32(0x3b);	/* XXX */
2015	IEEE80211_ADDR_COPY(associd.bssid, ni->ni_bssid);
2016	return uath_cmd_write(sc, WDCMSG_WRITE_ASSOCID, &associd,
2017	    sizeof associd, 0);
2018}
2019
2020static int
2021uath_set_ledsteady(struct uath_softc *sc, int lednum, int ledmode)
2022{
2023	struct uath_cmd_ledsteady led;
2024
2025	led.lednum = htobe32(lednum);
2026	led.ledmode = htobe32(ledmode);
2027
2028	DPRINTF(sc, UATH_DEBUG_LED, "set %s led %s (steady)\n",
2029	    (lednum == UATH_LED_LINK) ? "link" : "activity",
2030	    ledmode ? "on" : "off");
2031	return uath_cmd_write(sc, WDCMSG_SET_LED_STEADY, &led, sizeof led, 0);
2032}
2033
2034static int
2035uath_set_ledblink(struct uath_softc *sc, int lednum, int ledmode,
2036	int blinkrate, int slowmode)
2037{
2038	struct uath_cmd_ledblink led;
2039
2040	led.lednum = htobe32(lednum);
2041	led.ledmode = htobe32(ledmode);
2042	led.blinkrate = htobe32(blinkrate);
2043	led.slowmode = htobe32(slowmode);
2044
2045	DPRINTF(sc, UATH_DEBUG_LED, "set %s led %s (blink)\n",
2046	    (lednum == UATH_LED_LINK) ? "link" : "activity",
2047	    ledmode ? "on" : "off");
2048	return uath_cmd_write(sc, WDCMSG_SET_LED_BLINK, &led, sizeof led, 0);
2049}
2050
2051static int
2052uath_newstate(struct ieee80211vap *vap, enum ieee80211_state nstate, int arg)
2053{
2054	enum ieee80211_state ostate = vap->iv_state;
2055	int error;
2056	struct ieee80211_node *ni = vap->iv_bss;
2057	struct ieee80211com *ic = vap->iv_ic;
2058	struct uath_softc *sc = ic->ic_ifp->if_softc;
2059	struct uath_vap *uvp = UATH_VAP(vap);
2060
2061	DPRINTF(sc, UATH_DEBUG_STATE,
2062	    "%s: %s -> %s\n", __func__, ieee80211_state_name[vap->iv_state],
2063	    ieee80211_state_name[nstate]);
2064
2065	IEEE80211_UNLOCK(ic);
2066	UATH_LOCK(sc);
2067	callout_stop(&sc->stat_ch);
2068	callout_stop(&sc->watchdog_ch);
2069
2070	switch (nstate) {
2071	case IEEE80211_S_INIT:
2072		if (ostate == IEEE80211_S_RUN) {
2073			/* turn link and activity LEDs off */
2074			uath_set_ledstate(sc, 0);
2075		}
2076		break;
2077
2078	case IEEE80211_S_SCAN:
2079		break;
2080
2081	case IEEE80211_S_AUTH:
2082		/* XXX good place?  set RTS threshold  */
2083		uath_config(sc, CFG_USER_RTS_THRESHOLD, vap->iv_rtsthreshold);
2084		/* XXX bad place  */
2085		error = uath_set_keys(sc, vap);
2086		if (error != 0) {
2087			device_printf(sc->sc_dev,
2088			    "could not set crypto keys, error %d\n", error);
2089			break;
2090		}
2091		if (uath_switch_channel(sc, ni->ni_chan) != 0) {
2092			device_printf(sc->sc_dev, "could not switch channel\n");
2093			break;
2094		}
2095		if (uath_create_connection(sc, UATH_ID_BSS) != 0) {
2096			device_printf(sc->sc_dev,
2097			    "could not create connection\n");
2098			break;
2099		}
2100		break;
2101
2102	case IEEE80211_S_ASSOC:
2103		if (uath_set_rates(sc, &ni->ni_rates) != 0) {
2104			device_printf(sc->sc_dev,
2105			    "could not set negotiated rate set\n");
2106			break;
2107		}
2108		break;
2109
2110	case IEEE80211_S_RUN:
2111		/* XXX monitor mode doesn't be tested  */
2112		if (ic->ic_opmode == IEEE80211_M_MONITOR) {
2113			uath_set_ledstate(sc, 1);
2114			break;
2115		}
2116
2117		/*
2118		 * Tx rate is controlled by firmware, report the maximum
2119		 * negotiated rate in ifconfig output.
2120		 */
2121		ni->ni_txrate = ni->ni_rates.rs_rates[ni->ni_rates.rs_nrates-1];
2122
2123		if (uath_write_associd(sc) != 0) {
2124			device_printf(sc->sc_dev,
2125			    "could not write association id\n");
2126			break;
2127		}
2128		/* turn link LED on */
2129		uath_set_ledsteady(sc, UATH_LED_LINK, UATH_LED_ON);
2130		/* make activity LED blink */
2131		uath_set_ledblink(sc, UATH_LED_ACTIVITY, UATH_LED_ON, 1, 2);
2132		/* set state to associated */
2133		uath_set_ledstate(sc, 1);
2134
2135		/* start statistics timer */
2136		callout_reset(&sc->stat_ch, hz, uath_stat, sc);
2137		break;
2138	default:
2139		break;
2140	}
2141	UATH_UNLOCK(sc);
2142	IEEE80211_LOCK(ic);
2143	return (uvp->newstate(vap, nstate, arg));
2144}
2145
2146static int
2147uath_set_key(struct uath_softc *sc, const struct ieee80211_key *wk,
2148    int index)
2149{
2150#if 0
2151	struct uath_cmd_crypto crypto;
2152	int i;
2153
2154	bzero(&crypto, sizeof crypto);
2155	crypto.keyidx = htobe32(index);
2156	crypto.magic1 = htobe32(1);
2157	crypto.size   = htobe32(368);
2158	crypto.mask   = htobe32(0xffff);
2159	crypto.flags  = htobe32(0x80000068);
2160	if (index != UATH_DEFAULT_KEY)
2161		crypto.flags |= htobe32(index << 16);
2162	memset(crypto.magic2, 0xff, sizeof crypto.magic2);
2163
2164	/*
2165	 * Each byte of the key must be XOR'ed with 10101010 before being
2166	 * transmitted to the firmware.
2167	 */
2168	for (i = 0; i < wk->wk_keylen; i++)
2169		crypto.key[i] = wk->wk_key[i] ^ 0xaa;
2170
2171	DPRINTF(sc, UATH_DEBUG_CRYPTO,
2172	    "setting crypto key index=%d len=%d\n", index, wk->wk_keylen);
2173	return uath_cmd_write(sc, WDCMSG_SET_KEY_CACHE_ENTRY, &crypto,
2174	    sizeof crypto, 0);
2175#else
2176	/* XXX support H/W cryto  */
2177	return (0);
2178#endif
2179}
2180
2181static int
2182uath_set_keys(struct uath_softc *sc, struct ieee80211vap *vap)
2183{
2184	int i, error;
2185
2186	error = 0;
2187	for (i = 0; i < IEEE80211_WEP_NKID; i++) {
2188		const struct ieee80211_key *wk = &vap->iv_nw_keys[i];
2189
2190		if (wk->wk_flags & (IEEE80211_KEY_XMIT|IEEE80211_KEY_RECV)) {
2191			error = uath_set_key(sc, wk, i);
2192			if (error)
2193				return (error);
2194		}
2195	}
2196	if (vap->iv_def_txkey != IEEE80211_KEYIX_NONE) {
2197		error = uath_set_key(sc, &vap->iv_nw_keys[vap->iv_def_txkey],
2198			UATH_DEFAULT_KEY);
2199	}
2200	return (error);
2201}
2202
2203#define	UATH_SYSCTL_STAT_ADD32(c, h, n, p, d)	\
2204	    SYSCTL_ADD_UINT(c, h, OID_AUTO, n, CTLFLAG_RD, p, 0, d)
2205
2206static void
2207uath_sysctl_node(struct uath_softc *sc)
2208{
2209	struct sysctl_ctx_list *ctx;
2210	struct sysctl_oid_list *child;
2211	struct sysctl_oid *tree;
2212	struct uath_stat *stats;
2213
2214	stats = &sc->sc_stat;
2215	ctx = device_get_sysctl_ctx(sc->sc_dev);
2216	child = SYSCTL_CHILDREN(device_get_sysctl_tree(sc->sc_dev));
2217
2218	tree = SYSCTL_ADD_NODE(ctx, child, OID_AUTO, "stats", CTLFLAG_RD,
2219	    NULL, "UATH statistics");
2220	child = SYSCTL_CHILDREN(tree);
2221	UATH_SYSCTL_STAT_ADD32(ctx, child, "badchunkseqnum",
2222	    &stats->st_badchunkseqnum, "Bad chunk sequence numbers");
2223	UATH_SYSCTL_STAT_ADD32(ctx, child, "invalidlen", &stats->st_invalidlen,
2224	    "Invalid length");
2225	UATH_SYSCTL_STAT_ADD32(ctx, child, "multichunk", &stats->st_multichunk,
2226	    "Multi chunks");
2227	UATH_SYSCTL_STAT_ADD32(ctx, child, "toobigrxpkt",
2228	    &stats->st_toobigrxpkt, "Too big rx packets");
2229	UATH_SYSCTL_STAT_ADD32(ctx, child, "stopinprogress",
2230	    &stats->st_stopinprogress, "Stop in progress");
2231	UATH_SYSCTL_STAT_ADD32(ctx, child, "crcerrs", &stats->st_crcerr,
2232	    "CRC errors");
2233	UATH_SYSCTL_STAT_ADD32(ctx, child, "phyerr", &stats->st_phyerr,
2234	    "PHY errors");
2235	UATH_SYSCTL_STAT_ADD32(ctx, child, "decrypt_crcerr",
2236	    &stats->st_decrypt_crcerr, "Decryption CRC errors");
2237	UATH_SYSCTL_STAT_ADD32(ctx, child, "decrypt_micerr",
2238	    &stats->st_decrypt_micerr, "Decryption Misc errors");
2239	UATH_SYSCTL_STAT_ADD32(ctx, child, "decomperr", &stats->st_decomperr,
2240	    "Decomp errors");
2241	UATH_SYSCTL_STAT_ADD32(ctx, child, "keyerr", &stats->st_keyerr,
2242	    "Key errors");
2243	UATH_SYSCTL_STAT_ADD32(ctx, child, "err", &stats->st_err,
2244	    "Unknown errors");
2245
2246	UATH_SYSCTL_STAT_ADD32(ctx, child, "cmd_active",
2247	    &stats->st_cmd_active, "Active numbers in Command queue");
2248	UATH_SYSCTL_STAT_ADD32(ctx, child, "cmd_inactive",
2249	    &stats->st_cmd_inactive, "Inactive numbers in Command queue");
2250	UATH_SYSCTL_STAT_ADD32(ctx, child, "cmd_pending",
2251	    &stats->st_cmd_pending, "Pending numbers in Command queue");
2252	UATH_SYSCTL_STAT_ADD32(ctx, child, "cmd_waiting",
2253	    &stats->st_cmd_waiting, "Waiting numbers in Command queue");
2254	UATH_SYSCTL_STAT_ADD32(ctx, child, "rx_active",
2255	    &stats->st_rx_active, "Active numbers in RX queue");
2256	UATH_SYSCTL_STAT_ADD32(ctx, child, "rx_inactive",
2257	    &stats->st_rx_inactive, "Inactive numbers in RX queue");
2258	UATH_SYSCTL_STAT_ADD32(ctx, child, "tx_active",
2259	    &stats->st_tx_active, "Active numbers in TX queue");
2260	UATH_SYSCTL_STAT_ADD32(ctx, child, "tx_inactive",
2261	    &stats->st_tx_inactive, "Inactive numbers in TX queue");
2262	UATH_SYSCTL_STAT_ADD32(ctx, child, "tx_pending",
2263	    &stats->st_tx_pending, "Pending numbers in TX queue");
2264}
2265
2266#undef UATH_SYSCTL_STAT_ADD32
2267
2268static void
2269uath_cmdeof(struct uath_softc *sc, struct uath_cmd *cmd)
2270{
2271	struct uath_cmd_hdr *hdr;
2272	int dlen;
2273
2274	hdr = (struct uath_cmd_hdr *)cmd->buf;
2275	/* NB: msgid is passed thru w/o byte swapping */
2276#ifdef UATH_DEBUG
2277	if (sc->sc_debug & UATH_DEBUG_CMDS) {
2278		int len = be32toh(hdr->len);
2279		printf("%s: %s [ix %u] len %u status %u\n",
2280		    __func__, uath_codename(be32toh(hdr->code)),
2281		    hdr->msgid, len, be32toh(hdr->magic));
2282		if (sc->sc_debug & UATH_DEBUG_CMDS_DUMP)
2283			uath_dump_cmd(cmd->buf,
2284			    len > UATH_MAX_CMDSZ ? sizeof(*hdr) : len, '-');
2285	}
2286#endif
2287	hdr->code = be32toh(hdr->code);
2288	hdr->len = be32toh(hdr->len);
2289	hdr->magic = be32toh(hdr->magic);	/* target status on return */
2290
2291	switch (hdr->code & 0xff) {
2292	/* reply to a read command */
2293	default:
2294		dlen = hdr->len - sizeof(*hdr);
2295		DPRINTF(sc, UATH_DEBUG_RX_PROC | UATH_DEBUG_RECV_ALL,
2296		    "%s: code %d data len %u\n",
2297		    __func__, hdr->code & 0xff, dlen);
2298		/*
2299		 * The first response from the target after the
2300		 * HOST_AVAILABLE has an invalid msgid so we must
2301		 * treat it specially.
2302		 */
2303		if (hdr->msgid < UATH_CMD_LIST_COUNT) {
2304			uint32_t *rp = (uint32_t *)(hdr+1);
2305			u_int olen;
2306
2307			if (!(sizeof(*hdr) <= hdr->len &&
2308			      hdr->len < UATH_MAX_CMDSZ)) {
2309				device_printf(sc->sc_dev,
2310				    "%s: invalid WDC msg length %u; "
2311				    "msg ignored\n", __func__, hdr->len);
2312				return;
2313			}
2314			/*
2315			 * Calculate return/receive payload size; the
2316			 * first word, if present, always gives the
2317			 * number of bytes--unless it's 0 in which
2318			 * case a single 32-bit word should be present.
2319			 */
2320			if (dlen >= sizeof(uint32_t)) {
2321				olen = be32toh(rp[0]);
2322				dlen -= sizeof(uint32_t);
2323				if (olen == 0) {
2324					/* convention is 0 =>'s one word */
2325					olen = sizeof(uint32_t);
2326					/* XXX KASSERT(olen == dlen ) */
2327				}
2328			} else
2329				olen = 0;
2330			if (cmd->odata != NULL) {
2331				/* NB: cmd->olen validated in uath_cmd */
2332				if (olen > cmd->olen) {
2333					/* XXX complain? */
2334					device_printf(sc->sc_dev,
2335					    "%s: cmd 0x%x olen %u cmd olen %u\n",
2336					    __func__, hdr->code, olen,
2337					    cmd->olen);
2338					olen = cmd->olen;
2339				}
2340				if (olen > dlen) {
2341					/* XXX complain, shouldn't happen */
2342					device_printf(sc->sc_dev,
2343					    "%s: cmd 0x%x olen %u dlen %u\n",
2344					    __func__, hdr->code, olen, dlen);
2345					olen = dlen;
2346				}
2347				/* XXX have submitter do this */
2348				/* copy answer into caller's supplied buffer */
2349				bcopy(&rp[1], cmd->odata, olen);
2350				cmd->olen = olen;
2351			}
2352		}
2353		wakeup_one(cmd);		/* wake up caller */
2354		break;
2355
2356	case WDCMSG_TARGET_START:
2357		if (hdr->msgid >= UATH_CMD_LIST_COUNT) {
2358			/* XXX */
2359			return;
2360		}
2361		dlen = hdr->len - sizeof(*hdr);
2362		if (dlen != sizeof(uint32_t)) {
2363			/* XXX something wrong */
2364			return;
2365		}
2366		/* XXX have submitter do this */
2367		/* copy answer into caller's supplied buffer */
2368		bcopy(hdr+1, cmd->odata, sizeof(uint32_t));
2369		cmd->olen = sizeof(uint32_t);
2370		wakeup_one(cmd);		/* wake up caller */
2371		break;
2372
2373	case WDCMSG_SEND_COMPLETE:
2374		/* this notification is sent when UATH_TX_NOTIFY is set */
2375		DPRINTF(sc, UATH_DEBUG_RX_PROC | UATH_DEBUG_RECV_ALL,
2376		    "%s: received Tx notification\n", __func__);
2377		break;
2378
2379	case WDCMSG_TARGET_GET_STATS:
2380		DPRINTF(sc, UATH_DEBUG_RX_PROC | UATH_DEBUG_RECV_ALL,
2381		    "%s: received device statistics\n", __func__);
2382		callout_reset(&sc->stat_ch, hz, uath_stat, sc);
2383		break;
2384	}
2385}
2386
2387static void
2388uath_intr_rx_callback(struct usb2_xfer *xfer)
2389{
2390	struct uath_softc *sc = xfer->priv_sc;
2391	struct uath_cmd *cmd;
2392
2393	UATH_ASSERT_LOCKED(sc);
2394
2395	switch (USB_GET_STATE(xfer)) {
2396	case USB_ST_TRANSFERRED:
2397		cmd = STAILQ_FIRST(&sc->sc_cmd_waiting);
2398		if (cmd == NULL)
2399			goto setup;
2400		STAILQ_REMOVE_HEAD(&sc->sc_cmd_waiting, next);
2401		UATH_STAT_DEC(sc, st_cmd_waiting);
2402		STAILQ_INSERT_TAIL(&sc->sc_cmd_inactive, cmd, next);
2403		UATH_STAT_INC(sc, st_cmd_inactive);
2404
2405		KASSERT(xfer->actlen >= sizeof(struct uath_cmd_hdr),
2406		    ("short xfer error"));
2407		usb2_copy_out(xfer->frbuffers, 0, cmd->buf, xfer->actlen);
2408		uath_cmdeof(sc, cmd);
2409	case USB_ST_SETUP:
2410setup:
2411		xfer->frlengths[0] = xfer->max_data_length;
2412		usb2_start_hardware(xfer);
2413		break;
2414	default:
2415		if (xfer->error != USB_ERR_CANCELLED) {
2416			xfer->flags.stall_pipe = 1;
2417			goto setup;
2418		}
2419		break;
2420	}
2421}
2422
2423static void
2424uath_intr_tx_callback(struct usb2_xfer *xfer)
2425{
2426	struct uath_softc *sc = xfer->priv_sc;
2427	struct uath_cmd *cmd;
2428
2429	UATH_ASSERT_LOCKED(sc);
2430
2431	switch (USB_GET_STATE(xfer)) {
2432	case USB_ST_TRANSFERRED:
2433		cmd = STAILQ_FIRST(&sc->sc_cmd_active);
2434		if (cmd == NULL)
2435			goto setup;
2436		STAILQ_REMOVE_HEAD(&sc->sc_cmd_active, next);
2437		UATH_STAT_DEC(sc, st_cmd_active);
2438		STAILQ_INSERT_TAIL((cmd->flags & UATH_CMD_FLAG_READ) ?
2439		    &sc->sc_cmd_waiting : &sc->sc_cmd_inactive, cmd, next);
2440		if (cmd->flags & UATH_CMD_FLAG_READ)
2441			UATH_STAT_INC(sc, st_cmd_waiting);
2442		else
2443			UATH_STAT_INC(sc, st_cmd_inactive);
2444		/* FALLTHROUGH */
2445	case USB_ST_SETUP:
2446setup:
2447		cmd = STAILQ_FIRST(&sc->sc_cmd_pending);
2448		if (cmd == NULL) {
2449			DPRINTF(sc, UATH_DEBUG_XMIT, "%s: empty pending queue\n",
2450			    __func__);
2451			return;
2452		}
2453		STAILQ_REMOVE_HEAD(&sc->sc_cmd_pending, next);
2454		UATH_STAT_DEC(sc, st_cmd_pending);
2455		STAILQ_INSERT_TAIL((cmd->flags & UATH_CMD_FLAG_ASYNC) ?
2456		    &sc->sc_cmd_inactive : &sc->sc_cmd_active, cmd, next);
2457		if (cmd->flags & UATH_CMD_FLAG_ASYNC)
2458			UATH_STAT_INC(sc, st_cmd_inactive);
2459		else
2460			UATH_STAT_INC(sc, st_cmd_active);
2461
2462		usb2_set_frame_data(xfer, cmd->buf, 0);
2463		xfer->frlengths[0] = cmd->buflen;
2464		usb2_start_hardware(xfer);
2465		break;
2466	default:
2467		if (xfer->error != USB_ERR_CANCELLED) {
2468			xfer->flags.stall_pipe = 1;
2469			goto setup;
2470		}
2471		break;
2472	}
2473}
2474
2475static void
2476uath_update_rxstat(struct uath_softc *sc, uint32_t status)
2477{
2478
2479	switch (status) {
2480	case UATH_STATUS_STOP_IN_PROGRESS:
2481		UATH_STAT_INC(sc, st_stopinprogress);
2482		break;
2483	case UATH_STATUS_CRC_ERR:
2484		UATH_STAT_INC(sc, st_crcerr);
2485		break;
2486	case UATH_STATUS_PHY_ERR:
2487		UATH_STAT_INC(sc, st_phyerr);
2488		break;
2489	case UATH_STATUS_DECRYPT_CRC_ERR:
2490		UATH_STAT_INC(sc, st_decrypt_crcerr);
2491		break;
2492	case UATH_STATUS_DECRYPT_MIC_ERR:
2493		UATH_STAT_INC(sc, st_decrypt_micerr);
2494		break;
2495	case UATH_STATUS_DECOMP_ERR:
2496		UATH_STAT_INC(sc, st_decomperr);
2497		break;
2498	case UATH_STATUS_KEY_ERR:
2499		UATH_STAT_INC(sc, st_keyerr);
2500		break;
2501	case UATH_STATUS_ERR:
2502		UATH_STAT_INC(sc, st_err);
2503		break;
2504	default:
2505		break;
2506	}
2507}
2508
2509static struct mbuf *
2510uath_data_rxeof(struct usb2_xfer *xfer, struct uath_data *data,
2511    struct uath_rx_desc **pdesc)
2512{
2513	struct uath_softc *sc = xfer->priv_sc;
2514	struct ifnet *ifp = sc->sc_ifp;
2515	struct ieee80211com *ic = ifp->if_l2com;
2516	struct uath_chunk *chunk;
2517	struct uath_rx_desc *desc;
2518	struct mbuf *m = data->m, *mnew, *mp;
2519	uint16_t chunklen;
2520
2521	if (xfer->actlen < UATH_MIN_RXBUFSZ) {
2522		DPRINTF(sc, UATH_DEBUG_RECV | UATH_DEBUG_RECV_ALL,
2523		    "%s: wrong xfer size (len=%d)\n", __func__, xfer->actlen);
2524		ifp->if_ierrors++;
2525		return (NULL);
2526	}
2527
2528	chunk = (struct uath_chunk *)data->buf;
2529	if (chunk->seqnum == 0 && chunk->flags == 0 && chunk->length == 0) {
2530		device_printf(sc->sc_dev, "%s: strange response\n", __func__);
2531		ifp->if_ierrors++;
2532		UATH_RESET_INTRX(sc);
2533		return (NULL);
2534	}
2535
2536	if (chunk->seqnum != sc->sc_intrx_nextnum) {
2537		DPRINTF(sc, UATH_DEBUG_XMIT, "invalid seqnum %d, expected %d\n",
2538		    chunk->seqnum, sc->sc_intrx_nextnum);
2539		UATH_STAT_INC(sc, st_badchunkseqnum);
2540		if (sc->sc_intrx_head != NULL)
2541			m_freem(sc->sc_intrx_head);
2542		UATH_RESET_INTRX(sc);
2543		return (NULL);
2544	}
2545
2546	/* check multi-chunk frames  */
2547	if ((chunk->seqnum == 0 && !(chunk->flags & UATH_CFLAGS_FINAL)) ||
2548	    (chunk->seqnum != 0 && (chunk->flags & UATH_CFLAGS_FINAL)) ||
2549	    chunk->flags & UATH_CFLAGS_RXMSG)
2550		UATH_STAT_INC(sc, st_multichunk);
2551
2552	chunklen = be16toh(chunk->length);
2553	if (chunk->flags & UATH_CFLAGS_FINAL)
2554		chunklen -= sizeof(struct uath_rx_desc);
2555
2556	if (chunklen > 0 &&
2557	    (!(chunk->flags & UATH_CFLAGS_FINAL) || !(chunk->seqnum == 0))) {
2558		/* we should use intermediate RX buffer  */
2559		if (chunk->seqnum == 0)
2560			UATH_RESET_INTRX(sc);
2561		if ((sc->sc_intrx_len + sizeof(struct uath_rx_desc) +
2562		    chunklen) > UATH_MAX_INTRX_SIZE) {
2563			UATH_STAT_INC(sc, st_invalidlen);
2564			ifp->if_iqdrops++;
2565			if (sc->sc_intrx_head != NULL)
2566				m_freem(sc->sc_intrx_head);
2567			UATH_RESET_INTRX(sc);
2568			return (NULL);
2569		}
2570
2571		m->m_len = chunklen;
2572		m->m_data += sizeof(struct uath_chunk);
2573
2574		if (sc->sc_intrx_head == NULL) {
2575			sc->sc_intrx_head = m;
2576			sc->sc_intrx_tail = m;
2577		} else {
2578			m->m_flags &= ~M_PKTHDR;
2579			sc->sc_intrx_tail->m_next = m;
2580			sc->sc_intrx_tail = m;
2581		}
2582	}
2583	sc->sc_intrx_len += chunklen;
2584
2585	mnew = m_getcl(M_DONTWAIT, MT_DATA, M_PKTHDR);
2586	if (mnew == NULL) {
2587		DPRINTF(sc, UATH_DEBUG_RECV | UATH_DEBUG_RECV_ALL,
2588		    "%s: can't get new mbuf, drop frame\n", __func__);
2589		ifp->if_ierrors++;
2590		if (sc->sc_intrx_head != NULL)
2591			m_freem(sc->sc_intrx_head);
2592		UATH_RESET_INTRX(sc);
2593		return (NULL);
2594	}
2595
2596	data->m = mnew;
2597	data->buf = mtod(mnew, uint8_t *);
2598
2599	/* if the frame is not final continue the transfer  */
2600	if (!(chunk->flags & UATH_CFLAGS_FINAL)) {
2601		sc->sc_intrx_nextnum++;
2602		UATH_RESET_INTRX(sc);
2603		return (NULL);
2604	}
2605
2606	/*
2607	 * if the frame is not set UATH_CFLAGS_RXMSG, then rx descriptor is
2608	 * located at the end, 32-bit aligned
2609	 */
2610	desc = (chunk->flags & UATH_CFLAGS_RXMSG) ?
2611		(struct uath_rx_desc *)(chunk + 1) :
2612		(struct uath_rx_desc *)(((uint8_t *)chunk) +
2613		    sizeof(struct uath_chunk) + be16toh(chunk->length) -
2614		    sizeof(struct uath_rx_desc));
2615	*pdesc = desc;
2616
2617	DPRINTF(sc, UATH_DEBUG_RECV | UATH_DEBUG_RECV_ALL,
2618	    "%s: frame len %u code %u status %u rate %u antenna %u "
2619	    "rssi %d channel %u phyerror %u connix %u decrypterror %u "
2620	    "keycachemiss %u\n", __func__, be32toh(desc->framelen)
2621	    , be32toh(desc->code), be32toh(desc->status), be32toh(desc->rate)
2622	    , be32toh(desc->antenna), be32toh(desc->rssi), be32toh(desc->channel)
2623	    , be32toh(desc->phyerror), be32toh(desc->connix)
2624	    , be32toh(desc->decrypterror), be32toh(desc->keycachemiss));
2625
2626	if (be32toh(desc->len) > MCLBYTES) {
2627		DPRINTF(sc, UATH_DEBUG_RECV | UATH_DEBUG_RECV_ALL,
2628		    "%s: bad descriptor (len=%d)\n", __func__,
2629		    be32toh(desc->len));
2630		ifp->if_iqdrops++;
2631		UATH_STAT_INC(sc, st_toobigrxpkt);
2632		if (sc->sc_intrx_head != NULL)
2633			m_freem(sc->sc_intrx_head);
2634		UATH_RESET_INTRX(sc);
2635		return (NULL);
2636	}
2637
2638	uath_update_rxstat(sc, be32toh(desc->status));
2639
2640	/* finalize mbuf */
2641	if (sc->sc_intrx_head == NULL) {
2642		m->m_pkthdr.rcvif = ifp;
2643		m->m_pkthdr.len = m->m_len =
2644			be32toh(desc->framelen) - UATH_RX_DUMMYSIZE;
2645		m->m_data += sizeof(struct uath_chunk);
2646	} else {
2647		mp = sc->sc_intrx_head;
2648		mp->m_pkthdr.rcvif = ifp;
2649		mp->m_flags |= M_PKTHDR;
2650		mp->m_pkthdr.len = sc->sc_intrx_len;
2651		m = mp;
2652	}
2653
2654	/* there are a lot more fields in the RX descriptor */
2655	if (bpf_peers_present(ifp->if_bpf)) {
2656		struct uath_rx_radiotap_header *tap = &sc->sc_rxtap;
2657
2658		tap->wr_chan_freq = htole16(be32toh(desc->channel));
2659		tap->wr_chan_flags = htole16(ic->ic_curchan->ic_flags);
2660		tap->wr_dbm_antsignal = (int8_t)be32toh(desc->rssi);
2661
2662		bpf_mtap2(ifp->if_bpf, tap, sc->sc_rxtap_len, m);
2663	}
2664
2665	ifp->if_ipackets++;
2666	UATH_RESET_INTRX(sc);
2667
2668	return (m);
2669}
2670
2671static void
2672uath_bulk_rx_callback(struct usb2_xfer *xfer)
2673{
2674	struct uath_softc *sc = xfer->priv_sc;
2675	struct ifnet *ifp = sc->sc_ifp;
2676	struct ieee80211com *ic = ifp->if_l2com;
2677	struct ieee80211_frame *wh;
2678	struct ieee80211_node *ni;
2679	struct mbuf *m = NULL;
2680	struct uath_data *data;
2681	struct uath_rx_desc *desc = NULL;
2682	int8_t nf;
2683
2684	UATH_ASSERT_LOCKED(sc);
2685
2686	switch (USB_GET_STATE(xfer)) {
2687	case USB_ST_TRANSFERRED:
2688		data = STAILQ_FIRST(&sc->sc_rx_active);
2689		if (data == NULL)
2690			goto setup;
2691		STAILQ_REMOVE_HEAD(&sc->sc_rx_active, next);
2692		UATH_STAT_DEC(sc, st_rx_active);
2693		m = uath_data_rxeof(xfer, data, &desc);
2694		STAILQ_INSERT_TAIL(&sc->sc_rx_inactive, data, next);
2695		UATH_STAT_INC(sc, st_rx_inactive);
2696		/* FALLTHROUGH */
2697	case USB_ST_SETUP:
2698setup:
2699		data = STAILQ_FIRST(&sc->sc_rx_inactive);
2700		if (data == NULL)
2701			return;
2702		STAILQ_REMOVE_HEAD(&sc->sc_rx_inactive, next);
2703		UATH_STAT_DEC(sc, st_rx_inactive);
2704		STAILQ_INSERT_TAIL(&sc->sc_rx_active, data, next);
2705		UATH_STAT_INC(sc, st_rx_active);
2706		usb2_set_frame_data(xfer, data->buf, 0);
2707		xfer->frlengths[0] = xfer->max_data_length;
2708		usb2_start_hardware(xfer);
2709
2710		/*
2711		 * To avoid LOR we should unlock our private mutex here to call
2712		 * ieee80211_input() because here is at the end of a USB
2713		 * callback and safe to unlock.
2714		 */
2715		UATH_UNLOCK(sc);
2716		if (m != NULL && desc != NULL) {
2717			wh = mtod(m, struct ieee80211_frame *);
2718			ni = ieee80211_find_rxnode(ic,
2719			    (struct ieee80211_frame_min *)wh);
2720			nf = -95;	/* XXX */
2721			if (ni != NULL) {
2722				(void) ieee80211_input(ni, m,
2723				    (int)be32toh(desc->rssi), nf, 0);
2724				/* node is no longer needed */
2725				ieee80211_free_node(ni);
2726			} else
2727				(void) ieee80211_input_all(ic, m,
2728				    (int)be32toh(desc->rssi), nf, 0);
2729			m = NULL;
2730			desc = NULL;
2731		}
2732		UATH_LOCK(sc);
2733		break;
2734	default:
2735		/* needs it to the inactive queue due to a error.  */
2736		data = STAILQ_FIRST(&sc->sc_rx_active);
2737		if (data != NULL) {
2738			STAILQ_REMOVE_HEAD(&sc->sc_rx_active, next);
2739			UATH_STAT_DEC(sc, st_rx_active);
2740			STAILQ_INSERT_TAIL(&sc->sc_rx_inactive, data, next);
2741			UATH_STAT_INC(sc, st_rx_inactive);
2742		}
2743		if (xfer->error != USB_ERR_CANCELLED) {
2744			xfer->flags.stall_pipe = 1;
2745			ifp->if_ierrors++;
2746			goto setup;
2747		}
2748		break;
2749	}
2750}
2751
2752static void
2753uath_data_txeof(struct usb2_xfer *xfer, struct uath_data *data)
2754{
2755	struct uath_softc *sc = xfer->priv_sc;
2756	struct ifnet *ifp = sc->sc_ifp;
2757	struct mbuf *m;
2758
2759	UATH_ASSERT_LOCKED(sc);
2760
2761	/*
2762	 * Do any tx complete callback.  Note this must be done before releasing
2763	 * the node reference.
2764	 */
2765	if (data->m) {
2766		m = data->m;
2767		if (m->m_flags & M_TXCB) {
2768			/* XXX status? */
2769			ieee80211_process_callback(data->ni, m, 0);
2770		}
2771		m_freem(m);
2772		data->m = NULL;
2773	}
2774	if (data->ni) {
2775		ieee80211_free_node(data->ni);
2776		data->ni = NULL;
2777	}
2778	sc->sc_tx_timer = 0;
2779	ifp->if_opackets++;
2780	ifp->if_drv_flags &= ~IFF_DRV_OACTIVE;
2781}
2782
2783static void
2784uath_bulk_tx_callback(struct usb2_xfer *xfer)
2785{
2786	struct uath_softc *sc = xfer->priv_sc;
2787	struct ifnet *ifp = sc->sc_ifp;
2788	struct uath_data *data;
2789
2790	UATH_ASSERT_LOCKED(sc);
2791
2792	switch (USB_GET_STATE(xfer)) {
2793	case USB_ST_TRANSFERRED:
2794		data = STAILQ_FIRST(&sc->sc_tx_active);
2795		if (data == NULL)
2796			goto setup;
2797		STAILQ_REMOVE_HEAD(&sc->sc_tx_active, next);
2798		UATH_STAT_DEC(sc, st_tx_active);
2799		uath_data_txeof(xfer, data);
2800		STAILQ_INSERT_TAIL(&sc->sc_tx_inactive, data, next);
2801		UATH_STAT_INC(sc, st_tx_inactive);
2802		/* FALLTHROUGH */
2803	case USB_ST_SETUP:
2804setup:
2805		data = STAILQ_FIRST(&sc->sc_tx_pending);
2806		if (data == NULL) {
2807			DPRINTF(sc, UATH_DEBUG_XMIT, "%s: empty pending queue\n",
2808			    __func__);
2809			return;
2810		}
2811		STAILQ_REMOVE_HEAD(&sc->sc_tx_pending, next);
2812		UATH_STAT_DEC(sc, st_tx_pending);
2813		STAILQ_INSERT_TAIL(&sc->sc_tx_active, data, next);
2814		UATH_STAT_INC(sc, st_tx_active);
2815
2816		usb2_set_frame_data(xfer, data->buf, 0);
2817		xfer->frlengths[0] = data->buflen;
2818		usb2_start_hardware(xfer);
2819
2820		UATH_UNLOCK(sc);
2821		uath_start(ifp);
2822		UATH_LOCK(sc);
2823		break;
2824	default:
2825		data = STAILQ_FIRST(&sc->sc_tx_active);
2826		if (data == NULL)
2827			goto setup;
2828		if (data->ni != NULL) {
2829			ieee80211_free_node(data->ni);
2830			data->ni = NULL;
2831			ifp->if_oerrors++;
2832		}
2833		if (xfer->error != USB_ERR_CANCELLED) {
2834			xfer->flags.stall_pipe = 1;
2835			goto setup;
2836		}
2837		break;
2838	}
2839}
2840
2841static device_method_t uath_methods[] = {
2842	DEVMETHOD(device_probe, uath_match),
2843	DEVMETHOD(device_attach, uath_attach),
2844	DEVMETHOD(device_detach, uath_detach),
2845	{ 0, 0 }
2846};
2847static driver_t uath_driver = {
2848	"uath",
2849	uath_methods,
2850	sizeof(struct uath_softc)
2851};
2852static devclass_t uath_devclass;
2853
2854DRIVER_MODULE(uath, uhub, uath_driver, uath_devclass, NULL, 0);
2855MODULE_DEPEND(uath, wlan, 1, 1, 1);
2856MODULE_DEPEND(uath, usb, 1, 1, 1);
2857