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