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